Colors in JavaScript Console

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 on Chromium based browsers. It doesn't work in Node.js and it doesn't always get you what you want on other browsers like Firefox. 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.

console.log('%c Hi everyone!', 'color: #1c87c9; font-size: 18px');

If you want to add multiple style, you should add multiple “%c” text and add style arguments:

console.log('%c Style 1! %c Style 2!',
  'color: #1c87c9; background: #ccc; font-size: 20px;', 
  'color: #8ebf42; background: # 666; font - size: 20 px;'
);

The hard way

The hard way always woks! But you need to have the ANSI Escape Code of your specific color. A short list of these codes are 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 onlything to do is to start our log message with one of these codes. See the example below.console.log('\u001b[32m Hello World!');

console.log("\u001b[32m Hello World");

About console.log() method

The console.log() method outputs a message to the web console. The message may be either a single string or JavaScript objects. The console.log() 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 console.warn() and console.error() methods to specify warnings and errors, respectively.

console.warn('WARNING!');
console.error('ERROR!');