← Tous les articles

JavaScript “Cannot read properties of undefined”: understand and fix it

JavaScript's most common error means you read a property on a missing value. The typical causes and the habits that prevent it.

JavaScript “Cannot read properties of undefined”: understand and fix it

Key points

  • The error happens when reading a property of undefined or null.
  • The console gives the line; the property name tells you what was missing.
  • Optional chaining and load-order checks prevent most cases.

“Uncaught TypeError: Cannot read properties of undefined (reading ‘length’)” tells you exactly what happened: the code tried to read .length on something that did not exist. The question is why that value was missing.

The four causes we run into

  • The script runs before the HTML: document.querySelector('.menu') returns null because the element is not there yet. Load the script with defer or wait for DOMContentLoaded.
  • The element does not exist on this page: a site-wide script looks for a form that only lives on the contact page.
  • An unexpected API response: data.items is missing because the API returned an error.
  • Async data not there yet: reading a fetch result before the await.

Good habits

Exit early when the element is missing:

const form = document.querySelector('#contact-form');
if (!form) return; // not on this page
form.addEventListener('submit', onSubmit);

Use optional chaining and a default for external data:

const count = data?.items?.length ?? 0;

Check the response before reading it:

const res = await fetch(url);
if (!res.ok) throw new Error('API ' + res.status);
const data = await res.json();

Finding the cause fast

In the console, click the file link to the right of the message: the browser opens the exact line. Set a breakpoint just before it, reload, and inspect the variable. It beats sprinkling console.log everywhere.

FAQ

Does optional chaining hide bugs?

It can if used everywhere. Keep it for genuinely optional data; elsewhere, an explicit error is better.

It only happens in some browsers

Usually a different load order or a browser extension. Try a private window.

Facing this on your site? We diagnose and fix it without putting your content at risk.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →