JavaScript course · Part 7: Finding faults · lab 9 of 11
Finding out what went wrong
Reading a stack trace, pausing your code and looking around with the debugger, and writing code that fails loudly instead of quietly.
By the end you can
- Use an error message and its stack to find the cause
- Pause running code and inspect it rather than guessing
- Check inputs where they arrive, not deep inside
- Fail loudly, so a fault is found in development rather than by a customer
Easier if you did first
step 1 of 3
Let the error tell you
Debugging is not a talent. It is a procedure, and the first step is to read what you were told rather than starting to change things.
An error has three parts. The type, which narrows the kind of fault. The message, which names the thing involved. And the stack, which lists the functions that were running, most recent first, with file and line numbers.
The top line of the stack is where it blew up. That is often not where the fault is. A value became undefined somewhere earlier, and the explosion happens at the first place something tried to use it.
So read upwards: what is this value, where did it come from, and was it ever what I assumed?
The second step is to halve the problem. One console.log halfway through tells you which half the fault is in, and two more halve it again. Three logs usually beat twenty minutes of staring.
The code on the right throws. Run it, read the message, fix the cause rather than the symptom. There are three faults, and the third does not throw at all, which is the most dangerous kind.
TypeError: Cannot read properties of undefined (reading "name")
at customerName (app.js:12)
at renderRow (app.js:28)
at renderList (app.js:40)
line 12 is where it broke
line 28 and 40 are who called it
the cause is usually what was passed inWhat these words mean
- stack trace
- The chain of functions that were running, most recent first.
- TypeError
- The value is not the kind of thing you used it as.
- ReferenceError
- That name does not exist here.
- halving
- A log in the middle tells you which half the fault is in.
- silent failure
- A wrong answer with no error. The hardest kind to find.
Easy to get wrong
Fixing the line the error points at
Finding where the bad value came from
Adding a ?. at the point of explosion stops the error and keeps the wrong data, so the fault moves somewhere else and becomes harder to find.
Changing several things at once
One change, then run it
With three changes you cannot tell which one helped, and you may have introduced a second fault that masks the first.
What we check
- A missing customer no longer throws
- A real name still comes back
- The count works
- The guests add up to 75, not a joined string
- And the total is a number
- The text value is converted deliberately
Nothing printed yet. Run your code.