DEV Community

Cover image for A complete guide to the Browser console
Samuel Egbajie
Samuel Egbajie

Posted on • Updated on

A complete guide to the Browser console

In this article, you will learn the A to Z about the console object. Everything you need to know about the Console in JavaScript, including how to use it to format output, and how to use it to debug your code. You will also learn all the features of the console object, additional styling options and using string substitution to format output.

Prerequisites

Basic knowledge of JavaScript is required or Be console friendly.

what is a console in javascript?

A console is a global object that is used to output data to the console environment in the browser or the Nodejs command line interface.

This is a very useful tool for debugging and testing your code.It is also used to output data to the browser console in a more readable format.
This object is available in the global scope and is made up of 24 methods as at 6th of February 2022.

To check out the methods, you can use the console.log (Object. keys (console). length) in any console environment to check out the number of methods available and also console.log(console) to check out all the current available console object methods.

How to open a console in a Browser?

For different browsers and operating systems, there are different ways to open a console.
These are:

  • For Google Chrome, open the Chrome Menu in the upper-right-hand corner of the browser window and select More Tools > Developer Tools.
    You can also use Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux).

  • For Firefox, click on the Firefox Menu in the upper-right-hand corner of the browser and selects More Tools > Browser Console.
    You can also use the shortcut Shift + ⌘ + J (on macOS) or Shift + CTRL + J (on Windows/Linux).

  • For Microsoft Edge, open the Edge Menu in the upper-right-hand corner of the browser window and select More Tools > Developer Tools.
    You can also press CTRL + Shift + i to open it.

  • For other browsers, kindly check out their documentation.

How to use the console object


1. console.log ()

The easiest way to use the console is to use the console.log() function on your browser console.

example 1: Passing in a simple single argument of any data type.



console.log ("Hello World");


Enter fullscreen mode Exit fullscreen mode

This would simply output the text “Hello World” to the console.
Something to note is that the console will output any data type that is passed in. For instance, if you pass in a number, it will output the number. If you pass in a string, it will output the string. If you pass in an object, it will output the object in a readable format.

example 2: Passing in multiple arguments

The console.log() function can take in any number of arguments and will output them to the console.
It also outputs the arguments to the console in a readable format.



console.log("Hello World", true, false, null, [1,3,4], {test:"test"},  undefined) 
//returns    "Hello World" true false null [ 1, 3, 4 ] { test: 'test' } 




Enter fullscreen mode Exit fullscreen mode

console.log example
The console will output the arguments in a readable format.

example 3: Performing logics, arithmetic operations or string concatenations.

console.log allows logic, string concatenation or mathematical operations to be performed inside it and returns the result



console.log(1>2) // returns false
console.log(10-6) // returns 4
console.log("I am "+ "Learning") // returns "I am Learning"



Enter fullscreen mode Exit fullscreen mode

example 4: Perfoming Strings Styling like the css to html



console.log("%c I am a blue text on a black background.", "color:blue; background-color:black")


Enter fullscreen mode Exit fullscreen mode

console styling
The above example we uses %c to specify that we have styles to add which are later added as the second arguments of the console.log method.

example 5: Perfoming String Substitution



console.log("Hi %s, my name is %s and i am %d years old", 'world', 'Joe', 10)


Enter fullscreen mode Exit fullscreen mode

string substitution example
The above example takes in a string as the first argument which also contains %s and %d, making the statement not clear. This shows that, the second, third and forth arguments are to replace the %s and %d values. but what makes the two different? s% can only take in a string and %d takes in a digit.


2. console.table()

The console.table()function is used to output data to the console in a tabular format unlike the console.log() that logs out all data as inputted. It takes in an array of objects, an Array or an Object and outputs them to the console in a tabular format.



