A complete guide to the Browser console
Tags: javascript, console, beginners, programming
Published: 2022-02-07 15:02:30

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.  <u>console.log ()</u>

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.

```js
console.log ("Hello World");
```
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.
```js
console.log("Hello World", true, false, null, [1,3,4], {test:"test"},  undefined) 
//returns    "Hello World" true false null [ 1, 3, 4 ] { test: 'test' } 


```
![console.log example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2dr5hpu11ylkig0c5hk.png)
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
```js
console.log(1>2) // returns false
console.log(10-6) // returns 4
console.log("I am "+ "Learning") // returns "I am Learning"

```

#### example 4: Perfoming Strings Styling  like the css to html
```js
console.log("%c I am a blue text on a black background.", "color:blue; background-color:black")
```
![console styling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kjg03514lsa1v7f4ldh6.png)
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

```js
console.log("Hi %s, my name is %s and i am %d years old", 'world', 'Joe', 10)
```
![string substitution example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59gnk39b0nhremtxj0wl.png)
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.  <u> console.table()</u>
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.

```js
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' }
];
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ki2y7x4crqod4n8k85h8.png)

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

![object log example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/muesy3nzfjmig1quyutx.png)

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

![array of object log example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tpeddxyckb8t7jl478ja.png)

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.  <u> console.clear()</u>
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: 

```js
console.log("Hello World Before Clear");
console.clear()
console.log("Hello World After Clear");
```
This would clear the console with the text `"Hello World Before Clear"` and would output only `"Hello World After Clear"`.

---
### 4.  <u> console.assert()</u>
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: 

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

This would output nothing to the console because the condition is true, since integer is equal to integer 1 
 
#### - example 2: 
```js
console.assert(1 === 2, "1 is not equal to 2")
```
![console.assert example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f9gi5jw9wg2msxz7ahvw.png)
This would output the following to the console:   `"1 is not equal to 2" `because  the condition is false.

---
### 5.  <u>console.log() Aliases</u>:
 <u>console.error(), console.warn(), console.info(), console.debug()</u>

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. 
- <u> The console.error() </u> function is used to output an error message to the console.
- <u>  The console.warn() </u> function is used to output a warning message to the console.
-  <u> The console.info() </u> function is used to output an informational message to the console.
- <u>  The console.debug() </u> 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

```js
console.info('Console Info')
console.debug('Console Debug')
console.warn('Console Warn')
console.error('Console Error')
```
![console aliases](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e1bm2mwishyjwiflhr6j.png)
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.  <u>The Time Tracking Logs</u>
#### <u> console.time(), console.timeLog() and console.timeEnd() </u>
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.
- <u>  The console.time() </u> 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.  
- <u>  console.timeLog() </u> 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()`.
- <u> The console.timeEnd() </u> 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.

```js
// 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
```
![console.time() example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jsdmmcwm4zpb1at35ui6.png)

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.  <u> The Counter Logs </u>
<u>console.count() and console.countReset() </u>
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.
- <u>The console.count()</u> function is used to output a message to the console and start a counter. 
- <u>The console.countReset()</u> 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: 

```js
//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()
```
![Count Trackers Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vg6mnk957p7dse6tcjce.png)

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.  <u> The Grouping Logs </u>
<u>console.group(), console.groupEnd() and  console.groupCollapsed()</u>
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.

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

#### example :
```js
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");
```
![Grouping on console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j1glrmtgwj8ciixtlo8c.png)

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.  <u>console.trace()</u>
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 : 

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

![console.trace() example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2um9jhcwmy5i4cwc691r.png)

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.  <u>console.dir()</u>
<u>The console.dir()</u> 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 on[Debouncing in Javascript using a custom function or Lodash library.](https://dev.to/codepapi/debouncing-in-javascript-using-a-custom-function-or-lodash-library-lah)