The JavaScript console is a web API that helps in to debug JavaScript codes based on the browser environment or server-side environment. This console object gives us access to the console of the browser.
Reveal the console object by running the code below:
console.log(console)
From the code above, we see that the console object contains some methods.
NOTE: The console may appear different depending on the browser you are using because its environment implementations may differ.
The methods include table()
, time()
, clear()
, and log()
, etc.
To open the console, press Ctrl + Shift + K for Windows and Command + Option + K for Mac.
console
methodslog()
console.log("Hi I have been logged to the console!😊")
warn()
console.warn("This is a warning 🤦♀️")
info()
console.info("This is a message");
table()
console.table({name:"table", type:"console method", isMethod: true})
clear()
console
of your environment or browser. Run the code below on your browser console:Note: this will only run if your environment supports it.
console.log("I have been logged");console.warn("I have been warned");setTimeout(()=>{console.clear()}, 2000)setTimeout(()=>{console.log("console was cleared after 2 seconds")}, 3000)
The code above has the console clear everything it has after 2 seconds, and log the message that it has been cleared!
time()
and timeEnd()
time()
is used to display the time taken for a program to run.
It takes a label and calls it with timeEnd()
. Run the code below on your browser console:console.time("totalTime")console.log("Hey I will take time to run, see the time below:");console.timeEnd("totalTime");
There are other console methods available. Refer to the
for details. official documentation https://developer.mozilla.org/en-US/docs/Web/API/Console
console
objectYou can apply CSS to the console. It is done by using %c
and the CSS properties.
Look at the example below:
console.log("%c This is a red text!", "color: red")console.log("%c red, %c blue, and %c green", "color:red", "color:blue", "color:green");
for
Loop or while
loop, which is faster?Let’s see which is faster between these two with console.time()
:
let counter = 0;const whileLoop = () =>{console.time("whileLoop");while(counter <= 10){counter++;}console.timeEnd("whileLoop");}const forLoop = () =>{console.time("forLoop");for(counter; counter <= 10;counter++){}console.timeEnd("forLoop");}whileLoop();forLoop();
The console object is available to the JavaScript Engine through the environment console (such as the web browser of your computer). It is very useful because it has methods for debugging.