Blog |

How to Fix TypeError: Cannot Read Property Length of Undefined in JavaScript

How to Fix TypeError: Cannot Read Property Length of Undefined in JavaScript
Table of Contents

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!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape