Useful tricks for logging debugging information to the browser console

Posted . Visible to the public.

During debugging you might pepper your code with lines like these:

console.log('foo = ' + foo + ', bar = ' + bar)

I recommend to use variable interpolation instead:

console.log('foo = %o, bar = %o', foo, bar)

This has some advantages:

  1. It's easier to write
  2. Variables are colored in the console output
  3. You don't need to stringify arguments so the + operator doesn't explode
  4. If the variable is a structured object like a DOM element or an object has, you will be able to expand it inside the console and look at its contents

Another concise way to write the statement is this:

console.log({ foo, bar });

This uses Javascript's new destructuring syntax Show archive.org snapshot and is actually shorthand for:

console.log({ foo: foo, bar: bar });

Like above, you will be able to expand this object inside the console and look at its contents.

Henning Koch
Last edit
Henning Koch
Keywords
developer, console, development, console
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-01-30 16:32)