What is debugging?
Learn the debugging process and effective approaches.
What is debugging?
Debugging is the process of finding and fixing unexpected behavior in your code. A bug usually shows up as a wrong result, a crash or unexpected behavior. A good process has five steps: reproduce, isolate, understand the cause, fix and verify.
The most important step is reducing the bug to a small, repeatable example. If you cannot reproduce the bug, you cannot prove the fix works.
The five-step process
Let us apply the five steps in order. Reproduce: find the smallest input that triggers the bug. Isolate: narrow down to the line or function that causes it. Understand the cause: compare expected and actual behavior.
Then fix: make the smallest change that targets the root cause. Finally verify: run both the bug case and other cases again to make sure the fix did not break anything else.
Exercise Log values to the console
Define a function called sumPositive(nums). It should loop through nums with for...of and add numbers greater than or equal to 0 to total. Inside the loop, log each value with console.log(num). Then assign the result of sumPositive([3, -2, 5]) to a variable result and log it with console.log(result).
Show example solution
function sumPositive(nums) {
let total = 0;
for (const num of nums) {
console.log(num);
if (num >= 0) {
total += num;
}
}
return total;
}
const result = sumPositive([3, -2, 5]);
console.log(result);
Test yourself
-
Which is the first step of the debugging process?
- Reproduce the bug
- Rewrite all the code
- Delete every variable
- Restart the computer
Show answer
Reproduce the bug — Correct. You must reproduce the bug first; a bug you cannot repeat is hard to fix.
-
Complete the process step
console.log("step 1: reproduce the ____");Show answer
console.log("step 1: reproduce the bug"); -
Match the step to its meaning
- Reproduce
- Trigger the bug again with a small input
- Isolate
- Narrow down to the line that causes it
- Fix
- Change the code and remove the bug
- Verify
- Prove that the fix really works