Skip to the content

Debugging

JavaScript · Unit 20: Testing and debugging

Debugging is working out why a program isn't doing what you thought. The tool you have inside the app is console.log, and it covers almost everything.

Drop one inside the loop and watch how the variable changes on every turn.

function total(ns) {
  let t = 0;
  for (const n of ns) {
    t = t + n;
    console.log("t:", t);
  }
  return t;
}
console.log(total([3, 4]));

Prints

t: 3
t: 7
7

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    total is supposed to add the numbers up. What does this version print?

  2. 2. Complete the code

    Complete the trace so you can see how much has piled up on each turn.

  3. 3. Predict the output

    The person types 18. What does it print?

  4. 4. Complete the code

    The person types 7 and the sum comes out odd. Complete it to see what type the value is.

  5. 5. Find the bug

    This trace should show the position and the value of all three numbers. It skips the 4 and ends with undefined. Which line has the bug?

  6. 6. Put the lines in order

    Put mean(a, b) in order with a trace in the middle: first it adds, then it prints the sum and then it divides by 2.

  7. 7. Multiple choice

    The program prints inside: 5 and then outside: 0. What does that trace tell you?

  8. 8. Predict the output

    The traces say which way the program went. What does it print?

  9. 9. Predict the output

    Adding these three numbers gives something odd. What does the trace print?

  10. 10. Find the bug

    withTax(100) should print $116.00, because the tax adds 16 %. money(100) already prints fine. Which line has the bug?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →