console clarification 🔍
Tags: javascript, codenewbie, node, beginners
Published: 2020-08-19 14:07:31



The most web developers(including me) are using console object for debugging. In my point of view, the console object is one of the best ways for the debugging process. Here we are going to see some interesting uses of the console object.

# console.log

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Most of them are using `console.log`. It prints the output for what we are giving.
```javascript
let number = 10;
let str = 'alwar';
console.log(number, str) // 10, alwar
```

# console.assert
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; It prints the given message only when the given assertion is false. This is really useful for printing the error message with some conditions 😎. For example, I want to check the number based on the following conditions

* Greater than 10
* Less than 100
* Is it Even number

```javascript
function checkNumber(num) {
   console.assert(num > 10, 'Number is less than or equal to 10');
   console.assert(num < 100, 'Number is greater than or equal to 100');
   console.assert(num%2 === 0, "It's an odd number");
}
```
If we give 24 as the number it will print nothing, because it satisfies all of the above conditions. But if we give 13, we will get the output as
```
 Assertion failed: It's an odd number
```
It doesn't print the other two assertions. Because it satisfies the other two assertion's conditions.

# console.clear
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; It clears the console panel.Let's see one interesting scenario about this method. Let's consider we have two functions. Function 2 executes based on some condtion in function 1.
```javascript
  funtion func1(num) {
    let isEven = num%2 === 0;
    let isBigNumber = num > 10;
    let isNotVeryBigNumber = num < 100;

    console.assert(isBigNumber, 'Number is less than or equal to 10');
    console.assert(isNotVeryBigNumber, 'Number is greater than or equal to 100');
    console.assert(isEven, "It's an odd number");
    
   if(isEven) {
      func2(num)
   }
  }
  function func2(num) {
   console.clear();
   console.assert([44, 68].includes(num), "It's not present in the list");
  }
``` 
Here we are printing some assertions in `function 1` and call the function 2  only when the number is even. While calling `function 2` I don't want to see other details. That's why I am using the `console.clear` method to clear the previous assertions

# console.count
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It logs the number of times that this particular call to count() has been called. Suppose, if you are working on a big project with many collaborators, then you may need this feature 💪. In that project, you are working on one function and you want to know how many times this function has been called with the same value. That time `console.count` will help.
```javascript
let sum = 0;
function getSum(num) {
  console.count(`number: ${num} occurence`);
  sum += num;
}
let arr = [2, 4, 1, 4, 2];
arr.forEach((num) => getSum(num));
```
Here we got the output as 

```
   number: 2 occurence: 1
   number: 4 occurence: 1
   number: 1 occurence: 1
   number: 4 occurence: 2
   number: 2 occurence: 2
```

Here numbers 2, 4 have two occurrences.

# console.countReset
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Now we know what is count. In some cases, we want to reset the count of the particular value. For example, We want to compute the sum from two arrays. And we know occurrences of one array but we don't know occurrences of another array. We want to know occurrences of another array. Here `console.countReset` comes into play.
```javascript
let sum = 0;
function getSum(num) {
  console.count(`number: ${num} occurence`);
  sum += num;
}

let arr1 = [1, 2];
arr1.forEach((num) => getSum(num));
console.countReset(`number: 1 occurence`);
console.countReset(`number: 2 occurence`);

// Some other location
let arr2 = [2, 4, 1, 4, 2];
arr2.forEach((num) => getSum(num));
```

It will print the output as

```
number: 1 occurence: 1
number: 2 occurence: 1
number: 2 occurence: 1
number: 4 occurence: 1
number: 1 occurence: 1
number: 4 occurence: 2
number: 2 occurence: 2
```
Here the arr2 starts from the third line. Even though we already printed the occurrences of similar arr1 values, while start the printing for arr2 values it will print from the initial occurrence. Because we give countReset for the values of 1 and 2.
#### Note:
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  count and countReset labels should be same

# console.dir
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It displays the interactive list of properties of the given object. The most common scenario is the DOM object. Like we want to know the values like class names, parent element, child element, etc.. while viewing the particular webpage. You can copy the below code with available element Id and paste it to some website console, you can see get the directory structure of the distinct element.

```javascript
 let ele = document.getElementById('MyEle');
 console.dir(ele);
```
# console.err
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It shows the error message to the Web Console.

