[Solved] TypeError: Cannot read property ‘length’ of null

Total
8
Shares

The TypeError: Cannot read property ‘length’ of null occurs if you are trying to get the length of an object that is null.

In this tutorial we will look at what exactly is TypeError: Cannot read property ‘length’ of null and how to resolve this error with examples.

What is TypeError: Cannot read property ‘length’ of null?

This error indicates that the code is trying to compute the length property on a null variable. A null variable holds no or nonexistence value. Hence trying to calculate the length of a non-existent value is not possible. It is like counting the number of apples in an empty bag.

We may get no or undefined output if we implement length operation on data types that do not support it. Arrays and strings are the only two data that implement this property. Thus using it with any other data type will give the error.

It is a blocking error and will halt the execution. It is important to provide a fallback to the data passed.

Let us take a simple example to reproduce this error.

var number = null;
len = number.length;
console.log(len);

Output

len = number.length;
          ^
TypeError: Cannot read property 'length' of null

In the above example we are are trying to get the length on null value and hence we get a TypeError.

How to fix TypeError: Cannot read property ‘length’ of null?

There are mainly two approaches that we can use to fix the error. Let’s look at each of these solutions in detail with examples.

  1. Provide a fallback value in case the length is not defined or null.
  2. Check data type before using the length operator.

Solution 1: Providing the default fallback value

The fallback value can be referred to as the alternate value to be used in case the length is null. There are different ways to provide the fallback value.

Let’s understand with an example.

const ArrayVal = null;
const arr = ArrayVal || [];
console.log('The length is', arr.length); 

Output

The length is 0             

This method uses an empty array as a fallback value. A pipe || appends the fallback value. So when it cannot determine the length as the object turns out to be null, it considers empty array as fallback [] for length operation. For string data type, we can use empty string ('') instead of [].

Solution 2: Checking data type before using the length property

Another way to avoid this error is type checking before using the length operator. Using this approach acts as a condition for calculating the length of a variable so that it does not throw a Cannot read property ‘length’ of null error.

The below code snippet shall explain this in detail.

const ArrayVal = null;
if (Array.isArray(ArrayVal)) {
    console.log('This is a valid array');
} else {
  console.log('The variable is not a valid array');
}

Output

The variable is not a valid array

In the above example, we can use the inbuilt method isArray() method to check the variable type before proceeding further. Similarly can be done with the string data type.

const StringVal = null;
if (typeof StringVal === 'string') {
 console.log('It a string');
} else {
  console.log('It is not a string');
}

Output

It is not a string

In the above example, we can use the inbuilt method typeof operator to check the variable type is ‘string‘ before proceeding further.

Conclusion

The TypeError: Cannot read property ‘length’ of null occurs if you are trying find the length of an object expecting the type of array or string but in reality it turns out to be null or undefined. We can resolve this error by performing the type check or by providing the fallback mechanism in case of null.

To summarize, both the solutions are effective in handling the error. The first solution is preferred if we have a large piece of code with multiple processing as this approach handles the null pointer at declaration itself. The second approach is useful in cases of low computation.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like
JavaScript String toLowerCase()

JavaScript String toLowerCase()

Table of Contents Hide toLowerCase() ExampletoLowerCase() SyntaxtoLowerCase() ParametertoLowerCase() Return ValueExample: JavaScript Convert string from uppercase to lowercase In this tutorial, we will learn about the JavaScript String toLowerCase() method with…
View Post
JavaScript Recursive Function

JavaScript Recursive Function

Table of Contents Hide Introduction to the JavaScript recursive functionsJavaScript recursive function examples1) A simple JavaScript recursive function example2) JavaScript Program to Find Factorial of Number Using RecursionWhy don’t we…
View Post