Colors in JavaScript Console
The console.log() method outputs a message to the web console. Read the tutorial and learn the simplest method of putting a single or multiple styles to it.
To have colorful logs, there is an easy way that works only in specific situations, and a hard way that always works.
The easy way
The easy way works in most modern browsers, including Chrome, Firefox, and Safari. It doesn't work in Node.js. But it's a quick way that can help you especially if you're testing your web page with Chrome. In this case, you can use %c within the first argument of console.log(). It will pick up the next argument as a CSS style for the “%c” pattern argument text.
Colors %c in javascript console
console.log('%c Hi everyone!', 'color: #1c87c9; font-size: 18px');If you want to add multiple styles, you should add multiple “%c” placeholders and provide corresponding style arguments:
Styles in javascript console
console.log('%c Style 1! %c Style 2!',
'color: #1c87c9; background: #ccc; font-size: 20px;',
'color: #8ebf42; background: #666; font-size: 20px;'
);The hard way
The hard way always works in terminal environments! But you need to use the ANSI Escape Code for your specific color. A short list of these codes is provided here:
- Black:
\\u001b[30m - Red:
\\u001b[31m - Green:
\\u001b[32m - Yellow:
\\u001b[33m - Blue:
\\u001b[34m - Magenta:
\\u001b[35m - Cyan:
\\u001b[36m - White:
\\u001b[37m - Reset:
\\u001b[0m
Now the only thing to do is to start your log message with one of these codes. See the example below.
Log a green hello world with ANSI Escape Codes
console.log("\u001b[32m Hello World");About the console.log() method
The <kbd class="highlighted">console.log()</kbd> method outputs a message to the web console. The message may be either a single string or JavaScript object. The <kbd class="highlighted">console.log()</kbd> function is mostly used for debugging purposes as it makes JavaScript print the output to the console.
Printing errors and warnings
The JavaScript console also provides special methods to print warnings and errors. You can use <kbd class="highlighted">console.warn()</kbd> and <kbd class="highlighted">console.error()</kbd> methods to specify warnings and errors, respectively.
warn and error methods
console.warn('WARNING!');
console.error('ERROR!');