8 useful console methods in JavaScript.

November 20, 2020#javascript

8 useful console methods in JavaScript.

In this article, I will show you 8 useful console methods.

1. console.log

console.log() is used to output a message to the console, the message can be a string, a number, an array, an object, or a JavaScript expression.

console.log(1); // number.
console.log("hi"); // string.
console.log([1, 2, 3]); // array.
console.log({ hi: "bye" }); // object.
console.log(10 + 20); // expression.

2. console.assert

console.assert() writes the error message to the console only when the assertion is false.

console.assert(false, "The statement is false");
console.assert(50 > 100, "50 isn't bigger than 100");

3. console.clear

console.clear() clears the console only if it's allowed by the environment.

console.clear();

4. console.dir

console.dir() displays an interactive list of the properties of the specified JavaScript object.

console.dir(document.location);

5. console.error

console.error() is used to display an error to the console.

console.error("A simple error.");

6. console.count

console.count() logs the number of times that this particular call to count() has been called.

for (let i = 0; i < 10; i++) {
  console.count("number");
}

7. console.table

console.table() is used to display data in the form of a table.

let object = {
  a: "hi",
  b: "hello",
  c: "bye",
};

console.table(object);

8. console.time

console.time() tracks how long an operation takes.

console.time("loop");
for (let i = 0; i < 10000; i++) {}
console.timeEnd("loop");

Share the post: