In Javascript, the console is an object which provides access to the browser debugging console. As web developers, we use console.log
to diagnose and troubleshoot issues in our code. In this article, I am planning to give you an introduction to the console object.
If you type console in the DevTools, You can find out all the methods for the console object:
Displaying information:
console.log('hello log'); console.info('hello info'); console.warn('hello warning'); console.error('hello error');
Example:
console.log : Displaying general output of logging information.
console.info : Displaying informative logging of information
console.warn : Displaying warning message
console.error : Displaying error message
2. Using string substitutions:
We can use string substitutions for console.log()
,console.info()
,console.warn()
,console.error()
. Console object only support 4 types of string substitutions.
%o
: Outputs an objectlet person = {name: 'Joe',age:18}; console.log('%o',person);
%d
or%i
: Outputs an integerconsole.log('I ate %d cookies, %d ice cream yesterday', 3,1);
%s
: Outputs a stringlet str = 'friend'; console.log('hello %s','world'); console.log('hello %s', str);
%f
: Outputs a floating-point value:console.log('The PI number is: %f', 3.14159126);
3. Asserting: Log a message and stack trace to console if the first argument is false. This is a relatively easier way compare to wrap the console.log() inside a if statement.
let flag = false;
console.assert(flag,'flag is false');
4. Counting : Log the number of times this line has been called.
for (let i = 0; i < 10; i ++){
console.count();
}
we can also label the timer by giving parameter when we calling the console.count('label')
.
5. Track Time : We use console.time
and console.timeEnd
to track how long to wrong a block of code.
console.time();
for(let i = 0; i < 10000; i++ ){
}
console.timeEnd();
we can also label the timer by giving parameter when we calling the console.time('label')
.
6. Tables: Display tabular data as a table.
console.table([
{ id:1, name: 'rick', age: 14 },
{ id: 2, name: 'morty', age: 70 }
])
7. Groups: Create a new inline group, we use console.group()
to start grouping and we end a group with console.groupEnd()
.
console.group('group level 1');
console.log('level 1 information 1');
console.log('level 1 information 2');
console.group('group level 2');
console.log('level 2 information 2');
console.log('level 2 information 2');
console.log('level 2 information 2');
console.groupEnd();
console.groupEnd();
Reference: