Formatting console output

suggest change

Many of the console’s print methods can also handle C-like string formatting, using % tokens:

console.log('%s has %d points', 'Sam', 100);

Displays Sam has 100 points.

The full list of format specifiers in JavaScript is:

Specifier Output
%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
%O Formats the value as an expandable JavaScript object
%c Applies CSS style rules to the output string as specified by the second parameter

Advanced styling

When the CSS format specifier (%c) is placed at the left side of the string, the print method will accept a second parameter with CSS rules which allow fine-grained control over the formatting of that string:

console.log('%cHello world!', 'color: blue; font-size: xx-large');

Displays:

It is possible to use multiple %c format specifiers:

console.log("%cHello %cWorld%c!!", // string to be printed
            "color: blue;", // applies color formatting to the 1st substring
            "font-size: xx-large;", // applies font formatting to the 2nd substring
            "/* no CSS rule*/" // does not apply any rule to the remaing substring
);

Displays:

Using groups to indent output

Output can be idented and enclosed in a collapsible group in the debugging console with the following methods:

The identation can be removed for posterior entries by using the following method:

Groups can be cascaded to allow multiple idented output or collapsible layers within eachother:

= Collapsed group expanded =>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents