Debugging
JavaScript · Unit 20: Testing and debugging
- Full plan
- JavaScript
- 10 exercises
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. Predict the output
totalis supposed to add the numbers up. What does this version print?2. Complete the code
Complete the trace so you can see how much has piled up on each turn.
3. Predict the output
The person types 18. What does it print?
4. Complete the code
The person types 7 and the sum comes out odd. Complete it to see what type the value is.
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. 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. Multiple choice
The program prints
inside: 5and thenoutside: 0. What does that trace tell you?8. Predict the output
The traces say which way the program went. What does it print?
9. Predict the output
Adding these three numbers gives something odd. What does the trace print?
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?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.