DEV Community

Accreditly
Accreditly

Posted on

JavaScript `console` Methods: A Comprehensive Guide

In this blog post, we will dive into the JavaScript console object and explore its various methods. The console object provides developers with a range of helpful tools for debugging and monitoring code execution. Let's dive in!

1. console.log()

This is the most commonly used method for printing messages to the console. It displays a message, an object, or multiple messages/objects in a string format.

console.log("Hello, World!");
console.log("Hello", "World!");
console.log({ key: "value" });
Enter fullscreen mode Exit fullscreen mode

Expected output:

Hello, World!
Hello World!
{ key: "value" }
Enter fullscreen mode Exit fullscreen mode

2. console.info()

Similar to console.log(), this method prints informational messages to the console. In some browsers, it may display an info icon alongside the message.

console.info("This is an informational message.");
Enter fullscreen mode Exit fullscreen mode

Expected output:

[i] This is an informational message.
Enter fullscreen mode Exit fullscreen mode

3. console.warn()

This method prints warning messages to the console. In many browsers, it displays a warning icon and highlights the message in yellow.

console.warn("This is a warning message.");
Enter fullscreen mode Exit fullscreen mode

Expected output:

[⚠] This is a warning message.
Enter fullscreen mode Exit fullscreen mode

4. console.error()

Use this method to print error messages to the console. Many browsers display an error icon and highlight the message in red.

console.error("This is an error message.");
Enter fullscreen mode Exit fullscreen mode

Expected output:

[✖] This is an error message.
Enter fullscreen mode Exit fullscreen mode

5. console.assert()

This method writes an error message to the console if the specified condition is false. It does nothing if the condition is true.

console.assert(1 === 2, "1 is not equal to 2");
Enter fullscreen mode Exit fullscreen mode

Expected output:

[✖] Assertion failed: 1 is not equal to 2
Enter fullscreen mode Exit fullscreen mode

6. console.clear()

This method clears the console, removing all messages.

console.clear();
Enter fullscreen mode Exit fullscreen mode

7. console.table()

This method displays tabular data in a well-formatted table.

const data = [
  { name: "John", age: 30 },
  { name: "Jane", age: 28 },
];
console.table(data);
Enter fullscreen mode Exit fullscreen mode

Expected output:

┌─────────┬──────┬─────┐
│ (index) │ name │ age │
├─────────┼──────┼─────┤
│    0    │ John │  30 │
│    1    │ Jane │  28 │
└─────────┴──────┴─────┘
Enter fullscreen mode Exit fullscreen mode

8. console.count()

This method logs the number of times it has been called with a specific label.

for (let i = 0; i < 5; i++) {
  console.count("Counter");
}
Enter fullscreen mode Exit fullscreen mode

Expected output:

Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Enter fullscreen mode Exit fullscreen mode

9. console.countReset()

This method resets the count for the specified label.

console.count("Counter");
console.countReset("Counter");
console.count("Counter");
Enter fullscreen mode Exit fullscreen mode

Expected output:

Counter: 1
Counter: 1
Enter fullscreen mode Exit fullscreen mode

10. console.group(), console.groupCollapsed(), and console.groupEnd()

These methods are used to create nested groups of log messages, making it easier to read and understand output. console.groupCollapsed() creates a group that is initially collapsed.

console.group("Parent Group");
console.log("Parent Log");
console.group("Child Group");
console.log("Child Log");
console.groupEnd();
console.log("Parent Log");
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

Expected output:

Parent Group
  | Parent Log
  | Child Group
  |   ├ Child Log
  | Parent Log
Enter fullscreen mode Exit fullscreen mode

11. console.time() and console.timeEnd()

These methods help measure the time taken for a block of code to execute. They take a label as a parameter, and console.timeEnd() outputs the elapsed time.

console.time("Timer");
for (let i = 0; i < 1000; i++) {
  // Some operation
}
console.timeEnd("Timer");
Enter fullscreen mode Exit fullscreen mode

Expected output:

Timer: 3.123ms
Enter fullscreen mode Exit fullscreen mode

Note: this obviously changes depending on what you place inside the timer block!

12. console.trace()

This method displays a stack trace for the point at which it is called.

function firstFunction() {
  secondFunction();
}

function secondFunction() {
  console.trace();
}

firstFunction();
Enter fullscreen mode Exit fullscreen mode

Expected output:

Trace
    at secondFunction (script.js:6)
    at firstFunction (script.js:3)
    at script.js:9
Enter fullscreen mode Exit fullscreen mode

Bonus: Displaying Large Formatted Text in the Console

To display large, formatted text in the console, you can use the %c format specifier in console.log() along with CSS styling. You may see this kind of text shown in the console on large sites such as Facebook or Google, that are subject to frequent attacks on their users - it's often used to show a large warning to users telling them to not paste code into the console they do not understand.

console.log(
  "%cHello, World!",
  "font-size: 24px; font-weight: bold; color: blue;"
);
Enter fullscreen mode Exit fullscreen mode

In the example above, the %c format specifier is used to apply CSS styles to the text. The first argument of console.log() contains the text and the %c specifier, while the second argument contains the CSS styles.

You can apply multiple styles and use multiple %c specifiers within a single console.log() call:

console.log(
  "%cHello%c, %cWorld%c!",
  "font-size: 24px; font-weight: bold; color: blue;",
  "",
  "font-size: 24px; font-weight: bold; color: red;",
  ""
);
Enter fullscreen mode Exit fullscreen mode

In this example, different styles are applied to "Hello" and "World". Each %c specifier corresponds to a style string, and an empty string is used to reset the styling.

That's it! You now have a solid understanding of the various JavaScript console methods and how to display large formatted text in the console. Happy coding!

Find that easy? Already know most of it?

You might be interested in taking one of our Web Development Certifications, to help show prospective employers or clients that you know your stuff. We have a JavaScript Fundamentals certification, which covers some of the information found here.

Top comments (1)

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

Styling console logs is really a great feature in Javascript which can be used in various situations. The below article explains this feature in detail with some tips on clean coding.
Style console logs