JavaScript Error

Fix: Cannot read property 'length' of null

By Samrat•Last updated: Nov 2026

Exact message

TypeError: Cannot read properties of null (reading 'length')

Quick answer

This happens when you try to get the .length of a variable that is null. Ensure the variable is an array or string before checking its length, or use optional chaining (?.length).

🛠️ Fix it right here with AI Code Explainer

Edit the traceback below if needed, then let our AI suggest a fix without leaving this page.

AI suggestions can be wrong. Review and test before applying.

Why this error happens

Unlike undefined, null is an explicit assignment representing 'no value'. Accessing .length on null throws an error. This often happens when an API returns null instead of an empty array [].

Example: Wrong vs Right

Wrong

let items = null;
console.log(items.length);
// TypeError: Cannot read properties of null

Right

let items = null;

console.log(items?.length || 0);

items = items || [];
console.log(items.length);

How to fix it (step by step)

  1. Identify which variable is null (use console.log)
  2. Check if an API is returning null instead of []
  3. Use optional chaining (data?.length)
  4. Provide a fallback value: (data || []).length

Frequently asked questions

What is the difference between null and undefined?

undefined means a variable has been declared but not assigned a value. null is an explicit assignment representing no value.

How to check if a variable is an array?

Use Array.isArray(myVar). This returns true for arrays and false for null, undefined, objects, and strings.

Related Search Terms

cannot read property length of nullreading length of nulllength of undefined javascript

Related JS errors

Need to fix JS code not just errors?

Use the free to paste any JS snippet and get a line-by-line explanation.

Want an AI with memory for your project?

MonsterX AI remembers your codebase across chats.