Null Value Problem
Quick summary
You operated on a value that is `null` — calling a method or reading a property on `null` causes an error.
Why this happens
A function returned
nullunexpectedly (e.g.,querySelectorfound no element)A variable was explicitly set to
nullMissing data from an API response or database lookup
Minimal example
const user = null;
console.log(user.name);const user = null;
console.log(user?.name);user is null, so accessing .name throws a TypeError — optional chaining (?.) returns undefined instead.
How to diagnose
Log the value before the line that fails to confirm it is
nullTrace where the
nullcame from — which function or data source produced itCheck API documentation for fields that may be
null
How to fix
Add a null check before using the value (
if (value !== null))Use optional chaining (
value?.property) to safely access propertiesProvide a fallback or default value when the value is
null
How to prevent
Always check for
nullbefore accessing properties on uncertain valuesUse optional chaining consistently in JavaScript and TypeScript
Related Resources
Related Practice
- Identify the Data Type
Practice recognizing data types including null.