How to Fix the "Cannot read property of undefined" Error in JavaScript

Last updated on October 24, 2023
How to Fix the "Cannot read property of undefined" Error in JavaScript

The "cannot read property of undefined" error happens when you try to access a property or method of a variable that is undefined. To fix it, add an undefined check on the variable before you access it.

The "Cannot read property of undefined" error happening in JavaScript.
The "Cannot read property of undefined" error happening in JavaScript.

Depending on your scenario, doing any one of the following might resolve the error:

  1. Add an undefined check on the variable before you access it.
  2. Get the property/method from a replacement for the undefined variable.
  3. Use a fallback result instead of accessing the property.
  4. Check your code to find out why the variable is undefined.

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

1. Add undefined check on variable

To fix the "cannot read property of undefined" error, check that the value is not undefined before accessing the property.

For example, in this code:

const auth = undefined;

console.log(auth); // undefined

// ❌ TypeError: Cannot read properties of undefined (reading 'user')
console.log(auth.user.name);


We can fix the error by adding an optional chaining operator (?.) on the variable before accessing a property. If the variable is undefined or null, the operator will return undefined immediately and prevent property access.

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.user?.name); // undefined


The optional chaining operator also works when using bracket notation for property access:

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.['user']?.['name']); // undefined


This means that we can use it on arrays:

const arr = undefined;

console.log(arr?.[0]); // undefined

// Array containing an object
console.log(arr?.[2]?.prop); // undefined

Before the optional chaining was available, the only way we could avoid this error was to manually check for the truthiness of every containing object of the property in the nested hierarchy, for example:

const a = undefined;

// Optional chaining
if (a?.b?.c?.d?.e) {
  console.log(`e: ${e}`);
}

// No optional chaining
if (a && a.b && a.b.c && a.b.c.d && a.b.c.d.e) {
  console.log(`e: ${e}`);
}

2. Use replacement for undefined variable

In the first approach, we don't access the property or method when the variable turns out to be undefined. In this solution, we provide a fallback value that we'll access the property or method on.

Here, we use ?? to set the variable to a default string value if undefined, to avoid the "Cannot read property 'replace' of undefined" error.

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

The logical OR (||) operator can also do this:

console.log(5 || 10); // 5
console.log(undefined || 10); // 10

3. Use fallback value instead of accessing property

Another way to solve the "cannot read property of undefined" error is to avoid the property access altogether when the variable is undefined and use a default fallback value instead.

We can do this by combining the optional chaining operator (?.) and the nullish coalescing operator (??).

By using 0 as a fallback in this example, we prevent the "Cannot read property 'length' of undefined" error.

const arr = undefined;

// Using "0" as a fallback value
const arrLength = arr?.length ?? 0;

console.log(arrLength); // 0


const str = undefined;

// Using "0" as a fallback value
const strLength = str?.length ?? 0;

console.log(strLength); // 0

4. Find out why the variable is undefined

The solutions above are handy when we don't know beforehand if the variable will be undefined or not. But there are situations where the "cannot read property of undefined" error is caused by a coding error that led to the variable being undefined.

Make sure variables are initialized

It could be that you forgot to initialize the variable:

let doubles;

const nums = [1, 2, 3, 4, 5];

for (const num of nums) {
  let double = num * 2;

  // ❌ TypeError: cannot read properties of undefined (reading 'push')
  doubles.push(double);
}

console.log(doubles);

In this example, we call the push() method on the doubles variable without first initializing it, which causes the "Cannot read property 'push' of undefined" error.

let doubles;

console.log(doubles); // undefined

Because an uninitialized variable has a default value of undefined in JavaScript, accessing a property/method causes the error to be thrown.

The obvious fix for the error, in this case, is to assign the variable to a defined value.

// ✅ "doubles" initialized before use
let doubles = [];

let nums = [1, 2, 3, 4, 5];

for (const num of nums) {
  let double = num * 2;

  //  push() called - no error thrown
  doubles.push(double);
}

console.log(doubles); // [ 2, 4, 6, 8, 10 ]

Make sure called function returns value

If the property you're accessing is from a function call result, the error may have occurred because you forgot to actually return a value in the function.

This mistake commonly causes the "Cannot read property 'then' of undefined" error in JavaScript:

function fetchData(apiUrl) {
  // 👇 `return` keyword missing
  fetch(apiUrl).then((response) => {
    return response.json();
  });
}

// ❌ Cannot read property 'then' of undefined
fetchData('/api/data')
  .then((data) => console.log(data))

To fix the error in this case, we'll simply return fetch()'s Promise:

async function getUserData(userId) {
  if (userId) {
    const response = await fetch(`/api/users/${userId}`);
    return response.json();
  }
  // 😕 No return if userId is absent
}

// ❌ Cannot read property 'then' of undefined if userId is absent
getUserData().then(data => console.log(data));  

Make sure type is correct

Another common mistake that causes this error is accessing an element from an array variable before accessing an Array property/method instead of accessing the property/method on the actual array variable.

const array = [];

// ❌ TypeError: Cannot read properties of undefined (reading 'push')
array[0].push('html');
array[0].push('css');
array[0].push('javascript');

console.log(array);

Accessing the 0 property with bracket indexing gives us the element at the index 0 of the array. The array has no element, so arr[0] evaluates to undefined and calling push() on it causes the error.

To fix this, we need to call the method on the array variable, not one of its elements.

const array = [];

// ✅ Call push() on "array" variable, not "array[0]"
array.push('html');
array.push('css');
array.push('javascript');

console.log(array); // [ 'html', 'css', 'javascript' ]

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

See also