The Console API.
Sebastian Anioke
Posted on August 12, 2022
The ability to spend less time finding errors in a code is a necessary skill that every developer should have.
The Console API, a debugging tool that is part of the browser, provides developers with some functions that make it possible to find these errors.
I wrote this article to show web developers some of the functions that come with the console object and what they are used for. Hopefully, you will find it useful when debugging your code.
Console.log()
This is the most popular console method. It converts its arguments (which are separated by commas) to strings and logs them to the web console. In the console, it inserts spaces between the arguments and starts a new line after outputting all arguments.
Other similar functions include:
- Console.debug()
- Console.info()
Normally, the browser doesn't show debug statements and would return undefined. This is because console.debug() was created to be used in development areas only and should not be shown to users. However, this can be changed by enabling "verbose" in the default levels.
Note: When logging objects to the console from an IDE what gets logged is a reference to the object and not the value of the object when
console.log
is called, but the value of the object after the console is opened.
Console.warn()
The console.warn()
method outputs a warning message to the web console. It usually starts with an exclamation icon.
let x = 3;
if (x == 3) {
console.warn("This value might be too low");
}
console.warn
is used for displaying messages that might not necessarily cause a breakdown in the application but to show something that the user should be aware of. For example, if an API is deprecated, console.warn
can be used to send a message across to the user.
Console.error()
The console.error()
function outputs an error message to the console (we have all gotten this one).
let x = "3";
if (!Number.isInteger(x)) {
console.error(`${x} is not a number`);
};
console.error()
is used for building libraries so that the user is aware of the reason their code might not be working as expected.
Console.assert()
The console.assert
function takes two arguments. The first argument is a block of code that is either true or false while the second argument is the message to be printed to the console.
If the first argument is true the function does nothing, but if it is false, the second argument is printed to the console with an Assertion failed" prefix.
const numbers = [1,"2",3,"4",5,"6"];
for (element in numbers) {
console.assert(Number.isInteger(numbers[element]), `${numbers[element]} is not a number`);
}
Console.clear()
console.clear
is used for clearing the console. This is useful when you want to clear other console statements before displaying a new one.
function show() {
console.clear();
console.log("...checking line 2");
console.log("...checking line 5");
console.log("...checking line 6");
}
function clear() {
console.clear();
console.log("...checking line 13");
}
show();
clear();
Console.table()
console.table
takes one argument which is an object or an array and displays it in a tabular form.
If its argument is an array, the first column will represent the indices of the array and the second will be the values.
const color = ["blue", "red", "yellow","green", "purple"];
console.table(color);
If its argument is an object, the first column will represent the properties of the object and the second column the values.
const color = {
primary : "red",
secondary : "purple",
tertiary : "violet"
}
console.table(color);
If its argument is an array of objects, the first column will represent the indices of each object, and the remaining columns will be the properties of the object.
const members = [
{
name: "Micheal",
age : 21,
isPresent : true
},
{
name : "David",
age : 18,
isPresent : false
},
{
name : "Linda",
age : 22,
isPresent : true
},
{
name : "Philip",
age : 27,
isPresent : false
}
];
console.table(members);
You could also restrict the number of columns to be displayed by passing a second argument which is an array that will contain only the properties to be displayed.
console.table(members, ["name","age"]);
Console.trace()
When a function is called, it gets added to the call stack. If this function calls another function, that function is also added to the call stack till a value is returned.
console.trace
is simply used to trace how a function was called (i.e other functions that lead to it).
function factorial(number) {
if (number == 1) {
console.trace("Base case");
return 1
}else{
return number * factorial(number - 1);
}
}
factorial(4);
We can see that we hit the base case after the function was called four times. "Anonymous" is simply the global namespace that gets mounted on the call stack before any other function is added to it.
Console.count()
This function takes a string as an argument and logs to the console the number of times it has been called with that string. If no string is passed, it behaves as though it was called with a string value of "default".
function increaseCount(user) {
console.count(user);
}
increaseCount("Ben");
increaseCount();
increaseCount("Ben");
increaseCount();
increaseCount("Jane");
console.count
is also useful for keeping track of how many times an event handler has been triggered.
The count could also be reversed using console.countReset()
.
function increaseCount(user) {
console.count(user);
}
increaseCount("Ben");
increaseCount("Ben");
increaseCount("Jane");
console.countReset("Ben");
increaseCount("Ben");
Note: While trying to reset the count make sure that console.count() and console.countReset have the same argument.
Console.group()
console.group()
groups all subsequent console messages until console.groupEnd()
is called. The argument console.group
takes is used to provide an explanatory name for the group.
for (let i =0; i <= 2; i++) {
console.group(`Group ${i+1}`)
console.log(i)
console.log(i + 1)
console.log(i + 2)
console.log(i + 3)
console.groupEnd()
}
Console.time()
console.time()
takes an argument that represents its unique name and starts a timer with that name. To check the time it takes for a block of code to run, console.time()
is called above the code followed by another function console.timeEnd()
which is called at the end, with the same argument passed to console.time()
. console.timeEnd()
stops the timer and logs the time it took for the code to run (in milliseconds) to the console.
console.time(loop-time);
for (let i =0; i <= 2; i++) {
console.log(i + 2)
}
console.timeEnd(loop-time);
Also, to check the time since console.time() was called, a function, console.timeLog()
which takes the same argument as console.time is called between console.time and console.timeEnd().
console.time("loop-time");
for (let i =0; i <= 2; i++) {
for (let j=0; j<=2; j++) {
console.log(i + 2)
}
console.timeLog("loop-time");
}
console.timeEnd("loop-time");
Note :
console.time()
does not produce any output on its own and onceconsole.timeEnd()
has been called its inappropiate to callconsole.timeLog
untilconsole.time()
is called again.
Formatted Output with Console.
When Console functions similar to console.log() takes two arguments where the first contains %s, %i, %d, %f, %o, %O, or %c. The first argument is treated as a format string, and the values of subsequent arguments are substituted into the string in place of the two-character % sequences.
- %s - Format as a string.
- %i - Format as an integer.
- %f - Format as a floating point value.
- %O - Format as a javascript object.
- %o - Format as a DOM element.
- %c - Format as a CSS rule.
const a = {name:"Cindy"};
console.log("The first user is : %O", a);
console.log("Here are the elements in the DOM : ", document.documentElement);
console.log("%cThis is a text", "color:red;font-size:2rem");
Destructuring the Console object.
To save time, you could destructure console functions from the Console object.
const { log } = console;
const { error } = console;
log("This also works !");
error("This is wrong");
Conclusion.
Even with all of the available functions the console API provides, some developers only use console.log() when trying to find errors in their code.
Sometimes, using a console.log() works just fine but there are also sometimes when other functions might save you some time by providing better information regarding the bug to be fixed.
Thanks for reading this article. I hope you have learned something new and you are ready to start implementing what you have learned.
Posted on August 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.