JavaScript Console
Tags: javascript, tutorial, codenewbie, webdev
Published: 2021-05-19 23:30:10

The `console.log` method is not the only method used in the console.

Check out other console methods besides `log` by running the code below:

```js
console.dir(console);
```


![Screenshot 2021-05-04 182300.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1620149020633/sw9_ZplBF.png)


If you want to reference each of the console methods, click the links below:

- [asset](https://developer.mozilla.org/en-US/docs/Web/API/console/assert)
- [clear](https://developer.mozilla.org/en-US/docs/Web/API/Console/clear)
- [count](https://developer.mozilla.org/en-US/docs/Web/API/Console/count)
- [countReset](https://developer.mozilla.org/en-US/docs/Web/API/Console/countReset)
- [debug](https://developer.mozilla.org/en-US/docs/Web/API/Console/debug)
- [dir](https://developer.mozilla.org/en-US/docs/Web/API/Console/dir)
- [dirxml](https://developer.mozilla.org/en-US/docs/Web/API/Console/dirxml)
- [error](https://developer.mozilla.org/en-US/docs/Web/API/Console/error)
- [group](https://developer.mozilla.org/en-US/docs/Web/API/Console/group)
- [groupCollapsed](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupCollapsed)
- [groupEnd](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupEnd)
- [info](https://developer.mozilla.org/en-US/docs/Web/API/Console/info)
- [log](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)
- [profile](https://developer.mozilla.org/en-US/docs/Web/API/Console/profile)
- [profileEnd](https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd)
- [table](https://developer.mozilla.org/en-US/docs/Web/API/Console/table)
- [time](https://developer.mozilla.org/en-US/docs/Web/API/Console/time)
- [timeEnd](https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd)
- [timeLog](https://developer.mozilla.org/en-US/docs/Web/API/Console/timeLog)
- [timeStamp](https://developer.mozilla.org/en-US/docs/Web/API/Console/timeStamp)
- [trace](https://developer.mozilla.org/en-US/docs/Web/API/Console/trace)
- [warn](https://developer.mozilla.org/en-US/docs/Web/API/Console/warn)

---
Let's look at a few here:
### Measuring time
The start time is `console.time(...)` while the end time is `console.timeEnd(...)`. The timing is in milliseconds (ms).

See the syntax below:

```
console.time('...')
.
.
.
console.timeEnd('...')
```

Note: The same string (e.g. `response time`) must be used in both the `time` and `timeEnd` function

See the example below:

```js
console.time('response time');

alert('Click to continue');
console.timeEnd('response time');
```

See another example below:

```js
console.time('response time');

const pow = (x, y) => {
  let result = 1; 

  for (let i = 0; i < y; i++) {
    result *= x; 
  } 

  return result;
};

console.log( 'iterative:', pow(2, 4) ); // 16

console.timeEnd('response time');

console.time('response time');
const power = (x, y) => {
  if (y === 1) {
    return x;
  }
  else {
    return power( x, (y-1) ) * x;
  }
};

console.log( 'recursive:', power(2, 4) ); // 16

console.timeEnd('response time');
```

```js
// output
16
response time: 2.7529296875 ms

16
response time: 1.0400390625 ms
```

Recursive seems to be faster than iterative looping.

### Formating console output
We can also format the output from the console.
Below shows a list of common specifiers in JavaScript

|   specifier   |     output  |
|------------|------------|
| %s              |Format the value as a string |
| %i or %d              |Format the value as an integer|
| %f              |Format the value as a floating-point value|
| %o              |Format the value as an expandable DOM element |
| %O              |Format the value as an expandable JavaScript object |
| %c              |Applies CSS style rules to the output string as specified by the second parameter |

See the examples below:

```js
console.log('%s has %d points', 'Bello', 100); //  Bello has 100 points
console.log('%cHello world!', 'color: blue; font-size: 30px');
```


![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1620242194091/Io0_sXLLu.png)


It is possible to apply css rule differently on each word in the `console.log`

See the example below:

```js
console.log("%cHello %cWorld%c!!", // string to be printed
 "color: blue;", // applies color formatting to the 1st substring
 "font-size: 30px;", // applies font formatting to the 2nd substring
 "/* no CSS rule*/" // does not apply any rule to the remaining substring
);
```


![2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1620242813006/7LcZ1nBj6.png)


### Tabular values
The `console.table` can be used to display objects and arrays in a tabular format.

See the examples below:

```js
console.table( ['Hello', 'world'] );
console.table( {foo: 'bar', bar: 'baz'} );
```

```js
// output
(index) value
0       "Hello"
1       "world"

(index) value
foo     "bar"
bar     "baz"
```

![6.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1620246168343/769riCLUm.png)

See another fun example below:

```js
const personArr = [
{
 "personId": 123,
 "name": "Jhon",
 "city": "Melbourne",
 "phoneNo": "1234567890"
},
{
 "personId": 124,
 "name": "Amelia",
 "city": "Sydney",
 "phoneNo": "1234567890"
},
{
 "personId": 125,
 "name": "Emily",
 "city": "Perth",
 "phoneNo": "1234567890"
},
{
 "personId": 126,
 "name": "Abraham",
 "city": "Perth",
 "phoneNo": "1234567890"
}
];
console.table(personArr, ['name', 'personId']);
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1620246628782/7KYetFXWN.png)

---
### Clearing the console
Most of the time we clear the console with <kbd>Ctrl</kbd> + <kbd>L</kbd> but we can also use the `console.clear` method to clear the console.

```js
console.clear()
```

---
### Displaying objects
`console.dir(object)` displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

```js
const personArr = [
{
 "personId": 123,
 "name": "Jhon",
 "city": "Melbourne",
 "phoneNo": "1234567890"
},
{
 "personId": 124,
 "name": "Amelia",
 "city": "Sydney",
 "phoneNo": "1234567890"
},
{
 "personId": 125,
 "name": "Emily",
 "city": "Perth",
 "phoneNo": "1234567890"
},
{
 "personId": 126,
 "name": "Abraham",
 "city": "Perth",
 "phoneNo": "1234567890"
}
];
console.dir(personArr);
```

![12.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1620335583235/PXbBf7J5Y.png)

There's also a `console.dirxml` function that logs the **XML** (**eXtensible Markup Language**) representation of the descendant elements of the object if possible, or the
JavaScript representation if not.

See the example below:

```js
console.dirxml(document)
```

![14.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1620336388882/f8QenSDdX.png)

### Debugging with assertions
> The `console.assert()` method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens -  [MDN](https://developer.mozilla.org/en-US/docs/Web/API/console/assert) 

```js
console.assert('zero' === 0)
```

![15.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1620337182612/kda7cV2WZ.png)

Syntax:
```
console.assert(assertion, obj [, type1, ..., typeN]);
console.assert(assertion, string [, type1, ..., typeN]); 
```
There's an error message to the console only if the assertion is false. 

```js
console.assert(true, {key: 'string'}, NaN, Object, undefined); 
console.assert(true, {key: 'string'}, NaN, String, undefined); 
console.assert(true, {key: 'string'}, NaN, undefined);
console.assert(false, {key: 'string'}, NaN, Object, undefined); // error
```

![16.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1620338394619/c_oSmBxUC.png)


### Other print methods

- info – a small informative icon (ⓘ) appears on the left side in some browsers' developer tool.
- warn - a small warning icon (!) appears on the left side in some browsers' developer tool.
- error -  small times icon (⊗) appears on the left side in some browsers' developer tool.

```js
console.info('info - 1 message');
console.warn('warn - 1 message');
console.error('error - 1 message');
```

![20.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1620339053913/ihlmVAbNj.png)

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---