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");
test
Output multiple values
let year = 2020;
let age = 99;
console.log(age, year);
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);
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');
Seeing red.
Output an object
We can output objects directly via:
console.dir({a:1,b:2});
▾ 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}));
{"a":1,"b":2}
Output an object using table
console.table({a:1,b:2});
| (index) | Value |
| a | 1 |
| b | 2 |
Output a variable using template literals ES6
let width = 100;
console.log(`width is: ${width}`);
width is: 100
Log errors & warnings
console.error("Computer says no");
⛔️ ▾ Computer says no
console.warn("Computer says maybe");
⚠️ ▾ Computer says maybe
Clear console
console.clear;
Execution time
Measure how long some code execution took:
console.time('id1');
...
console.timeEnd('id1');
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)