As a Javascript developer, you are surely aware of the console.log() method. It is the most straightforward way to debug your code.
But do you know that Console API provides many more useful methods?
In this article, we'll explore different methods provided by the console object.
Console Object
The console
object gives you access to the browser’s console. It lets you output strings, arrays, and objects that help debug your code. The console is part of the window object and is supplied by the Browser Object Model (BOM).
Console Object Methods
1. console.assert()
Log a message and stack trace to console if the first argument is false.
In the above example, the expression 3 === 4
is false, so this method logs the same message which is passed as a second argument.
2. console.clear()
Clears the console.
3. console.count()
Logs the number of times that this particular call to count() has been called.
You can pass a "label" as an argument.
4. console.error()
Used to log error message to the console. Useful in the testing of code. By default, the error message will be highlighted with red color.
5. console.group() & console.groupEnd()
Creates a new inline group in the console. This indents following console messages by an additional level until console.groupEnd()
is called. They accept labels of the same value.
6. info()
Outputs an informational message to the console.
7. console.table()
Writes a table in the console view.
The first parameter is required and must be either an object or an array, containing data to fill the table.
8. console.time() & console.timeEnd()
Whenever we want to know the amount of time spend by a block or a function, we can make use of the time() and timeEnd() methods provided by the javascript console object. They take a label that must be the same, and the code inside can be anything( function, object, simple console).
9. console.warn()
Used to log warning message to the console. By default, the warning message will be highlighted with yellow color.
10. console.trace()
The console.trace() method displays a trace that shows how the code ended up at a certain point.
Custom Console Logs
Users can add Styling to the console logs in order to make logs Custom. The Syntax for it is to add the CSS styling as a parameter to the logs which will replace %c
in the logs.
Wrap Up
Next time you want to debug your code use the above-listed methods. Thanks for reading. Please share it with your network. Don’t forget to leave your comments below.