console methods in JavaScript
Today we’ll explain the various console methods in JavaScript and how to use it with examples.
Checkout more articles on JavaScript
console methods
- log()
- info()
- warn()
- error()
- clear()
- table()
- count()
- time() and timeEnd()
- group() and groupEnd()
- Custom console logs
1. log()
Use the log()
method to print any type of the value. It could be a string, integer, object, array, boolean, etc.
1 2 3 4 5 6 7 | console.log('Clue Mediator'); console.log(304); console.log(true); console.log(undefined); console.log(null); console.log([1, 2, 3, 4]); // array console.log({ x: 1, y: 2, z: 3 }); // object |
2. info()
Use the info()
method to display logs as information.
1 | console.info('Info log!'); |
3. warn()
Use the warn()
method to show the warning log in the console.
1 | console.warn('Warn log!'); |
4. error()
Same as the above logs we can use the error()
method to show the error log in the console.
1 | console.error('Error log!'); |
5. clear()
Run the clear()
command to clear the console log.
1 | console.clear(); |
6. table()
The table()
method allows us to generate a table inside a console. The input must be an array or an object which will be shown as a table.
1 2 | console.table({ 'x': 1, 'y': 2 }); console.table([['Clue'], ['Mediator'], ['The way to write your code!']]); |
7. count()
The console.count()
method logs the number of times that this particular call to count()
has been called.
1 2 3 4 5 | console.count('Clue Mediator'); console.count('The way to write your code'); console.count('The way to write your code'); console.count('Clue Mediator'); console.count('The way to write your code'); |
8. time() and timeEnd()
Use the time()
method to start a timer you can use to track how long an operation takes. The timeEnd()
method stops a timer that was previously started by calling console.time()
.
1 2 3 4 5 6 7 8 9 10 | console.time('timeExample'); const fn1 = function () { console.log('fn1 called!'); } const fn2 = function () { console.log('fn2 called!'); } fn1(); // calling fn1(); fn2(); // calling fn2(); console.timeEnd('timeExample'); |
9. group() and groupEnd()
Using the group()
, your console logs are grouped together, while each grouping creates another level in the hierarchy.
1 2 3 4 5 | console.group('Info'); console.log('Clue Mediator'); console.log('The way to write your code'); console.groupEnd('Info'); console.log('continue...'); |
10. Custom console logs
Use the style for custom console logs. We have to use the %c
in the logs to add the style.
1 2 3 | const size = '10px'; const style = `padding: 5px 7px; background-color: #f1efea; color: #454e5c; font-style: ${size}; font-weight: 600;`; console.log('%cClue Mediator', style); |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