Node.js · 19/19 5 min
Reading stack traces and logs
Find your frame, decode the classic TypeErrors, and log like you mean it.
Find your frame
TypeError: Cannot read properties of undefined (reading 'price')
at calcTotal (src/services/cart.js:14:22) ← your code: start here
at Array.reduce (<anonymous>)
at checkout (src/controllers/checkout.js:9:18)
at Layer.handle (node_modules/express/lib/router/layer.js:95:5)
Skip node_modules and <anonymous> frames. The first frame in your code is where it blew up; the next ones show who called it.
Decode the message
| Message | Usually means |
|---|---|
Cannot read properties of undefined (reading 'x') |
the thing before .x is undefined: a missing await, wrong key, empty find |
x is not a function |
wrong import shape, or a value shadowed a function |
x is not defined |
typo, or missing import |
Cannot set headers after they are sent |
responded twice: missing return |
Converting circular structure to JSON |
sending a request/response or Mongoose doc with cycles |
Assignment to constant variable |
reassigned a const |
Maximum call stack size exceeded |
recursion without a base case, or a getter calling itself |
Log with intent
console.log({ id, cart }); // label every value
console.log(JSON.stringify(order, null, 2));
console.log(typeof price, price); // "string 10" explains a lot
- Log at the boundary where expected and actual diverge, not everywhere.
- Log types, not just values:
"10"and10print the same. - Remove the logs once the test is green.
Narrate
"The test expects 201 and gets 500. The stack says cart.js:14, item is undefined, so find returned nothing. I think the id is a string and the stored id is a number." That's the hypothesis-driven loop interviewers want to hear.
Practise it now
Next in Node.js
The event loop, visually