Console.log overdose
Console.log is probably the most written line of code in the JavaScript language. Developers often use this function as a way to display values, assert value, create false breakpoints and so on. In this post we will explore some other functions that can help you write better code and avoid the "console.log" overdose.
Console.assert
Often what we want to achieve is to evaluate a condition in our code and print something int he console in case it fails. Assert takes a conditional expression and a string - it print the string if the expression evaluate to false.
if(!some_condition_that_should_always_be_true){
console.log("Something is not right");
}
//Could be better written
console.assert(some_condition_that_should_always_be_true, "Something is not right")Console.count
Some other time we just want to count how many time something happen during our code's execution. A cumbersome way of doing that is to print something with console.log each time the thing we want to track happen then filter our logs to manually count the occurrence. That approach has a lot of issues - the first being that you have to manually count the occurrence (in 2024, that's unthinkable); second you have to filter your logs which prevent you from looking at other log output while counting. The solution is console.count .
let a = 0
if(something_happended_to_a){
a++;
console.count("Inc A");
}
if(something_else_happend_to_a){
a++;
console.count("Inc A");
}
if(again_something_happend_to_a){
a++;
console.count("Inc A");
}Console.count returns the number of time it has been called with a particular label. In this snippet we have the label "Inc A" that has been used 3 times.
Console.time
Another common use case of console.log is to time calculate the execution time of a code block. Usually it is done by having a constant declared at the beginning of the block that holds the timestamp then declaring another constant that hold the timestamp at the end, then we can console.log the difference between the two timestamp. This is cumbersome and we are declaring boilerplate code into our code base. The solution is console.time and console.timeEnd.
//This is the block for which we want to calculate the execution time
console.time("myTimerLabel");
someComplexStuff();
moreComplexStuff();
console.timeEnd("myTimerLabel");Our timer start when we call console.time and ends when we call console.timeEnd in the console it prints the label that we used followed by the time that has passed between the two calls.