DEV Community

Charlie @ 90-10.dev
Charlie @ 90-10.dev

Posted on • Originally published at 90-10.dev on

Using the Browser Console

The browser console is a powerful tool for web developers and can be used to diagnose and fix issues on a website. To access the console, open your browser's developer tools and navigate to the console tab.

The console can be used to execute JavaScript code, and will display any output or errors. This can be useful for debugging scripts or testing small snippets of code. Additionally, the console can be used to inspect and modify HTML and CSS on the current page, allowing for quick prototyping and experimentation.

Here are a couple of tricks you can use in your browser console.

Output to console

This is probably the most widely used debug technique:

console.log("test");
Enter fullscreen mode Exit fullscreen mode

test

Output multiple values

let year = 2020;
let age = 99;
console.log(age, year);
Enter fullscreen mode Exit fullscreen mode

99, 2020

Output with formatting

Specifiers can be used to achieve string interpolation:

let year = 2020;
let age = 99;
console.log('It is %i and I am %i years old.', year, age);
Enter fullscreen mode Exit fullscreen mode

It is 2020 and I am 99 years old.

Available Specifiers

Specifier Output
%s String
%i or %d Integer
%f Float
%o Optimal formating for collections
%O Expandable data
%c CSS style

Output with style

Here is how to use the %c specifier mentioned above:

console.log('%c Seeing red', 'color: red');
Enter fullscreen mode Exit fullscreen mode

Seeing red.

Output an object

We can output objects directly via:

console.dir({a:1,b:2});
Enter fullscreen mode Exit fullscreen mode

▾ Object { a: 1, b: 2 }

a: 1

b: 2

...

... but we can also show a JSON-ifyed version:

console.log(JSON.stringify({a:1,b:2}));
Enter fullscreen mode Exit fullscreen mode

{"a":1,"b":2}

Output an object using table

console.table({a:1,b:2});
Enter fullscreen mode Exit fullscreen mode

| (index) | Value |

| a | 1 |

| b | 2 |

Output a variable using template literals ES6

let width = 100;
console.log(`width is: ${width}`);
Enter fullscreen mode Exit fullscreen mode

width is: 100

Log errors & warnings

console.error("Computer says no");
Enter fullscreen mode Exit fullscreen mode

⛔️ ▾ Computer says no

console.warn("Computer says maybe");
Enter fullscreen mode Exit fullscreen mode

⚠️ ▾ Computer says maybe

Clear console

console.clear;
Enter fullscreen mode Exit fullscreen mode

Execution time

Measure how long some code execution took:

console.time('id1');
...
console.timeEnd('id1');
Enter fullscreen mode Exit fullscreen mode

default: 6202.5400390625ms


The browser console is a powerful tool for web developers and can greatly streamline the debugging and development process.

Top comments (0)