Unravelling JavaScript Console API

Niharika Singh โ›“ - Aug 24 '20 - - Dev Community

Nights that end with console.log() usually precede mornings that start with console.log(). ๐Ÿ˜”

Well, there's life beyond console.log().

Let's go over some JavaScript console methods that REALLY have the potential to make your life better.


0. console.log()

console.log("You already know this!");

// This is used to output a message to the console.

Output:

Alt Text

1. console.table()

Sometimes we want to output a large object on the console. Using console.log() can be a pain.

console.table() is a treat to sore eyes.

function Crypto(symbol, name) {
  this.symbol = symbol;
  this.name = name;
}

let bitcoin = new Crypto("$BTC", "Bitcoin");
let ethereum = new Crypto("$ETH", "Ethereum");
let polkadot = new Crypto("$DOT", "Polkadot");

console.table([bitcoin, ethereum, polkadot]);

Output:

Alt Text

How beautiful and incredibly readable does that look!

If you had used console.log() here, this is what you would have seen instead:

Alt Text

2. console.info() / console.error() / console.warn()

The console.info() method outputs an informational message.

The console.error() method outputs an error message.

The console.warn() method outputs a warning message.

console.info("FYI: Today is Monday");

console.error("Today is not Friday");

console.warn("Get back to work!");

Output:

Alt Text

๐Ÿ’ก It is a good practice to log messages on the console with appropriate formatting.

3. console.time()

This API method will tell you runtime in milliseconds. You can have multiple timers running at once in a JS program. (Maximum 10,000 timers.)

console.time("time taken");
//DO SOMETHING
let x = 90;
let y = 100;
let z = x + y / 100;
console.timeEnd("time taken");

Output:

time taken: 0ms - timer ended

These were some lesser known methods of console API in JavaScript.

I am hopeful that these methods will help you!

Cheers.

. . . . . . . . . . . . . . . . .