Chapter 16. Working with the Console

Introduction

Despite your best intentions, things can and will go wrong with your code. There are several debugging tools available to you. Today’s browsers have powerful debuggers built in to them that let you step through code and inspect the values of variables and expressions. Sometimes, though, you might want to keep it simple and use the console.

In its most basic form, you interact with the console by calling console.log with a message. This message is printed to the browser’s JavaScript console. While more verbose than breakpoint-based debugging, sometimes it can still be useful to log and inspect values at runtime.

Other than a simple console.log, there are other things you can do with the console such as group messages, use counters, display tables, and even style your output with CSS. There are also other log levels (error, warn, debug) that you can use to categorize and filter your console messages.

Styling Console Output

Problem

You want to apply some CSS to your console log output. For example, maybe you want to make the font larger and change the color.

Solution

Use the %c directive in your log message to denote what text you want styled. For each usage of %c, add another argument to console.log containing CSS styles (see Example 16-1).

Example 16-1. Styling console output
console.log('%cHello world!', 'font-size: 2rem; color: red;');
console.log('This console message uses %cstyled text. %cCool!',
  'font-style: italic;' ...

Get Web API Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.