This is one of the most common JavaScript errors in web development. The error occurs when your code attempts to access the length property on a variable that is null. Unlike similar errors involving undefined, a null value typically indicates that a DOM API or storage operation couldn’t find what you were looking for.

The length property is commonly used with arrays and strings, making this error frequent in DOM manipulation, form handling, and data processing. The fact that the value is null (rather than undefined) tells you something specific: an API explicitly returned “nothing found” rather than the variable never being assigned.

Cannot read properties of null (reading ‘length’) is one of the most common JavaScript errors. In older browsers, you might see this displayed as: “Cannot read property ‘length’ of null”

Other browsers report this error differently:

  • Safari: null is not an object (evaluating '...length')
  • Firefox: TypeError: ... is null

If you’re seeing undefined instead of null, the cause is different:

The Problem

“Cannot read properties of null (reading ‘length’)” is a TypeError that occurs when JavaScript attempts to access the length property on a value that is null. This is a blocking error that stops script execution at the point where it occurs.

The error typically happens when a DOM API can’t find an element:


// Element doesn't exist in the DOM
const element = document.getElementById('nonexistent');
console.log(element.innerHTML.length);
// TypeError: Cannot read properties of null (reading 'length')

Key point: The value being null (not undefined) tells you that some API or operation explicitly returned “not found” or “no value.” This is an important clue for debugging.

Understanding the Root Cause

The distinction between null and undefined matters here. When you see null, it usually means:

  • A DOM method couldn’t find the element you requested
  • A storage API doesn’t have the key you asked for
  • A regex or string operation found no match
  • Code explicitly set a value to null

1. DOM Element Selection Failures

Most common cause: Methods like getElementById(), querySelector(), and closest() return null when they can’t find a matching element.

How to identify: Errors occur when your code runs before the DOM is ready, when element IDs have typos, or when elements are conditionally rendered and not yet present.

2. localStorage and sessionStorage Operations

The getItem() method returns null when the requested key doesn’t exist in storage.

How to identify: Errors occur when accessing stored data that was never set, was cleared, or the key name has a typo.

3. String and RegExp Match Operations

String.match() and RegExp.exec() return null when no match is found, not an empty array.

How to identify: Errors occur when processing text that doesn’t contain the expected pattern.

4. Detached or Removed DOM Elements

Properties like parentNode or parentElement return null for elements that have been removed from the DOM or were never attached.

How to identify: Errors occur after DOM manipulation operations or when working with dynamically created elements.

5. Explicit Null Assignment

Code may explicitly set variables to null as a placeholder or to indicate “no value,” and later operations forget to check for this.

How to identify: Review code flow to find where null values are intentionally assigned.

6. API Responses with Null Fields

Server responses may include null values for optional fields, which then get accessed without checking.

How to identify: Errors correlate with API calls and occur when processing response data.

How to Fix “Cannot read properties of null (reading ‘length’)”

Quick Troubleshooting Checklist

  • Check if DOM elements exist before accessing their properties
  • Verify element IDs and selectors match your HTML exactly
  • Ensure scripts run after the DOM is ready
  • Check localStorage keys for typos
  • Handle regex/match results that may be null
  • Add null checks before accessing length on dynamic values

If basic checks don’t resolve the issue, follow these systematic debugging steps:

Step 1: Identify What’s Returning Null

Use browser DevTools to pinpoint exactly which operation is returning null:

  1. Open DevTools Console (F12 or option-command-i)
  2. Look at the error stack trace to find the exact line
  3. Add a breakpoint or console.log before the problematic code
  4. Inspect which variable is null

// Debug by checking what's null
const element = document.getElementById('myElement');
console.log('Element found:', element); // null means element doesn't exist

const storedData = localStorage.getItem('myKey');
console.log('Stored data:', storedData); // null means key doesn't exist

const matches = someString.match(/pattern/);
console.log('Matches:', matches); // null means no match found

Step 2: Handle DOM Selection Safely

Always verify DOM elements exist before accessing their properties:


// Safe DOM element access
const element = document.getElementById('myElement');
if (element) {
  const textLength = element.textContent.length;
  console.log('Text length:', textLength);
} else {
  console.warn('Element not found: myElement');
}

// Using optional chaining (ES2020)
const textLength = document.getElementById('myElement')?.textContent?.length ?? 0;

