JavaScript:
Using a debugger
How to:
Here’s a bit of JavaScript code that’s not behaving as expected:
function buggyMultiply(a, b) {
return a + b; // Oops! This should be a multiplication, not addition.
}
let result = buggyMultiply(5, 3);
console.log('Result:', result);
The output is incorrect:
Result: 8
Let’s debug in Chrome DevTools:
- Open this JS in a browser.
- Right-click and select “Inspect” to open DevTools.
- Click the “Sources” tab.
- Find your code snippet or page and put a breakpoint by clicking on the line number beside the
return
statement. - Refresh the page to trigger the breakpoint.
- Check the “Scope” panel to see local variables
a
andb
. - Step through with the “Step over next function call” button.
- Spot the bug in the
return
statement. - Fix the code:
function buggyMultiply(a, b) {
return a * b; // Fixed!
}
let result = buggyMultiply(5, 3);
console.log('Result:', result);
The corrected output:
Result: 15
Deep Dive
The concept of debugging has been around since the early days of computing—legend says it started when a moth was found in a computer in the 1940s! Today, JavaScript debuggers like the built-in browser tools (Chrome DevTools, Firefox Developer Tools) or IDE integrated debuggers (Visual Studio Code, WebStorm) offer a ton of features.
Alternatives to built-in debuggers include third-party tools like WebStorm or using the good-old console.log
to output variable states. But these don’t offer the real-time interaction and detailed inspection provided by debuggers.
Regarding implementation details, most debuggers work similarly: they allow you to set breakpoints that pause execution, step through code, inspect current variable states, watch expressions, and even manipulate values on the fly to test different scenarios.