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.
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()
.
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.
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.
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.
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
.
%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.
%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.
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”.
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;");
The text “This is a styled message!” will be printed in blue with a font size of 20 px.
%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.
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.
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();
console.log()
methodIf 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...");
Let’s discuss some best practices for formatting in console logs.
Use clear and descriptive messages: Ensure the log messages are clear, descriptive, and relevant. This makes debugging easier when reviewing logs.
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.
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.
Group all related logs: Similar or related logs should be grouped for better visibility.
Let’s attempt a short quiz to assess your understanding.
Why is it helpful to format messages in console.log()
?
It makes the logs look more professional.
It helps highlight important data and improves readability.
It allows logs to be stored as JSON objects.
It automatically saves the logs to a file.
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.
Haven’t found what you were looking for? Contact Us
Free Resources