Fix: Cannot read property 'length' of null
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.
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)
- Identify which variable is null (use console.log)
- Check if an API is returning null instead of []
- Use optional chaining (data?.length)
- 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
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.