Introduction of Console object in Javascript

ยท

2 min read

Introduction of Console object in Javascript

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:

image.png

  1. Displaying information:

    console.log('hello log'); 
    console.info('hello info');
    console.warn('hello warning');
    console.error('hello error');
    

    Example:

    image.png

  2. console.log : Displaying general output of logging information.

  3. console.info : Displaying informative logging of information

  4. console.warn : Displaying warning message

  5. 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 object

    let person = {name: 'Joe',age:18};
    console.log('%o',person);
    

    image.png

  • %d or %i: Outputs an integer

    console.log('I ate %d cookies, %d ice cream yesterday', 3,1);
    

    image.png

  • %s: Outputs a string

    let str = 'friend';
    console.log('hello %s','world');
    console.log('hello %s', str);
    

    image.png

  • %f: Outputs a floating-point value:

    console.log('The PI number is: %f', 3.14159126);
    

    image.png

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

image.png

4. Counting : Log the number of times this line has been called.

for (let i = 0; i < 10; i ++){
console.count();
}

image.png

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

image.png

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 }
])

image.png

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

image.png

Reference:

ย