Null and undefined: the crash that happens far from the mistake
Cannot read properties of undefined, NoneType has no attribute, NaN appearing from nowhere.
What is null and undefined error?
A missing value gets used as if it were present. In JavaScript that is undefined or null; in Python it is None. The crash happens where the value is finally used, which is often nowhere near where it went missing.
Why it happens
Lookups that can fail return an empty result rather than raising: Array.find returns undefined, dict.get returns None, an out-of-range index returns undefined in JavaScript. Code then reads a property off it. The gap between where the empty value was created and where it blew up is what makes these hard to trace — the failing line is usually not the wrong line.
How to recognise it
- The error names a property you are certain exists.
- NaN appears in a calculation with no obvious source.
- It works with full data and fails with real, incomplete data.
- A legitimate 0 or empty string is being treated as missing.
Errors and symptoms this causes
- TypeError: Cannot read properties of undefined (reading 'x')
- TypeError: Cannot read properties of null
- AttributeError: 'NoneType' object has no attribute
- TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
- result is NaN
How to fix it
Check the result of anything that can fail to find something, before using it. Prefer ?? over || and `is None` over truthiness, because 0 and "" are falsy but not missing — that distinction is the source of a whole family of these. Work backwards from the crash to where the value was created; the bug is at the creation, not the crash.
Practise null and undefined errors
Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.