Cannot read properties of undefined (reading 'length') in JS

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
4 min

banner

# Cannot read properties of undefined (reading 'length') in JS

The "TypeError: Cannot read properties of undefined (reading 'length')" error occurs when accessing the length property on an undefined value.

To solve the error, make sure to only access the length property on data types that support it - arrays and strings.

cannot read property length of undefined

Here is an example of how the error occurs.

index.js
const arr = undefined; // ⛔️ TypeError: Cannot read properties of undefined (reading 'length') arr.length;

cannot read properties of undefined reading length

# Use an if statement to avoid the error

One way to avoid the error is to use a simple if statement.

index.js
// ✅ with arrays const arr = []; if (arr) { console.log(arr.length); // 👉️ 0 } // ------------------------------------------ // ✅ with strings const str = 'abc'; if (str) { console.log(str.length); // 👉️ 3 }

use if statement to avoid the error

The code for this article is available on GitHub

We check if the variable stores a truthy value before accessing the length property.

undefined is a falsy value, so the if block won't run if the variable stores undefined.

# Provide a fallback value if the value is undefined

Alternatively, provide a fallback for the value before accessing the length property.

index.js
const fromDb = undefined; // ✅ with Arrays const arr = fromDb || []; console.log(arr.length); // 👉️ 0 // ----------------------------------------------- // ✅ with Strings const str = fromDb || ''; console.log(str.length); // 👉️ 0

provide fallback value if the value is undefined

The code for this article is available on GitHub

The logical OR (||) operator returns the value to the left if the value to the right is falsy (e.g. undefined).

We used a fallback of an empty array or empty string.

# Using the optional chaining operator (?.)

Use the optional chaining (?.) operator to short-circuit if the value is undefined.

index.js
const arr = undefined; const result = arr?.length || 0; console.log(result); // 👉️ 0 console.log(arr?.length); // 👉️ undefined

using the optional chaining operator

The code for this article is available on GitHub

The optional chaining (?.) operator short-circuits and returns undefined if the value to the left is nullish (null or undefined).

We also used the logical OR (||) operator to return 0 if accessing the length property returns undefined but this is not necessary.

# Check if the value is of the correct type before accessing length

You can also check if the value is of the correct type before accessing the length property.

index.js
const value = undefined; // ✅ Check if array before accessing length if (Array.isArray(value)) { const result = value.length; console.log(result); } else { console.log('The value is NOT an array'); } // ✅ Check if string before accessing length if (typeof value === 'string') { const result = value.length; console.log(result); } else { console.log('The value is NOT a string'); }

check if the value is of the correct type before accessing length

The code for this article is available on GitHub

The Array.isArray() method returns true if the value is an array and false otherwise.

We also used the typeof operator to check if the value is a string.

# Providing a fallback value in place to avoid the error

You can also provide a fallback value in place, right before accessing the length property.

index.js
const fromDb = undefined; const result1 = (fromDb || []).length; console.log(result1); // 👉️ 0 const result2 = (fromDb || '').length; console.log(result2); // 👉️ 0

If the variable stores a falsy value, the value to the right is returned.

# Using the ternary operator to avoid the error

You can also use the ternary operator, which is very similar to an if/else statement.

index.js
const str = undefined; const result = str ? str.length : 0; console.log(result); // 👉️ 0
The code for this article is available on GitHub

If the value to the left of the question mark is falsy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

# Track down where the variable got assigned an undefined value

If the error persists, you have to track down where the variable got assigned an undefined value.

The length property only exists on arrays and strings, so trying to access it on a value of any other type causes an error.

A common source of undefined values is assigning the output of a function that doesn't return anything to a variable.

Many built-in methods that mutate an object in place return undefined.

All JavaScript functions that don't return a value return undefined.

# Accessing an Array at an index that doesn't exist

The error commonly occurs when you access an array at an index that doesn't exist and get an undefined value back.

index.js
const arr = ['bobby', 'hadz', 'com']; // ⛔️ TypeError: Cannot read properties of undefined (reading 'length') const result = arr[3].length;
JavaScript indices are zero-based, so the first element in an array has an index of 0 and the last element has an index of array.length - 1.

The last index in the array in the example is 2.

index.js
const arr = ['bobby', 'hadz', 'com']; const result = arr[2].length; console.log(result); // 👉️ 3

You can use the optional chaining (?.) operator to avoid getting the error when accessing array elements that might not exist.

index.js
const arr = ['bobby', 'hadz', 'com']; const result = arr[100]?.length; console.log(result); // 👉️ undefined
The code for this article is available on GitHub

If you'd rather default the value to 0 if it's undefined, use the logical OR (||) operator.

index.js
const arr = ['bobby', 'hadz', 'com']; const result = arr[100]?.length || 0; console.log(result); // 👉️ 0

Use the same approach if you have to access nested array elements at indices that might not exist.

index.js
const nestedArr = []; console.log(nestedArr?.[0]?.length); // 👉️ undefined console.log(nestedArr?.[0]?.[0]?.length); // 👉️ undefined console.log(nestedArr?.[0]?.[0]?.[1]?.length); // 👉️ undefined

# Solve the error when working with classes

If you get the error when working with classes, you have to declare a class property and set it to an empty string or an empty array before accessing it.

index.js
class Person { first = ''; getLength() { return this.first.length; } } const p1 = new Person(); console.log(p1.getLength()); // 👉️ 0
The code for this article is available on GitHub

We initialized the value for the first class property. Had we not done that, we would have gotten the error when trying to access the length property.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.