Different console methods in Javascript

· 269 words · 2 minute read

There are few console methods available in Javascript, console.log being the most common one. Each of these variations of console methods could and should be used depending on type of data to output.

  1. console.log() - As mentioned earlier console.log() is the most common console method and can be used to output any kind of data.
console.log();

const message = "Hello world";
const num1 = 10;
const num2 = 20;

console.log(message); //string
console.log(num1); //number
console.log(num1, num2, message); //comma separated values
console.log(num2 / num1); //expressions
  1. console.clear() - clears out the console
console.clear();
  1. console.error() - Can be used in case we want to show an error message on the console. It adds a red background to the message so that it is differentiable from other messages whenever some error occurs.
console.error("Oops, that didn't work");
  1. console.table() - It outputs the values in the form of a table. The table() methods expects the input in the form of an array or object.
const arr = [10, 30, 20];

console.table(arr);

usestate

const student = {
  name: "Gagan",
  course: "MCA",
};

console.table(student);

usestate

  1. console.count() - Logs the number of time count() method was called. We can call count without or without any parameter. The default label it adds to the count is default:
console.count();
console.count();
console.count();
console.count();
console.count();

usestate

or optionally we can pass a custom label to the count() method.

console.count("Got called times: ");
console.count("Got called times: ");
console.count("Got called times: ");
console.count("Got called times: ");
console.count("Got called times: ");

usestate

  1. console.time() - It logs the time between the execution of statements.
console.time("start");
let i = 0;

while (i < 5000) {
  i++;
}
console.timeEnd("start");

output> start: 0.117919921875 ms