If you are a programmer, you know very well the need for debugging code. We often use external libraries to show logs or format them. However, you may not realize that the browser console is inherently a very powerful tool for this.
When it comes to consoles, the first thing that comes to mind is console.log
right? But apart from that, there are many other useful methods. In this article, let’s see how to make the most of the console.
What is a console?
The JavaScript console is a feature built into browsers today and comes with development tools that can be used immediately with a shell-like interface. It allows developers to:
- View the log of errors and warnings of a website.
- Interact with websites using JavaScript commands.
- Debug the application and view the DOM directly in the browser.
- Observe and analyze network activities.
Basically, it gives you the right to write, manage and monitor JavaScript right in the browser.
console.log, console.error, console.warn and console.info
These are probably the most used methods. You may pass multiple parameters into these methods. The parameters will be evaluated and joined together into a string separated by a space (if the parameter is an object or an array, you can navigate between their properties).
console.group
This method allows you to group console.log (or error, info …) into a group. Its syntax is very simple: put all the console.log
lines you want to group under one console.group()
(or console.groupCollapsed()
if you want the group to be closed by default). Then put a line console.groupEnd()
at the end of the logs you want to group.
console.table
Displaying JSON or a large JSON array with console.log
is a pretty “awful” thing. The console.table
method will help us to handle this well, which allows us to render the JSON structure in a beautiful, easy-to-see format in the form of tables.
(You can click the column name to sort.)
console.count, console.time, console.timeEnd
These three methods are like a Swiss versatile knife for programmers. The console.count
method will count the number of times the count
has been called, if passing another parameter to count()
, it will count the number of calls associated with each parameter. The console.time
method will launch a counter with the name of the counter passed as a parameter (we can run up to 10,000 counters on the same page). After running the counter, we call the console.timeEnd()
method to stop the counter and print the counter’s run time.
console.trace and console.assert
These methods will print out the faulty steps from the time it is called. Assuming you are building a JS library and you want to notify the user where the error occurred, these methods are useful in that case. The console.assert
and console.trace
methods are the same except that console.assert
will only print if the passed condition is not met.
Over