let arr= [1,2,3, "a","b", "c"];
let obj= {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
let arrOfObj = [
    { name: 'shark', likes: 'ocean' },
    { name: 'turtle', likes: 'pond' },
    { name: 'otter', likes: 'fish biscuits' }
];


Enter fullscreen mode Exit fullscreen mode

The above code sample would be used to illustrate how codes would output on console.log() vs console.table()

- example 1: console.log(arr) vs console.table(arr)

array log example

- example 2: console.log(obj) vs console.table(obj)

object log example

- example 3: console.log(arrOfObj) vs console.table(arrOfObj)

array of object log example

The difference between the console.log and the console.table is that, the console.log outputs Arrays and Objects just the way they are, while the console.table presents them in a tabular format.
A very important use case for this is when testing an API with a list of data. This makes it more readable.


3. console.clear()

The console.clear() function is used to clear the console. It is very useful when you are debugging and you want to clear the console before you start writing your code.
example:



console.log("Hello World Before Clear");
console.clear()
console.log("Hello World After Clear");


Enter fullscreen mode Exit fullscreen mode

This would clear the console with the text "Hello World Before Clear" and would output only "Hello World After Clear".


4. console.assert()

The console.assert() function is used to check if a condition is true or false. If the condition is false, it will output an error message to the console, but if it is not, it will do nothing.

- example 1:



console.assert(1 === 1, "1 is not equal to 1")


Enter fullscreen mode Exit fullscreen mode

This would output nothing to the console because the condition is true, since integer is equal to integer 1

- example 2:



console.assert(1 === 2, "1 is not equal to 2")


Enter fullscreen mode Exit fullscreen mode

console.assert example
This would output the following to the console: "1 is not equal to 2"because the condition is false.


5. console.log() Aliases:

console.error(), console.warn(), console.info(), console.debug()

There are 4 console.log() aliases because there are 4 different types of messages that can be outputted to the console. There are aliases because there work like the console.log but the functions are used to output data to the console in a different format and/or background colors.

  • The console.error() function is used to output an error message to the console.
  • The console.warn() function is used to output a warning message to the console.
  • The console.info() function is used to output an informational message to the console.
  • The console.debug() function is used to output a debugging message to the console. These functions are all very similar to the console.log() function.

The only difference is that they output renders in a different format, background colors or the left icon which may vary from browser to browser.
These are all aliases for the console.log() function.

example



console.info('Console Info')
console.debug('Console Debug')
console.warn('Console Warn')
console.error('Console Error')


Enter fullscreen mode Exit fullscreen mode

console aliases
The above is a representation of the console.log aliases behavior on the Google Chrome browser which indicates the exhibition of the console.error on a red background color and console.warn on a yellow background color.
The colors and behavior varies from browsers to browser and it is more informative than just using the console.log.


6.  The Time Tracking Logs

console.time(), console.timeLog() and console.timeEnd()

The time tracking Logs in the console are used to track the time it takes to run a piece of code.
There are 3 functions that are used to track the time.

  • The console.time() function is used to start a timer in a console, it should be placed at the beginning a process. It takes in a label as an argument which is of string data type. This label act as an identifier of whatever process time interval you want to track.
  • console.timeLog() function is used to output processing time to the console at a each interval interval. If you only want to track the total time, you might not need the console.timeLog() function. It also takes in the same argument as the console.time().
  • The console.timeEnd() function is used to stop a timer and output a message to the console of the total time to run the process.It also takes in the same argument as the console.time().

Note: The reason why we use the same argument for the console.time() and console.timeEnd() is because we want to track the time of a process. if we want to track the time of another process, we can use the same label.



// Our label here is Track Time
console.time("Track Time") //Here is our time tracking begins

for (let i = 0; i < 5; i++) {
    // some code
    console.log(i)
    console.timeLog("Track Time") // This is what keeps track of time after each loop

  }

  console.timeEnd("Track Time"); // Here is where our time tracking ends


Enter fullscreen mode Exit fullscreen mode

console.time() example

The above example shows time tracked after each loop, from 0 to 4, while the last shows the total time tracked after the whole process.
A good use case for using the time tracking logs is when trying to compare the speed of algorithms to enable you make use of the most efficient.


7. The Counter Logs

console.count() and console.countReset()
The counter logs in the console are used to count the number of times a piece of code is executed.
There are 2 functions that are used to count the number of times a piece of code is executed.

  • The console.count() function is used to output a message to the console and start a counter.
  • The console.countReset() function is used to output a message to the console and reset the counter.

The Count Tracker Logs also takes in a label as a argument. In this below example, we named in the "Count Track".

example:



//console.count()
function Counter1(){
    console.count("Count Track")
}

function Counter2(){
    console.count("Count Track")  
}
Counter1()
Counter1()
Counter2()
Counter2()
Counter1()
//console.countReset()
console.countReset("Count Track")

//counts after reset
Counter2()
Counter1()


Enter fullscreen mode Exit fullscreen mode

Count Trackers Result

From the result above, Counter1 and Counter2 functions tracked the count using the console method console.count() with a label "Count Track" at each function call up to 5 times till the console.countReset() method was introduced with the same label as the console.count().
The count restarted after the countReset was called.


8. The Grouping Logs

console.group(), console.groupEnd() and console.groupCollapsed()
The grouping logs in the console are used to group a set of logs together.
There are 3 functions and are used to group a set of logs together.

  • The console.group() function is used to output a message to the console and start a group.
  • The console.groupEnd() function is used to output a message to the console and stop a group.
  • The console.groupCollapsed() function is used to output a message to the console at any group level, but is is collapsed by default.

example :



console.log("This is the outer level which is Level 1");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.log("More of level 3");
console.groupCollapsed()
console.log("test collapse");
console.log("test collapse2");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");


Enter fullscreen mode Exit fullscreen mode

Grouping on console

The above displays the result of the grouped codes. The result shows levels of each group formed using the console.group() method. at every time the console.group() method was called, a new group was created, at any point a groupEnd() was called, the last group was taken off.
The groupCollapsed maintained any group it found itself except gave birth to children which where collapsed by default.


9. console.trace()

The console.trace() function is used to output a stack trace to the console.
This is very useful when you are debugging and you want to see the stack trace of the error.

example :



 function showTrace(){
  function foo() {
    function bar() {
        console.trace("show me traces")    }
    bar();
  }

  foo();
  }
    showTrace()


Enter fullscreen mode Exit fullscreen mode

console.trace() example

The above example shows stack trace of the in order of the last child to the parent function. A good use case for it is when debugging to sort the origin of a certain stack.


10. console.dir()

The console.dir() is used to output all the properties of a javascript object to the console. This is very useful when you are debugging and you want to see the properties of an object. It outputs the properties of an object in hierarchical format.

Conclusion

The console environment can be utilized to output data in more useful, customized and readable format beyond just the console.log.

I hope it has helped 😀 😀 😀
Thanks for reading and Happy coding!!!

You can also check out My other article onDebouncing in Javascript using a custom function or Lodash library.

Top comments (2)

Collapse
 
manuartero profile image
Manuel Artero Anguita 🟨

cool guide! didn't know about the grouping feature, seems to be specially useful for structuring... going to start using it for sure :)

Collapse
 
codepapi profile image
Samuel Egbajie

Yeah, a lot of good struff.
Thanks for reading