Summary - Debugging
Test a calculation function using console.assert and console.trace.
Summary - Debugging
In this group you learned the core tools of debugging: the process (reproduce, isolate, understand, fix, verify), the call stack with console.trace, breakpoints with debugger, assertions with console.assert, and common bug patterns.
Now you will combine them: you will write a calculation function, check its expected result with console.assert and see the call trace with console.trace.
Exercise Assert the calculation function
Define a function called discount(price, rate). It should discount price by rate: return price - price * rate. Then check the expected result with console.assert(discount(100, 0.2) === 80, "discount wrong").
Show example solution
function discount(price, rate) {
return price - price * rate;
}
console.assert(discount(100, 0.2) === 80, "discount wrong");
Exercise Write the full test
Define a function called half(n); it should return n / 2. Add the debugger statement inside the function. Then check the result with console.assert(half(10) === 5, "half wrong") and print the call trace with console.trace("half trace").
Show example solution
function half(n) {
debugger;
return n / 2;
}
console.assert(half(10) === 5, "half wrong");
console.trace("half trace");
Test yourself
-
Match the tool to its purpose
- console.trace()
- Shows the call stack
- debugger
- Pauses code and opens tools
- console.assert(cond, msg)
- Warns when condition is false
- console.log(value)
- Writes the value to console
-
Add the call trace
function run() { compute(); console.____("run called"); }Show answer
function run() { compute(); console.trace("run called"); }