How to format messages in console.log() in JavaScript

Key takeaways:

  • The console.log() function can be used not only to print messages to the console but also to format them, making the messages more visually distinct and easier to interpret.

  • Formatting logs is crucial for highlighting important data, improving readability, and increasing debugging efficiency, especially as applications grow in complexity.

  • You can use placeholders (%s, %d, %f, etc.) to format different data types in the logs, while %c allows applying CSS for styling.

  • Logs can include strings, numbers, objects, arrays, and even CSS-styled text, allowing for a more structured and informative output.

  • It is possible to group logs to make related messages collapsible, enhancing organization and readability.

We know that the console.log() method will log a message to the console, but console.log() can also format the text and make the message stand out from other messages. This gives us the ability to find important messages in the console. In this Answer, we’ll learn how to format messages using placeholders, style text with CSS, and combine different data types in console.log().

Why format messages in console.log()

As the application grows, the logs become more complex, and formatting becomes crucial to make them more readable. By formatting console logs, we can:

  • Highlight key data and values.

  • Make logs easier to scan, especially when there are multiple outputs.

  • Improve debugging efficiency by structuring the output.

The basic syntax of the console.log()

Before discussing formatting, here’s a quick review of the basic syntax for console.log():

console.log(message);

In the above syntax:

  • console: It is an object that provides access to the browser’s debugging console.

  • log(): It is a method that outputs a message to the console.

  • message: This can be an object(s), string, or a primitive data type.

Formatting messages with placeholders

The console.log() method supports various placeholders to format the output message dynamically. Placeholders allow us to insert values into the string and control how they are displayed. They define the type of data to be printed on standard output. We can use format specifiers to tell the log function how the data should be printed. For example:

var a = 10;
console.log("%s treated as string", a);


Below is the list of common placeholders we have:

  • %s → Formats the value as a string.

  • %i or %d → Formats the value as an integer.

  • %f → Formats the value as a floating-point value.

  • %o → Formats the value as an expandable DOM element, as seen in the Elements panel.

  • %O → Formats the value as an expandable JavaScript object.

  • %c → Applies CSS style rules to the output string as specified by the second parameter.

Example 1: Formatting strings and numbers

We can format our log messages by using placeholders and passing the corresponding values as arguments.

let name = "John";
let age = 25;
console.log("My name is %s, and I am %d years old.", name, age);

In the above code, %s is replaced by the string John, and %d is replaced by the integer 25.

Example 2: Displaying floats with %f

For floating-point numbers, we can use the %f placeholder. JavaScript can output many decimal places by default. We can format it to two decimal places by using toFixed():

let pi = 22/7;
console.log("The value of the pi is $%f.", pi);
console.log("Two decimal value of the pi is $%f.", pi);

In the above code, the value of pi is displayed and formatted into two decimals.

Example 3: Styling console output with %c

One of the powerful features of console.log() is the ability to apply CSS styles using the %c placeholder. This allows us to customize the appearance of the log messages with colors, fonts, and other CSS properties.

The CSS styling is not supported by our code widget. Use the console of the browser to see the effect of the CSS styling in the following command. Open the browser’s console by following these steps.

  1. Open the Developer tools panel.

    • Google Chrome and Microsoft Edge: Press “Ctrl + Shift + I” or “F12”

    • Mozilla Firefox: Press “Ctrl + Shift + K” or “F12”

    • Safari: Go to Safari > Preferences or press “Command + ,” and click the "Advanced" tab. Check the option “Show Develop menu in menu bar”. Press “Command + Option + C” to open the console directly.

    • For macOS, use “Command + Option” inplace of “Ctrl + Shift”.

  1. Once the Developer tools are open, select the “Console” tab.

To apply CSS styling to a log message, use the %c placeholder, followed by the style as a string argument:

console.log("%cThis is a styled message!", "color: blue; font-size: 20px;");
Applying CSS Styling in JavaScript

The text “This is a styled message!” will be printed in blue with a font size of 20 px.

Output of the CSS styling using %c command
Output of the CSS styling using %c command

Example 4: Displaying objects and arrays with %o

To inspect objects or arrays, use %o, which outputs an interactive object in the browser’s console. Run the following commands into the browser’s console to see the interactive object in the console.

let person = { name: "Alice", age: 30 };
console.log("Person details: %o", person);

The object is logged in the console, which allows us to see its properties.

Example 5: Combining multiple data types in console.log()

We can log multiple variables, strings, objects, and other data types together in a single console.log() statement. This is particularly useful when debugging a function that returns several outputs or when we want to view multiple variables at once.

let name = "Alice";
let age = 30;
let isLoggedIn = true;
console.log("Name:", name, "| Age:", age, "| Logged In:", isLoggedIn);

In the above code, We display multiple values or states side by side. This technique helps in debugging.

Example 6: Group all related logs in console.logs()

If we have multiple related logs, use console.group() and console.groupEnd() to organize them in a collapsible format in the console.

let name = "Alice";
let age = 30;
let isLoggedIn = true;
console.group("User Info");
console.log("Name:", name);
console.log("Age:", age);
console.log("Logged In:", isLoggedIn);
console.groupEnd();

Limiting the use of the console.log() method

If we want to prevent console.log from being used by users, then we can assign the value of console.log to our function.

console.log = function() {
console.error(" Logging by user is disabled ");
}
console.log("Testing...");

Best practices for formatting console logs

Let’s discuss some best practices for formatting in console logs.

  1. Use clear and descriptive messages: Ensure the log messages are clear, descriptive, and relevant. This makes debugging easier when reviewing logs.

  2. Use CSS sparingly: While styled logs can be visually appealing, overuse can clutter the console. Use styling selectively, such as for important warnings or notable information.

  3. Remove or disable logs in production: Logging too much information in production code can affect performance. Be sure to remove or disable unnecessary logs before deploying the final code.

  4. Group all related logs: Similar or related logs should be grouped for better visibility.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

Why is it helpful to format messages in console.log()?

A)

It makes the logs look more professional.

B)

It helps highlight important data and improves readability.

C)

It allows logs to be stored as JSON objects.

D)

It automatically saves the logs to a file.

Question 1 of 30 attempted

Conclusion

Formatting messages in the console.log() method enhances the debugging process by making logs easier to read and interpret. Using placeholders, applying CSS styling, and combining various data types in a single log output makes complex logs more manageable and provides better context during debugging. We should practice clear messaging, group all related logs, and limit unnecessary logs in production to ensure efficient development and performance.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


Is it possible to format text in console.log()?

Yes, we can format text in console.log() using placeholders and CSS styles. Placeholders like %s for strings, %d for integers, and %c for applying CSS styles allow you to structure the output and make logs more readable.


How to style console messages

To style console messages, use the %c placeholder in the console.log() method, followed by a string that contains CSS style properties. For example:

console.log('%cThis is a styled message!', 'color: blue; font-size: 20px;');

This will display the text with the specified styling.


What format is a logger log message?

Logger log messages typically include placeholders to format different data types like strings (%s), integers (%d), floating-point numbers (%f), and objects (%o). These placeholders are replaced with the corresponding data passed as arguments in console.log().


How to console log with style

To log with style, use the %c placeholder in combination with CSS styling rules. For example, to change the text color and size, we can do:

console.log('%cStyled message', 'color: red; font-weight: bold;');

This allows to customize the appearance of console logs, making important messages stand out.


Free Resources

Attributions:
  1. undefined by undefined