When it breaks: read the error
Red text is the engine talking to you
Sooner or later, the console fills with red. It's tempting to panic, or to paste the whole thing somewhere and hope. Don't. An error message is the engine telling you exactly what it couldn't do. It always has the same three parts:
- The type: what kind of problem.
ReferenceError,TypeError,SyntaxError. - The message: what the engine was trying to do when it failed.
- The location: the file, line and column. Below it, the chain of functions that led there (you'll understand that chain properly in the scope chapter).
Read the first line. Then go to that line. Most of the time, that's the whole job.
The three you'll meet most
ReferenceError: consol is not defined
You asked for a genie by name, and the Memory Tower has no record of him. Either he was never declared, there's a typo (consol instead of console), or he lives somewhere this code can't see.
Notice the difference: a genie that was declared but never assigned doesn't cause an error. He just points at undefined. A genie that doesn't exist at all is a ReferenceError.
TypeError: Cannot read properties of undefined (reading 'name')
The engine found the genie, but he's sitting on the volcano island of undefined, and you tried to get .name from it. Islands don't have properties. Remember the investigation, when you tried to add a property to null? Same problem, different island.
The question to ask: why is this genie pointing at undefined when I expected something else? Usually something earlier didn't give you what you thought, or a property name is misspelled.
TypeError: console.lg is not a function
You put parentheses after something, asking for it to be run, but the thing you pointed at isn't a function. console exists, but it has no lg - so you're trying to run undefined. A typo in a method name is the classic cause.
And one that stops everything: SyntaxError
SyntaxError: Missing initializer in const declaration means the engine couldn't even read your code, so nothing ran at all. That's why, in the investigation, the const productId; example didn't log a single line.
A routine for any error
- Read the type and message. Out loud, if it helps.
- Go to the line it points at.
- Ask: which value isn't what I expected? Log it:
console.log(user). - Work backwards to where that value came from.
If you do ask an AI for help, give it the full error, the line, and what you expected to happen - after you've made your own guess. Your guess is how you learn; the AI's answer is how you check it.
Try it
Before running each snippet, predict the error type and which genie or value is the problem.