DEV Community

Cover image for console clarification 🔍
Alwar G
Alwar G

Posted on

console clarification 🔍

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

       Most of them are using console.log. It prints the output for what we are giving.

let number = 10;
let str = 'alwar';
console.log(number, str) // 10, alwar
Enter fullscreen mode Exit fullscreen mode

console.assert

       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
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");
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

It doesn't print the other two assertions. Because it satisfies the other two assertion's conditions.

console.clear

       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.

  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");
  }
Enter fullscreen mode Exit fullscreen mode

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

       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.

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));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Here numbers 2, 4 have two occurrences.

console.countReset

       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.

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));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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:

       count and countReset labels should be same

console.dir

       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.

 let ele = document.getElementById('MyEle');
 console.dir(ele);
Enter fullscreen mode Exit fullscreen mode

console.err

       It shows the error message to the Web Console.

 function isEven(num) {
   let isEven = num%2 === 0;
   if(!isEven) {
      console.err('Wrong number');
   }
  return isEven;
 }
Enter fullscreen mode Exit fullscreen mode

In this code, it will print the error as the Wrong number.

console.info

       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

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

if (res > 50) {
  res = res -10;
  console.info('Subraction is done');
}
return res;
}
Enter fullscreen mode Exit fullscreen mode

Here it will print the message only when the result is greater than 50.

console.warn

       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:
function getIndex(number) {
  let output;
  for(let i = 0; i< arr.length; i++) {
     if(number === arr[i]) {
       output = i;
     }
  }
  return output;
}
Enter fullscreen mode Exit fullscreen mode
Version 2:
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);
}

Enter fullscreen mode Exit fullscreen mode

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

       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.

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();

Enter fullscreen mode Exit fullscreen mode

It will give the output as
console-grouping

console.table

       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.

let infoObj = {
  name: 'Alwar', 
  age: 23,
  'marital-status': 'single', 
  education: 'B.E(ECE)', 
  skills: 'HTML, CSS, JS',
  country: 'India'
};
console.table(infoObj);
Enter fullscreen mode Exit fullscreen mode

It will give the output as
console-table

console.trace

       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 ✨.

  function func1() {
    func2();
  }

  function func2() {
    func3();
  }

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

  func1();
Enter fullscreen mode Exit fullscreen mode

Here we are getting the output as

console-trace

console.time and console.timeEnd

       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:
console.time('variable scope test');
let a = 10;
function getElement() {
  console.log(a);
}
console.timeEnd('variable scope test');
Enter fullscreen mode Exit fullscreen mode
code 2:
console.time('variable scope test');

function getElement() {
  let a = 10;
  console.log(a);
}
console.timeEnd('variable scope test');
Enter fullscreen mode Exit fullscreen mode

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.

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 😜.

Top comments (0)