```javascript
 function isEven(num) {
   let isEven = num%2 === 0;
   if(!isEven) {
      console.err('Wrong number');
   }
  return isEven;
 }
```
In this code, it will print the error as the Wrong number.
# console.info
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It shows an informational message to the Web Console. This is really useful for mentioning which part of the code is currently executed. Consider the below code

```javascript
function getOutput(num) {
let res = num;
res = res + 10;

if (res > 50) {
  res = res -10;
  console.info('Subraction is done');
}
return res;
}
```
Here it will print the message only when the result is greater than 50.

# console.warn
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It outputs a warning message to the Web Console. This is really useful for writting the code in the node js environment. Let's say you are upgrading your npm package from version 1 to version 2. Here you are implementing new methods that are faster than the previous methods and next update you want to remove those slow performance methods. So you should warn your users to change your old methods. Here `console.warn` will do the important task 🔥
##### Version 1:
```javascript
function getIndex(number) {
  let output;
  for(let i = 0; i< arr.length; i++) {
     if(number === arr[i]) {
       output = i;
     }
  }
  return output;
}
```

##### Version 2:
```javascript
function getIndex(number) {
  console.warn('Use getFasterIndex instead of getIndex. In the next update this function will be removed');
  let output;
  for(let i = 0; i< arr.length; i++) {
     if(number === arr[i]) {
       output = i;
     }
  }
  return output;
}

function getFasterIndex(number) {
  return arr.findIndex((ele) => ele === number);
}

```
In version 2 we are warning the user to use `getFasterIndex` instead of `getIndex`.

#### How error, info, warn differs from console.log?
These are almost equal to `console.log`. But the point is we can write the code with more `semantical` meaning 🔥.

# console.group, console.groupCollapsed and console.groupend
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Grouping the messages under some section is really useful for segregating the console messages 💡. `console.group` creates the new group, `console.groupEnd` ends the current group. `console.groupCollapsed` is same as `console.group`, except the group is initially closed when it's logged to the Console.

```javascript
console.group('Errors');
console.error('this method is not defined');
console.error('Browser will not support this feature');
console.groupEnd();
console.groupCollapsed('Warnings')
console.warn('You Should update your package');
console.warn('More info will give more result');
console.groupEnd();

```
It will give the output as 
![console-grouping](https://i.imgur.com/0PABBlz.png)

# console.table
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It displays the tabular data as table(array or object). Suppose you have a situation like you want to see the properties with values quickly instead of logging the object and opening it to view the properties with the values 😜. for these situations, you can use this feature.
```javascript
let infoObj = {
  name: 'Alwar', 
  age: 23,
  'marital-status': 'single', 
  education: 'B.E(ECE)', 
  skills: 'HTML, CSS, JS',
  country: 'India'
};
console.table(infoObj);
```
It will give the output as
![console-table](https://i.imgur.com/yiBzum6.png)
# console.trace
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  It displays the stack trace to the Web Console. I personally loved this feature, because we can able to track the flow of the code with the help of this feature ✨.
```javascript
  function func1() {
    func2();
  }

  function func2() {
    func3();
  }

  function func3() {
    console.trace();
  }

  func1();
```

Here we are getting the output as 

![console-trace](https://i.imgur.com/Xq3e7Pf.png)

# console.time and console.timeEnd
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Actually this is the coolest feature in the console API. Because we can able to monitor the performance(how much time will it take to complete the task) with the help of these features 🔥. For example, we have the following two codes. I want to check which code gives the good performance.
##### code 1:
```javascript
console.time('variable scope test');
let a = 10;
function getElement() {
  console.log(a);
}
console.timeEnd('variable scope test');
```
##### code 2:
```javascript
console.time('variable scope test');

function getElement() {
  let a = 10;
  console.log(a);
}
console.timeEnd('variable scope test');
```
`code 1` gives the output as _variable scope test: **0.86181640625ms**_ and `code 2` gives the output as _variable scope test: **0.005126953125ms**_. Therefore we can conclude the `code 2` is faster than `code 1`. If you want to know how `code 2` deserves a good performance, then read the below post.
{% link https://dev.to/alwarg/how-variable-scoping-affects-the-performance-4eg2 %}

I hope you enjoyed this post 🙏. I personally believe that ***better code comes from better debugging.*** Here I have consolidated the console debugging process. Maybe you are from a different debugging process. Feel free to post your commands if you want to share something and also remember that reading the post without reaction is injurious to writers 😜.