JavaScript Intermediate: Data, the DOM and Events
Errors and Debugging
In this lesson you will
- Recognise common error types and read error messages
- Handle errors with try, catch and finally
- Debug with console output and the browser tools
Introduction
Professional developers spend a lot of time fixing bugs. The difference between a beginner and an expert is not that experts make fewer mistakes. It is that they know how to find them quickly. This lesson gives you that skill.
Common error types
Run each of these on its own to read the message.
- ReferenceError: the name does not exist (a typo, or out of scope).
- TypeError: the value is the wrong kind, such as reading a property of
undefined. - SyntaxError: a typo in the structure, such as a missing bracket. The code will not run at all.
Quick quiz
Reading a property of undefined, like user.name where user is undefined, causes which error?
try and catch
When something might fail, wrap it in try. If an error happens, JavaScript jumps to catch instead of crashing.
tryholds the risky code.catch (error)runs only if an error was thrown.finallyalways runs, whether there was an error or not.
Throwing your own errors
Use throw to report a problem, for example when a function receives bad input.
Debugging with the console
The simplest tool is still the best: print values and see.
In a real browser, the developer tools (usually the F12 key) add much more: the console, the Sources panel where you can set breakpoints to pause your code, and the Network panel. A debugger; statement pauses your code at that line when the tools are open.
Quick quiz
Which block of a try statement always runs, error or not?
A debugging routine
- Read the error message. It names the problem and the line number.
- Reproduce it: make the bug happen on demand.
- Narrow it down: print values to find where reality differs from what you expected.
- Change one thing at a time, and test again.
- If you are stuck, explain the problem out loud, step by step. This often reveals the answer.
Try it yourself
This function has a bug. It should return the largest number in an array, but it gives the wrong answer. Use console.log to find the problem and fix it.
Hint: what is wrong with starting max at 0 when every number is negative?
Summary
- Learn the three common errors: ReferenceError, TypeError and SyntaxError.
try/catch/finallyhandle failures without crashing.throw new Error()reports your own.- Debug by reading messages, printing values, and changing one thing at a time.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading