Module 6: Errors, Debugging, and Troubleshooting
Debugging Tips: Breakpoints, Logging, `debugger`
Debugging is the process of finding and fixing errors in your code.
-
console.log()
(and related methods):- The simplest debugging tool. Insert
console.log()
statements at various points in your code to inspect variable values, check execution flow, or confirm if a piece of code is being reached. - Other console methods:
console.error()
,console.warn()
,console.info()
,console.table()
(for arrays/objects),console.trace()
.
function calculate(a, b) { console.log("Calculating with a:", a, "and b:", b); let result = a * b; console.log("Result:", result); return result; }
- The simplest debugging tool. Insert
-
Browser Developer Tools Debugger (Breakpoints):
- Modern browsers have powerful built-in debuggers (usually in the "Sources" or "Debugger" tab of Developer Tools).
- Breakpoints: You can set breakpoints on specific lines of your code. When the JavaScript engine reaches a breakpoint, it pauses execution, allowing you to:
- Inspect the values of variables in the current scope.
- Step through the code line by line (
Step Over
,Step Into
,Step Out
). - Examine the call stack (the sequence of function calls that led to the current point).
- Watch expressions (monitor the value of specific expressions as you step).
- To set a breakpoint, open your script in the Sources panel and click on the line number.
-
debugger;
statement:- You can insert the
debugger;
statement directly into your JavaScript code. - If the browser's developer tools are open, execution will pause at this statement as if a breakpoint was set there.
function complexLogic(data) { // ... some code ... debugger; // Execution will pause here if DevTools are open // ... more code ... }
- You can insert the
-
Understand Error Messages:
- Pay close attention to error messages in the console. They usually provide the error type (e.g.,
TypeError
), a description, and the file name and line number where the error occurred.
- Pay close attention to error messages in the console. They usually provide the error type (e.g.,
-
Rubber Duck Debugging:
- Explain your code, line by line, to someone else or even to an inanimate object (like a rubber duck). Often, the act of verbalizing the logic helps you spot the error yourself.
-
Simplify and Isolate:
- If you have a complex bug, try to simplify the code or create a minimal reproducible example that still exhibits the bug. This makes it easier to pinpoint the source of the problem.