Last updated: Mar 3, 2024
Reading time·4 min
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.
Here is an example of how the error occurs.
const arr = undefined; // ⛔️ TypeError: Cannot read properties of undefined (reading 'length') arr.length;
if
statement to avoid the errorOne way to avoid the error is to use a simple if
statement.
// ✅ with arrays const arr = []; if (arr) { console.log(arr.length); // 👉️ 0 } // ------------------------------------------ // ✅ with strings const str = 'abc'; if (str) { console.log(str.length); // 👉️ 3 }
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
.
Alternatively, provide a fallback for the value before accessing the length
property.
const fromDb = undefined; // ✅ with Arrays const arr = fromDb || []; console.log(arr.length); // 👉️ 0 // ----------------------------------------------- // ✅ with Strings const str = fromDb || ''; console.log(str.length); // 👉️ 0
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.
Use the optional chaining (?.) operator to short-circuit if the value is
undefined
.
const arr = undefined; const result = arr?.length || 0; console.log(result); // 👉️ 0 console.log(arr?.length); // 👉️ undefined
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.
length
You can also check if the value is of the correct type before accessing the
length
property.
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'); }
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.
You can also provide a fallback value in place, right before accessing the
length
property.
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.
You can also use the
ternary operator, which
is very similar to an if/else
statement.
const str = undefined; const result = str ? str.length : 0; console.log(result); // 👉️ 0
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.
undefined
valueIf 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.
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
.
The error commonly occurs when you access an array at an index that doesn't
exist and get an undefined
value back.
const arr = ['bobby', 'hadz', 'com']; // ⛔️ TypeError: Cannot read properties of undefined (reading 'length') const result = arr[3].length;
0
and the last element has an index of array.length - 1
.The last index in the array in the example is 2
.
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.
const arr = ['bobby', 'hadz', 'com']; const result = arr[100]?.length; console.log(result); // 👉️ undefined
If you'd rather default the value to 0
if it's undefined
, use the logical OR
(||) operator.
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.
const nestedArr = []; console.log(nestedArr?.[0]?.length); // 👉️ undefined console.log(nestedArr?.[0]?.[0]?.length); // 👉️ undefined console.log(nestedArr?.[0]?.[0]?.[1]?.length); // 👉️ undefined
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.
class Person { first = ''; getLength() { return this.first.length; } } const p1 = new Person(); console.log(p1.getLength()); // 👉️ 0
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.