Skip to content

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 null unexpectedly (e.g., querySelector found no element)

  • A variable was explicitly set to null

  • Missing data from an API response or database lookup

Minimal example

✗ Broken code
const user = null;
console.log(user.name);
✓ Fixed code
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 null

  • Trace where the null came from — which function or data source produced it

  • Check 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 properties

  • Provide a fallback or default value when the value is null

How to prevent

  • Always check for null before accessing properties on uncertain values

  • Use optional chaining consistently in JavaScript and TypeScript

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language