👨🏼‍💻

khriztianmoreno's Blog

Home Tags About |

Some methods beyond console.log in Javascript

Published at 2023-02-17
Updated at 2023-02-17
Last update over 365 days ago Licensed under MIT javascriptweb-developmentprogramming

Some methods beyond console.log in Javascript

Often, during debugging, JavaScript developers tend to use the console.log() method to print values. But there are some other console methods that make life much easier. Want to know what these methods are? Let’s get to know them!

1. console.table()

Displaying long arrays or objects is a headache using the console.log() method, but with console.table() we have a much more elegant way to do it.

// Matrix
const matrix = [
  ["apple", "banana", "cherry"],
  ["Rs 80/kg", "Rs 100/kg", "Rs 120/kg"],
  ["5 ⭐", "4 ⭐", "4.5 ⭐"],
];
console.table(matrix);

// Maps
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

const family = {};
family.mother = new Person("Jane", "Smith");
family.father = new Person("John", "Smith");
family.daughter = new Person("Emily", "Smith");
console.table(family);

console.table()

2. console.trace()

Having trouble debugging a function? Wondering how the execution flows? console.trace() is your friend!

function outerFunction() {
  function innerFunction() {
    console.trace();
  }
  innerFunction();
}
outerFunction();

console.trace()

3. console.error() and console.warn()

Tired of boring logs? Spice things up with console.error() and console.warn()

console.error("This is an error message");
console.warn("This is a warning message");
console.log("This is a log message");

console.error()

4. console.assert()

This is another brilliant debugging tool! If the assertion fails, the console will print the trace.

function func() {
  const a = -1;
  console.assert(a === -1, "a is not equal to -1");
  console.assert(a >= 0, "a is negative");
}

func();

console.assert()

5. console.time(), console.timeEnd(), and console.timeLog()

Need to check how long something is taking? Timer methods are there to rescue you!

console.time("timeout-timer");

setTimeout(() => {
  console.timeEnd("timeout-timer");
}, 1000);

setTimeout(() => {
  console.timeLog("timeout-timer");
}, 500);

console.time()

NOTE: setTimeouts are not executed immediately, which results in a slight deviation from the expected time.

That’s all folks! I hope this helps you become a better dev!

Profile

@khriztianmoreno on Twitter and GitHub