BLOG

Little Tips about Console

7/11/2017Time to read: 2 min

I just read an article by Christian Heilmann. He did a poll on Twitter and it showed that 67% of developers uses console.log to debug their JavaScript instead of some more advanced tools such as debugger or breakpoints. I will shamelessly say that, I am one of those 67%. In this short post, I will share some tips about console that I discovered recently.

console.clear

console.clear() clear everything from the console. This is extremely useful when you are using some online editors such as CodePen. CodePen will keep running the JavaScript everytime you make a change, while all the error messages and console logs are just appended to the console. Having a console.clear() at the top of your JS panel will make debugging much easier.

console.clear

Note that in Node's interactive console, there is no console.clear. To clear the screen, you can use

process.stdout.write('\033c');

033c is an escape code for reseting the terminal. This might or might not work depending on your platform. For more explanation, see this StackOverflow answer.

console.group

You can group your console logs, and each group will appear as a collapsible section in dev console. The syntax for group is

console.group([label]); // label is an optional argument for the name of the group
// your console logs
console.groupEnd(); // groupEnd will close the current group.

Using group will initially render the groups expanded. If you want them collapsed, just replace console.group with console.groupCollapsed.

You can also nest groups to create some really complex console outputs (Really? I would rather spend my time feeding cats).

console group

Substitution in console.log

Before we discuss substitution, do you know console.log can take multiple arguments? Like you can do console.log(firstNumber, '+', secondNumber, '=', sum), so you don't need to use string concatenations.

I just found that console.log supports substitution.

console.log(msg [, subst1, ..., substN]);

Here is an example

console.log('PI is %f', Math.PI); // PI is 3.141592653589793

For more information on substitution, check here.

However, when I test, chrome doesn't respect some more advanced formatting, for example console.log('PI is %.2f', Math.PI) will give the same result, instead of truncating the number.

Those Silly Games We Played in the College Dorm
Joining Veeva