console.log: Your Flashlight

Summer School, page 5 of 11. A two-minute read.

The most popular debugging tool in the world is also the simplest: console.log. When your code isn't doing what you expect, put console.log statements in to see what's actually happening inside it. It's like shining a flashlight into a dark room.

Let's debug a real example. This function is supposed to calculate the total price of a shopping cart, but the answer is wrong:

JavaScript
function cartTotal(prices) {
  let total = 0;
  for (let i = 1; i < prices.length; i++) {
    total += prices[i];
  }
  return total;
}

console.log(cartTotal([10, 20, 30]));

It prints

50

We expected 60. Let's add some logging to see what's going on inside the loop:

JavaScript
function cartTotal(prices) {
  let total = 0;
  for (let i = 1; i < prices.length; i++) {
    console.log("i:", i, "price:", prices[i], "total before:", total);
    total += prices[i];
  }
  return total;
}

console.log(cartTotal([10, 20, 30]));

It prints

i: 1 price: 20 total before: 0
i: 2 price: 30 total before: 20
50

Aha! The loop never visits the price 10. The output shows i starting at 1, so we're skipping index 0. It's an off-by-one error! Change let i = 1 to let i = 0, remove the debugging log, and we get 60. Case closed. 🔍

Logging tips

Label your logs. A bare console.log(x) that prints 7 is useless when you have ten logs. Always add a label:

JavaScript
const total = 60;
const count = 3;

console.log(total);
console.log("total:", total);
console.log({ total, count });

It prints

60
total: 60
{ total: 60, count: 3 }

That last trick is a favorite of professional developers. Wrapping variables in curly braces creates an object (using the shorthand from Grade 8), so you see both the names and the values.

Check the type. Many bugs come from a value being the wrong type, like a string "5" instead of a number 5. They look the same when logged! Add typeof:

JavaScript
const quantity = "5";
console.log("quantity:", quantity, typeof quantity);

It prints

quantity: 5 string

Other console methods. The console has a few more tricks up its sleeve:

  • console.error("Something broke") prints in red, like an error.
  • console.warn("Careful!") prints in yellow, as a warning.
  • console.table(arrayOfObjects) prints an array of objects as a beautiful table. (Try it in the browser with the students array from Grade 8!)
TipClean up after yourself

Debugging logs are temporary. Once you've found and fixed the bug, remove them (or comment them out). Leaving hundreds of console.log statements in your finished code is like leaving your detective's chalk outlines all over the crime scene.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning