The Console API.
Tags: javascript, beginners
Published: 2022-08-12 02:37:39

---
title: The Console API.
published: true
description: Know the functions of the console object that makes debugging a lot faster.
tags: JavaScript, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fxmuall737iok5vukwuf.jpg
---

The ability to spend less time finding errors in a code is a necessary skill that every developer should have.

The Console API, a debugging tool that is part of the browser, provides developers with some functions that make it possible to find these errors.

I wrote this article to show web developers some of the functions that come with the console object and what they are used for. Hopefully, you will find it useful when debugging your code.

## Console.log()

This is the most popular console method. It converts its arguments (which are separated by commas) to strings and logs them to the web console. In the console, it inserts spaces between the arguments and starts a new line after outputting all arguments.

!["An output of the console"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/01s7difyknboreqy61xg.jpg)

Other similar functions include:
* **Console.debug()** 
* **Console.info()** 

Normally, the browser doesn't show debug statements and would return undefined. This is because console.debug() was created to be used in development areas only and should not be shown to users.  However, this can be changed by enabling "verbose" in the default levels.             
!["Make debug visible"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1l81qayi6uxpfe03k4oc.jpg)

> **Note:** When logging objects to the console from an IDE what gets logged is a reference to the object and not the value of the object when `console.log` is called, but the value of the object after the console is opened.

## Console.warn()
The `console.warn()` method outputs a warning message to the web console. It usually starts with an exclamation icon.

```js
let x = 3;
if (x == 3) {
    console.warn("This value might be too low");
}
```
!["A warning message from the console"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/va8c090fp1tcfwg1et3n.jpg)

`console.warn` is used for displaying messages that might not necessarily cause a breakdown in the application but to show something that the user should be aware of. For example, if an API is deprecated, `console.warn` can be used to send a message across to the user.

## Console.error()
The `console.error()` function outputs an error message to the console (we have all gotten this one).  

```js
let x = "3";
if (!Number.isInteger(x)) {
    console.error(`${x} is not a number`);
};
```
!["An error message from the console"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjdsdnktcjq3q7b7ordy.jpg)

`console.error()` is used for building libraries so that the user is aware of the reason their code might not be working as expected.

## Console.assert()
The `console.assert` function takes two arguments. The first argument is a block of code that is either true or false while the second argument is the message to be printed to the console.

If the first argument is true the function does nothing, but if it is false, the second argument is printed to the console with an Assertion failed" prefix. 

```js
const numbers = [1,"2",3,"4",5,"6"];
for (element in numbers) {
    console.assert(Number.isInteger(numbers[element]), `${numbers[element]} is not a number`);
}
```
!["Assertion failed console message"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fj02lmig6dqzk6ikgbtd.jpg)


## Console.clear()
`console.clear` is used for clearing the console. This is useful when you want to clear other console statements before displaying a new one.

```js
function show() {
    console.clear();
    console.log("...checking line 2");
    console.log("...checking line 5");
    console.log("...checking line 6");
}

function clear() {
    console.clear();
    console.log("...checking line 13");
}

show();
clear();
```
!["Clearing the console"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fkbeotxbafareacdtnqh.jpg)

## Console.table()
`console.table` takes one argument which is an object or an array and displays it in a tabular form.

If its argument is an array, the first column will represent the indices of the array and the second will be the values.

```js
const color = ["blue", "red", "yellow","green", "purple"];
console.table(color);
```
![Displaying an array with console.table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vt85enu9s4eptsx77rd1.jpg)

If its argument is an object, the first column will represent the properties of the object and the second column the values.

```js
const color = {
    primary : "red",
    secondary : "purple",
    tertiary : "violet"
}
console.table(color);
```
![Displaying an object with console.table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7592sjzer5jcdkxcm3l3.jpg)

If its argument is an array of objects, the first column will represent the indices of each object, and the remaining columns will be the properties of the object.

```js
const members = [
    {
        name: "Micheal",
        age : 21,
        isPresent : true
    },
    {
        name : "David",
        age : 18,
        isPresent : false
    },
    {
        name : "Linda",
        age : 22,
        isPresent : true
    },
    {
        name : "Philip",
        age : 27,
        isPresent : false
    }
];
console.table(members);
```
![Displaying an array of objects with console.table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pw2ux7mxagmqlrog1ixv.jpg)

You could also restrict the number of columns to be displayed by passing a second argument which is an array that will contain only the properties to be displayed.
```js
console.table(members, ["name","age"]);
```
!["Table displaying an array of objects with filtered output"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/viknhpnfz6fp1r9oyjmv.jpg)


