The underutilized console operators in JavaScript
When debugging in JavaScript many programers use console.log() to test as they go. This is a good use of console, but did you know that there are other console operators that you can use? This article will tell you about just a few that you may find useful.
1. console.log()
This method is mainly used to print the value passed to it to the console. Any type can be used inside the log(), be it an object, array, string, boolean etc.
Example
console.log('JavaScript');
console.log(9);
console.log([8, 7, 6]);
console.log({a: 1, b: 2, c: 3});
console.log(true);
console.log(null);
console.log(undefined);
Output
2. console.clear()
This method is used to clear the console. After coding for awhile, your console can become cluttered and hard to read. By clearing the console, you will not only be able to read console messages easier, but clear your mind of reading the jumble of old code.
Example
console.clear()
Output
3. console.count()
This method is used to count the number that the function hit. This can be used inside a loop to check how many times a particular value has been executed.
Example
for(let i=0; i<6; i++){
console.count(i);
}
Output
4. console.error()
A useful method to use when testing out your code. It is used to log errors in the browser console.
Example
console.error('Error found')
5. console.warn()
Yet another useful method to use while testing your code. It will throw a warning in the browser console.
Example
console.warn('Danger, Will Robinson')
6. console.time() & console.timeEnd()
Used together these operations can let a user know how long it takes to perform a function. Both take a string as a parameter.
Example
console.time('timer');
const hello = function(){
console.log('Hello Console!');}const bye = function(){
console.log('Bye Console!');}hello(); // calling hello();
bye(); // calling bye();console.timeEnd('timer');
7. console.table()
This generates a table inside the console for better readability.
Example
console.table({a: 1, b: 2, c: 3});
8. console.group() & console.groupEnd()
These methods group() and groupEnd() allows us to group contents in a separate block, which will be indented. Just like the time()
and the timeEnd()
they also accept a label, of the same value.
Example
console.group('group1');
console.warn('Danger, Will Robinson');
console.error('Error');
console.log('We belong together');
console.groupEnd('group1');console.log('I am so lonely');
Conclusion
The console is a very useful operator for programers to work with and debug their code. By using console() to the full extent, we can improve the efficiency of how we work with our code in the browser console.