// For querySelector with arrays
const items = document.querySelectorAll('.item');
console.log('Found items:', items.length); // querySelectorAll never returns null

Step 3: Wait for DOM Ready

Ensure your scripts run after the DOM is fully loaded:


// Option 1: DOMContentLoaded event
document.addEventListener('DOMContentLoaded', function() {
  const element = document.getElementById('myElement');
  // Element will exist if it's in the HTML
});

// Option 2: Place scripts at end of body
// <script src="app.js"></script> just before </body>

// Option 3: Use defer attribute
// <script src="app.js" defer></script> in <head>

Step 4: Handle localStorage Safely

Always check for null when retrieving stored values:


// Safe localStorage access
function getStoredArray(key) {
  const stored = localStorage.getItem(key);

  if (stored === null) {
    console.log(`No data found for key: ${key}`);
    return [];
  }

  try {
    return JSON.parse(stored);
  } catch (e) {
    console.error('Failed to parse stored data:', e);
    return [];
  }
}

// Usage
const items = getStoredArray('myItems');
console.log('Item count:', items.length); // Safe, always an array

Step 5: Handle Regex and String Matching

String.match() returns null when there’s no match, not an empty array:


// Unsafe: match() returns null when no match
const text = 'Hello world';
const matches = text.match(/\d+/); // No digits in string
console.log(matches.length); // TypeError: Cannot read properties of null

// Safe: Check for null first
const matches = text.match(/\d+/);
if (matches) {
  console.log('Found matches:', matches.length);
} else {
  console.log('No matches found');
}

// Alternative: Use nullish coalescing
const matchCount = text.match(/\d+/)?.length ?? 0;

Step 6: Use Defensive Programming Patterns

Build functions that handle null values gracefully:


// Defensive function for getting element text length
function getElementTextLength(selector) {
  const element = document.querySelector(selector);

  if (!element) {
    console.warn(`Element not found: ${selector}`);
    return 0;
  }

  return element.textContent?.length ?? 0;
}

// Defensive function for array-like operations
function safeLength(value) {
  if (value === null || value === undefined) {
    return 0;
  }

  if (typeof value === 'string' || Array.isArray(value)) {
    return value.length;
  }

  return 0;
}

// Usage
console.log(safeLength(document.getElementById('missing')?.textContent)); // 0
console.log(safeLength('hello')); // 5
console.log(safeLength(null)); // 0

Step 7: Monitor Null Property Errors in Production

These errors often only appear in production where real users encounter edge cases you didn’t anticipate. Set up monitoring to catch and understand these errors as they happen. Error monitoring services like TrackJS can help you identify patterns in null property access errors, showing you which DOM selectors fail, which localStorage keys are missing, and which user flows trigger the errors.

Monitor for trends like increases in these errors after deployments, which might indicate broken selectors or missing elements.

When to Ignore This Error

“Cannot read properties of null (reading ‘length’)” should rarely be ignored, as it usually indicates a real problem. However, consider the context:

  • Browser extension interference: Extensions modifying your DOM can cause elements to disappear
  • Race conditions in SPAs: Framework routing may cause brief periods where elements don’t exist
  • Third-party widgets: External code accessing elements it expects but your page doesn’t have

Investigate further when you see:

  • Consistent patterns: Same selector failing repeatedly
  • User-facing impact: Errors breaking core functionality
  • Production spikes: Sudden increases after deployments
  • Critical user flows: Errors affecting forms, checkout, or navigation

Summary

“Cannot read properties of null (reading ‘length’)” tells you that a value you expected to be a string or array is actually null. The null value (rather than undefined) is an important clue: it usually means a DOM API couldn’t find an element, localStorage doesn’t have the key you requested, or a regex found no match.

The solution involves understanding which operation returned null and adding appropriate checks before accessing the length property. Focus on the APIs that commonly return null (getElementById, querySelector, localStorage.getItem, String.match) and ensure your code handles the “not found” case gracefully.

Remember: null means “intentionally no value” while undefined means “never assigned.” This distinction helps you trace back to the source of the problem.

TrackJS is the easy way to monitor your JavaScript applications and fix production errors. TrackJS is provides detailed error monitoring and alerting to developers around the world at companies like 3M, Tidal, IKEA, Venmo, Allbirds, and Frontend Masters. TrackJS catches millions of errors from users everyday. Let's start catching yours.

Protect your JavaScript