Console Methods

Five console methods that will help you be a better programmer

Console Methods

Hello Everyone 👋. Utill now you must have must have used console.log() method to display something in console of browser or in node, but today I will tell you about 5 methods which will help you display things in better way so sit back and give it a read.

console.error()

console.error() is also used to print something same as console.log() but the browser console hightlights the console.error() method, because of which it can be used for debugging, and more serious stuff which you dont want to ignore while you look at console which so many other things consoled too. error.png

console.table()

We all have worked with arrays and objects at some point of our life, consoling it and going through all the properties and values sometimes can be painfull, here you can use console.table() to view you object and array in very nice and clean Table form. table.png

console.time() & console.timeEnd()

Sometimes we want to calculate the time the function is taking to run or a loop taking to complete itself, here I want to add something the time taken by the program to run on your system may not always be same as time taken to run the same function or loop on your friends system, here all I want to say is every system is different and their background process are different, below you will find how to write these methods and the output of the same code snippet.

console.time()
for(let i=0; i<100000; i++){
  // do nothings here
}
console.timeEnd()

time & timeEnd.png

console.trace()

As the name itself suggest the console.trace() gives a visual trace in stack flow which tells us how a certain function is been called and what is the path to that function for eg,

function firstFn(){
  secondFn();
}
function secondFn(){
  thirdFn()
}
function thirdFn(){
  console.trace();
}
firstFn();

At first firstFn() will run and will call secondFn() which will run and then it will call thirdFn() which has the trace method in it which will now show the trace in console trace.png here anonymous is nothing but gobal execution context.

console.assert

Sometimes you want to display something only when it is false or undefined, then console.assert is the way to go, console.assert takes two parameter, first is the expression & second can be anything you want to display, console.assert will work for values like false, undefined, NaN, 0, null but it will never work for true.

let expression = false;
console.assert(expression, 'false');

expression = null;
console.assert(expression, 'null');

expression = undefined;
console.assert(expression, 'undefined');

expression = NaN;
console.assert(expression, 'NaN');

expression = 0;
console.assert(expression, '0');

expression = true;
console.assert(expression, 'true will not work');

expression = 1;
console.assert(expression, '1 will not work');

assert.png

Thank You for giving it a read🥳, I hope you liked it😁!

See you soon, Byee👋