JuniorJavaScript

What is a stack trace? When you see "Cannot read properties of undefined", how do you find the cause?

A stack trace is the list of function calls that were still in progress when an error happened, with the file name, line and column of each call. In JavaScript, the top frame is where the error happened; the frames below it are the path that led there.

For TypeError: Cannot read properties of undefined (reading 'name'), a good answer goes through these steps:

  1. Read the message: the property being read is name, so whatever comes right before .name is undefined.
  2. Find the first frame from your own code: skip frames in node_modules or node:internal, then open that exact file, line and column.
  3. Trace the data back: the line that threw is where the error showed up, not necessarily where it started. Walk down the frames to see where the undefined value came from: an API that hasn't returned yet, empty initial state, or data that is missing a field.
  4. Reproduce it with the smallest possible example, then fix it in the right place: fix the data at its source, or handle a legitimate missing value with a default or ?..

Bonus points if you add that when you catch an error and throw a new one, new Error("…", { cause: err }) keeps the original error, and that minified production code needs source maps before its stack traces are readable.