## Console.trace()
When a function is called, it gets added to the call stack. If this function calls another function, that function is also added to the call stack till a value is returned.

`console.trace` is simply used to trace how a function was called (i.e other functions that lead to it).

```js
function factorial(number) {
    if (number == 1) {
        console.trace("Base case");
        return 1
    }else{
        return number * factorial(number - 1);
    }
}
factorial(4);
```
!["Displaying the function of console.trace"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jm09l5pr1q63n9o3hg4.jpg)

We can see that we hit the base case after the function was called four times. "Anonymous" is simply the global namespace that gets mounted on the call stack before any other function is added to it.

## Console.count()
This function takes a string as an argument and logs to the console the number of times it has been called with that string. If no string is passed, it behaves as though it was called with a string value of "default".

```js
function increaseCount(user) {
    console.count(user);
}
increaseCount("Ben");
increaseCount();
increaseCount("Ben");
increaseCount();
increaseCount("Jane");
```
![Displaying the number of times console.count was called](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bi8fa8gogmuhwqgy7x74.jpg)

`console.count` is also useful for keeping track of how many times an event handler has been triggered.

The count could also be reversed using `console.countReset()`.
```js
function increaseCount(user) {
    console.count(user);
}
increaseCount("Ben");
increaseCount("Ben");
increaseCount("Jane");
console.countReset("Ben");
increaseCount("Ben");
```

![Resetting the count with console.countReset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bi8fa8gogmuhwqgy7x74.jpg)

> **Note**: While trying to reset the count make sure that console.count() and console.countReset have the same argument.

## Console.group()
`console.group()` groups all subsequent console messages until `console.groupEnd()` is called. The argument `console.group` takes is used to provide an explanatory name for the group.

```js
for (let i =0; i <= 2; i++) {
    console.group(`Group ${i+1}`)
    console.log(i)
    console.log(i + 1)
    console.log(i + 2)
    console.log(i + 3)
    console.groupEnd()
}
```
![Grouping console.logs with console.group](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kx6g6mdchp2vv7j9g0y9.jpg)
## Console.time()
`console.time()` takes an argument that represents its unique name and starts a timer with that name. To check the time it takes for a block of code to run, `console.time()` is called above the code followed by another function `console.timeEnd()` which is called at the end, with the same argument passed to   `console.time()`.  `console.timeEnd()` stops the timer and logs the time it took for the code to run (in milliseconds) to the console.

```js
console.time(loop-time);
for (let i =0; i <= 2; i++) {
    console.log(i + 2)
}
console.timeEnd(loop-time);
```
![displaying how long it took for a for loop to run](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gdehie6c61x0clsc3gm.jpg)

Also, to check the time since console.time() was called, a function, `console.timeLog()` which takes the same argument as console.time is called between console.time and console.timeEnd().

```js
console.time("loop-time");
for (let i =0; i <= 2; i++) {
    for (let j=0; j<=2; j++) {
    console.log(i + 2)
    }
    console.timeLog("loop-time");
}
console.timeEnd("loop-time");
```
![using console.timeLog in a nested for loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txlm2dvsl6awrv281gx6.jpg)


> **Note** : `console.time()` does not produce any output on its own and once `console.timeEnd()` has been called its inappropiate to call `console.timeLog` until `console.time()` is called again.

## Formatted Output with Console.
When Console functions similar to console.log() takes two arguments where the first contains %s, %i, %d, %f, %o, %O, or %c. The first argument is treated as a format string, and the values of subsequent arguments are substituted into the string in place of the two-character % sequences.

* %s - Format as a string.
* %i - Format as an integer.
* %f - Format as a floating point value.
* %O - Format as a javascript object.
* %o - Format as a DOM element.
* %c - Format as a CSS rule.
```js
const a = {name:"Cindy"};
console.log("The first user is : %O", a);
console.log("Here are the elements in the DOM : ", document.documentElement);
console.log("%cThis is a text", "color:red;font-size:2rem");
```
!["Using Console Formatters"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ei0q5r3sgdfx2vpgdxxl.jpg)

## Destructuring the Console object.
To save time, you could destructure console functions from the Console object.
```js
const { log } = console;
const { error } = console;

log("This also works !");
error("This is wrong");
```
![Destructuring the console object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9g3qewrywcwoo9dzniro.jpg)

## Conclusion.
Even with all of the available functions the console API provides, some developers only use console.log() when trying to find errors in their code. 

Sometimes, using a console.log() works just fine but there are also sometimes when other functions might save you some time by providing better information regarding the bug to be fixed.

Thanks for reading this article. I hope you have learned something new and you are ready to start implementing what you have learned.