Error messages look intimidating at first, with their red text and strange words. But once you know how to read them, they're incredibly helpful. They tell you what went wrong and where.
Here's a typical error you might see in the browser console:
Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
at formatName (script.js:3:22)
at greetUser (script.js:8:15)
at script.js:12:1
Let's decode it, line by line:
TypeErroris the type of error. We know it's a "wrong type of value" problem.Cannot read properties of undefined (reading 'toUpperCase')is the message. Something wasundefined, and we tried to readtoUpperCasefrom it.at formatName (script.js:3:22)is where it happened: inside the functionformatName, in the filescript.js, on line 3, at character 22.- The lines below are the stack trace: the trail of function calls that led to the error. Read it from the bottom up: the main script (line 12) called
greetUser, which (on line 8) calledformatName, which crashed on line 3.
So now we know exactly where to look: line 3 of script.js. Something there was undefined. And the stack trace tells us it was called from greetUser on line 8, so maybe greetUser passed in the wrong thing.
In the browser console, the script.js:3 part is usually a clickable link. Click it and DevTools jumps straight to the exact line in your code. Very handy!
The error-reading routine
Whenever you see an error, follow these steps:
- Don't panic. Take a breath. It's just a clue.
- Read the error type. Syntax? Reference? Type? That narrows things down a lot.
- Read the message carefully. Every word matters. "is not defined" and "is not a function" mean very different things.
- Go to the line number. Look at that line, and the lines just before it.
- Ask "why?" Why is that value
undefined? Where did it come from? Follow the trail backwards. - Still stuck? Search for it. Copy the error message (minus your own variable names) into a search engine. You are almost certainly not the first person to see it.
For syntax errors in particular, the line JavaScript complains about isn't always the line with the mistake. If you forget a closing bracket on line 5, JavaScript might not notice until line 20, when it finally realizes something is missing. If the reported line looks perfectly fine, look above it.