JavaScript Formatting console output


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:

%sFormats the value as a string
%i or %dFormats the value as an integer
%fFormats the value as a floating point value
%oFormats the value as an expandable DOM element
%OFormats the value as an expandable JavaScript object
%cApplies 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');



It is possible to use multiple %c format specifiers:

  • any substring to the right of a %c has a corresponding parameter in the print method;
  • this parameter may be an emtpy string, if there is no need to apply CSS rules to that same substring;
  • if two %c format specifiers are found, the 1st (encased in %c) and 2nd substring will have their rules defined in the 2nd and 3rd parameter of the print method respectively.
  • if three %c format specifiers are found, then the 1st, 2nd and 3rd substrings will have their rules defined in the 2nd , 3rd and 4th parameter respectively, and so on...
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


multiple CSS specifiers output

Using groups to indent output

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

  • console.groupCollapsed(): creates a collapsed group of entries that can be expanded through the disclosure button in order to reveal all the entries performed after this method is invoked;
  • creates an expanded group of entries that can be collapsed in order to hide the entries after this method is invoked.

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

  • console.groupEnd(): exits the current group, allowing newer entries to be printed in the parent group after this method is invoked.

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

Collapsed group = Collapsed group expanded => Expanded group