One of the most common errors we record, “Cannot read properties of undefined (reading ‘length’)”, turned up in our own logs recently while looking into an issue with Microsoft Edge and the Facebook sdk. Let’s dive into this error, what it means, and how to fix it.
Breaking down the Message
TypeError: Cannot read properties of undefined (reading 'length')
In older browsers, this might also be shown as:
Cannot read property 'length' of undefined
TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target object.
This message indicates that our code expects to have an object with a length
property, but that object was not present. length
is commonly used on string
and array
, but a custom object could also have this property.
This is a blocking error, and script execution will stop when this error occurs.
Understanding the Root Cause
This error can be thrown for a lot of reasons, as it is incredibly common to reference the length
property of string
or array
during everyday development. For example, if we had a function that acts on a string argument, but is called without a string, we would see this error.
function foo(myString) { if (myString.length >= 10) { // do something } } foo(); // Whoops! TypeError
In our case, we were intercepting a call to fetch
, and we had assumed the url
property would be a string.
But, dear developer, it was not always a string. 🤦♂️.
We had some code like this that intercepted fetch requests and recorded some metadata if the request was correct. It looked something like this:
ourInterceptedFetch(options) { if (options.url.length <= 0) { // fail out } }
We were doing appropriate defensive type checking to make sure that the options
argument had a valid url
property. Unfortunately, fetch also accepts options
to be any object with a stringifier: an object with a toString
method. Like this:
fetch({ toString: function() { return `https://whatever.com/`; } });
In this case, options.url
is undefined, so when we try to check options.url.length
, it blows up with our error, “Cannot read property ‘length’ of undefined”. Ugh.
While this may be valid, it is a bit weird, right? We thought so too.
How to Fix It
So how do we fix this and prevent it from happening again?
1. Understand why your object is undefined
First and foremost, you need to understand why this happened before you can fix it. You are probably not doing exactly the same thing we are, so the reason your object is undefined may be somewhat different. Consider:
- Are you relying on a network response to be a certain shape?
- Are you processing user-input?
- Is an external function or library calling into your code?
Or maybe its just a logical bug somewhere in your code.
2. Add Defensive Checking
Anytime you don’t completely control the input into your code, you need to be defensively checking that arguments have the correct shape. API response change, functions get updated, and users do terrible, terrible things.
For instance, if you have a fetch
request that receives a JSON response with a foo
string property, you might have a defensive check that looks like this:
fetch("https://example.com/api") .then(resp => { return resp.json(); }) .then(json => { if (!json || typeof json.foo != 'string') { // Record an error, the payload is not the expected shape. } });
3. Monitor Your Environment
You’ll need to make sure that the issue is really fixed and that the problem stops happening. Mistakes happen, APIs change, and users are unpredictable. Just because your application works today, doesn’t mean an error won’t be discovered tomorrow. Tracking when exceptional events happen to your users gives you the context to understand and fix bugs faster. Check out TrackJS Error Monitoring for the fastest and easiest way to get started.
Пытаюсь настроить выгрузку банковских выписок из почты в гугл таблицы.
При выполнении скрипта, прога ругается и выдает ошибку:
TypeError: Cannot read properties of undefined (reading 'length')
appendData_ @ json.gs:30
saveEmails @ json.gs:36
на этот кусок кода:
function appendData_(sheet, array2d) {
sheet.getRange(sheet.getLastRow() + 1, 1, array2d.length, array2d[0].length).setValues(array2d);
}
function saveEmails() {
var array2d = processEmails();
if (array2d) {
В чем может быть причина и как исправить?
-
Вопрос задан07 апр.
-
534 просмотра
Ошибка «TypeError: Cannot read properties of undefined (reading ‘length’)» означает, что переменная «array2d» не определена или имеет значение «undefined», когда вызывается свойство «length» у массива. Это может произойти, если функция «processEmails()» не возвращает массив, либо возвращает пустой массив.
Чтобы исправить ошибку, необходимо проверить, что функция «processEmails()» возвращает массив с данными, а не «undefined» или пустой массив. Можно добавить проверку на «undefined» перед вызовом функции или добавить условие для обработки пустого массива.
Пригласить эксперта
-
Показать ещё
Загружается…
04 июн. 2023, в 01:35
1500 руб./за проект
04 июн. 2023, в 01:25
40000 руб./за проект
03 июн. 2023, в 23:42
1500 руб./за проект
Минуточку внимания
The other answers are focusing on prop.items
list but in your question you mention that you get the exception when trying to access the length of the places
inside user
s.
You are getting the error message because some users may not have any places listed inside them, hence, no places list -> no length property.
To fix this, you need to check if the places list exists and then access its length:
placeCount={ user.places ? user.places.length : 0 }
Here, we use a ternary operator to check if user.places
exists, then we use the length, else use zero.
Edit:
As pointed out by Phil in the comments below, you can also use coalescing operator, which is much cleaner, like this:
placeCount={ user.places?.length ?? 0 }
The syntax simply translates as if user.places has a value for length, then use that value, else use zero as a default value.
Are you experiencing the “cannot read property ‘length’ of undefined” error in JavaScript? This error occurs when you attempt to access the length
property from a variable that has a value of undefined
.
const arr = undefined;
// TypeError: Cannot read properties of undefined (reading 'length')
const length = arr.length;
console.log(length);
To fix the “cannot read property ‘length’ of undefined” error, perform an undefined
check on the variable before accessing the length
property from it. There are various ways to do this.
1. Use an if Statement
We can use an if
statement to check if the variable is truthy before accessing the length
property:
const arr = undefined;
let arrLength = undefined;
// Check if "arr" is truthy
if (arr) {
arrLength = arr.length;
}
console.log(arrLength); // undefined
const str = undefined;
let strLength = undefined;
// Check if "str" is truthy
if (str) {
strLength = str.length;
}
console.log(strLength); // undefined
2. Use Optional Chaining
We can use the optional chaining operator (?.
) to return undefined
and prevent the method call if the variable is nullish (null
or undefined
):
const arr = undefined;
// Use optional chaining on "arr" variable
const arrLength = arr?.length;
console.log(arrLength); // undefined
const str = undefined;
// Use optional chaining on "str" variable
const strLength = str?.length;
console.log(strLength); // undefined
3. Access the length Property of a Fallback Value
We can use the nullish coalescing operator (??
) to provide a fallback value to access the length
property from.
const arr = undefined;
// Providing an empty array fallback
const arrLength = (arr ?? []).length;
console.log(arrLength); // 0
const str = undefined;
// Providing an empty string fallback
const strLength = (str ?? '').length;
console.log(strLength); // 0
The nullish 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(2 ?? 5); // 2
console.log(undefined ?? 5); // 5
We can also use the logical OR (||) operator to provide a fallback value from which to access the length
property.
const arr = undefined;
// Providing an empty array fallback
const arrLength = (arr || []).length;
console.log(arrLength); // 0
const str = undefined;
// Providing an empty string fallback
const strLength = (str || '').length;
console.log(strLength); // 0
Like the ??
operator, ||
returns the value to its left if it is not null
or undefined
. If it is, then ||
returns the value to its right.
4. Use a Fallback Value Instead of Accessing the length Property
We can also combine the optional chaining operator (?.
) and the nullish coalescing operator (??
) to provide a fallback value to use as the result, instead of accessing the length
property from the undefined
value.
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
As we saw earlier, the logical OR operator (||
) can replace the ??
operator in cases like this:
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
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
Sign up and receive a free copy immediately.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.
The TypeError: Cannot read property 'length' of undefined
is one of the most common type errors in JavaScript. It occurs when the length
property is read on an undefined variable.
Error message:
TypeError: Cannot read properties of undefined (reading 'length')
Error Type:
TypeError
What Causes TypeError: Cannot Read Property Length of Undefined
Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined
is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property 'length' of undefined
.
TypeError: Cannot Read Property Length of Undefined Example
Here’s an example of a JavaScript TypeError: Cannot read property 'length' of undefined
thrown when the length
property is attempted to be read on an undefined variable:
function myFunc(a) {
console.log(a.length);
}
var myVar;
myFunc(myVar);
Since the variable myVar
is declared but not initialized, it is undefined. When it is passed to the myFunc()
function, the property length
is attempted to be accessed. Since a
is undefined at that point, running the code causes the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
How to Avoid TypeError: Cannot Read Property Length of Undefined
When such an error is encountered, it should be ensured that the variable causing the error is assigned a value. The length
property is supported by data types such as arrays and strings. Custom objects can also have this property.
To avoid coming across situations where properties of undefined variables may be accessed accidentally, an if
check should be added before dealing with such variables:
if (myVar !== undefined) {
...
}
if (typeof(myVar) !== 'undefined') {
...
}
Updating the previous example to include an if
check:
function myFunc(a) {
if (a !== undefined) {
console.log(a.length);
}
}
var myVar;
myFunc(myVar);
Running the above code avoids the error since the property length
is only accessed if a
is not undefined
.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!