Ошибка cannot read properties of null reading length

The «Uncaught TypeError: Cannot read properties of null (reading ‘length’)» error occurs in JavaScript, whenever you try to use the length property of an array (or string) on a variable that is null.

This usually happens when you receive your data from a database, and you don’t check whether the data exists in the first place. Take a look at the following example:

// Trying to fetch updates from a database that returns null
const updates = null

// ❌ This will throw: Uncaught TypeError: Cannot read properties of null (reading 'length')
if (!updates.length) {
    console.log('You are up to date! 🎉')
}

// The above translates to:
if (!null.length) { ... }

Copied to clipboard!

We expect the updates variable to be an array, but a null is returned and so we get the above-mentioned error. This is because null doesn’t have a length property. Try to run null.length in your console and you will get the same error.

Get your weekly dose of webtips

Get access to 300+ webtips 💌

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Master JavaScript


How to Fix the Error?

In order to fix the error, we need to make sure that the array is not null. In order to do this, the simplest way is to use optional chaining.

// ✔️ Even if updates is null, this will work
if (!updates?.length) {
    console.log('You are up to date! 🎉')
}

// The above translates to:
if (!null?.length) { ... }

The preferred way to avoid the error

Copied to clipboard!

You can use optional chaining by introducing a question mark after the variable. This ensures that the property will only be read if the variable indeed has a value.

We can also use a logical OR, or use the built-in Array.isArray method to check prior to using the length property to prevent running into issues.

// Using logical OR
const updates = null || []

// Using Array.isArray
if (Array.isArray(updates) && !updates.length) { ... }

Using logical OR and Array.isArray

Copied to clipboard!

In the first example, we fallback to an empty array, if the value retrieved, is null. This ensures that we will always be working with an array.

The second example uses Array.isArray to first check if we are working with an array. If this part evaluates to false, we won’t check the length property, therefore no error will be thrown. We can also use logical OR in place where we want to work with the length property:

if (!(updates || []).length) { ... }

Using logical OR in place using parentheses

Copied to clipboard!


Working With Strings

Strings also have a length property. The same rules apply to them. Prefer using optional chaining, or a logical OR to fallback to default values. The only difference here, is you want to provide an empty string as a fallback value:

// Using optional chaining
const string = null

if (!string?.length) { ... }

// Using logical OR
const string = null || ''

// Using the typeof operator to
if (typeof string === 'string') {
    const length = string.length
}

How to avoid the error when working with strings

Copied to clipboard!

152 | const jobs = !!((_a = resume.profession) === null || _a === void 0 ? void 0 : _a.length) ?
153 | CARGOS OCUPADOS: ${convertArrayToText(professionDescription(resume))}. enter code here 154 | TEMPO DE EXPERIÊNCIA PROFISSIONAL TOTAL: ${literalTime(normalizedWorTime(resume))}. : «»;

155 | const languages = !!resume.language.length ? IDIOMAS: ${convertArrayToText(getLanguageText(resume))}. : «»;
156 | const additional = PUBLICAÇÕES: ${publicationsText(resume)}. PREMIAÇÕES: ${awardsText(resume)};
157 | return education + jobs + languages + additional;
158 | }

I have this error in my code, it came up suddenly, I’ve searched several forums but found nothing relevant.

Within Visual Studio Code, it gives the following error:
«Could not open utils.js in the editor.»

When running on Windows, file names are checked against a whitelist to protect against remote code execution attacks. File names may consist only of alphanumeric characters (all languages), periods, dashes,
slashes, and underscores.»

 152 |     const jobs = !!((_a = resume.profession) === null || _a === void 0 ? void 0 : _a.length) ?
  153 |         `CARGOS OCUPADOS: ${convertArrayToText(professionDescription(resume))}. 
  154 |   TEMPO DE EXPERIÊNCIA PROFISSIONAL TOTAL:  ${literalTime(normalizedWorTime(resume))}. ` : "";
> 155 |     const languages = !!resume.language.length ? ` IDIOMAS: ${convertArrayToText(getLanguageText(resume))}. ` : "";
  156 |     const additional = `PUBLICAÇÕES: ${publicationsText(resume)}. PREMIAÇÕES: ${awardsText(resume)}`;
  157 |     return education + jobs + languages + additional;
  158 | }
Table of Contents

Hide

  1. What is TypeError: Cannot read property ‘length’ of null?
  2. How to fix TypeError: Cannot read property ‘length’ of null?
    1. Solution 1: Providing the default fallback value
    2. Solution 2: Checking data type before using the length property
  3. Conclusion

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.

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.

Related Tags
  • Array,
  • length,
  • null,
  • TypeError,
  • undefined

Sign Up for Our Newsletters

Get notified on the latest articles

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

result = [affectedRows.length, affectedRows];

It happens only when both returning & plain are set, when there are no updated rows:

 await person.update({ phone: '123' }, { where: { email: 'a@a.com' }, returning: true, plain: true })
ERROR unhandledRejection Cannot read properties of null (reading 'length')
TypeError: Cannot read properties of null (reading 'length')
    at Function.update (/node_modules/sequelize/lib/model.js:1945:32)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Using postgres, so affectedRows always exists.
Sequelize should check if affectedRows == null and do nothing if there are no updated rows (valid use case). Let the app flow continue.

As a Javascript programmer, you must have dealt with the “TypeError: cannot read properties of null”. 

In JavaScript, sometimes your code works completely fine, or you can get trapped in errors. This standard error occurs when one tries to read a property or call a method on a null object. In simple words, you try to access the value of null or undefined. If you are still in the same confused state, read further to find a precise solution. 

Before we move toward the answer, let’s discuss two basic terms, null and DOM, in detail, which will help you to understand the article completely.

Table of Contents
  1. What is a Null in JavaScript?
  2. What is DOM in JavaScript?
  3. Causes of the “TypeError: Cannot Read Properties of Null” Error
  4. Ways to Fix the “TypeError: Cannot Read Properties of Null” Error

What is a Null in JavaScript?

In JavaScript, a null is a primitive value, meaning the intentional absence of any object value. It is treated as a false in boolean operations. A variable with a null value is of the object type. Now understand null with the help of an example:

Code

console.log("Example of null");

let a = null;

console.log("Type of a:" ,typeof a);

console.log("A contain:" ,a);

Output

Example of null

Type of a: object

a contain: null

What is DOM in JavaScript?

Dom stands for Document Object Model in JavaScript; it is a programming interface that allows us to select, create, modify or remove elements from a document. We can easily add events to our document elements to make our page more dynamic.

Causes of the “TypeError: Cannot Read Properties of Null” Error

Normally, we face TypeError: cannot read properties of null in JavaScript when we try to access a property of the null object. Here we have a list of the most common causes of this error which are:

  1. Write wrong spelling
  2. Access property of a null object
  3. Inserting script tags before DOM elements declaration

Cause 1: Write The Wrong Spelling

When we use the wrong spell of an element id, we face this error now; let’s see an example of where we found this error.

Code

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

 

  <input type="text" id="fname" name="fname">

 <script>

var first_name = document.getElementById("name").value;

console.log(firstName)

</script>




  </body>

</html>

Output

TypeError: cannot read properties of null

In the above coding, we write fname and in the script tag, we are trying to get the id name which is not present; that’s why we face this error.

Cause 2: Accessing a Property of a Null Object

Whenever we try to access a property of a null object, we have to face the type error. Now see a simple example in which we explain this concept:

Code

console.log("Error due to Property of null");

let myvariable=null;

console.log("length of variable is:" ,myvariable.value);

Output

TypeError: cannot read properties of null

Cause 3: Inserting Script Tags Before Dom Element Declaration

The TypeError: cannot read properties of null is commonly occurs when we use the getElementById() method and pass it an id that is not present in the DOM. Usually, this error occurs when we write a script tag before the DOM element declaration. Now understand the reason for this error with the help of an example:

Code

Index.html

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

  <script src="src/script.js"></script>

  <input type="text" id="name" name="name">

   

  </body>

</html>




Script.js

var firstName = document.getElementById("name").value;

console.log(firstName)

Output

TypeError: cannot read properties of null

In this code, we write script tags before declaring DOM elements; that’s why we have TypeError.

Ways to Fix the “TypeError: Cannot Read Properties of Null” Error

Following are some solutions we can use to fix TypeError: cannot read properties of null in JavaScript.

  1. Check element id
  2. Write script tag after DOM elements declared
  3. Ways to handle null values
  4. Check if The Object Is Null or Undefined
  5. Check for Typo Errors
  6. Check if the object and property exist
  7. Use Type Checking

Now have a look at the solutions to that errors.

Solution 1: Check Element Id

It’s a good practice to always double-check the element id so you save yourself from this common type of error. Now solve the above error by simply writing the correct element id.

Code

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

 Enter your First Name:

  <input type="text" id="fname" name="fname">

 <script>

var first_name = document.getElementById("fname").value;

</script>




  </body>

</html>

Output

TypeError: cannot read properties of null

Solution 2: Write Script Tag After DOM Elements Declaration

Always try to write a script tag at the end of the body tag or after the DOM element declaration. Now understand this solution by removing the error from the above example:

Code

Index.html

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

 Enter your First Name:

  <input type="text" id="fname" name="fname">

   <script src="src/script.js"></script>

  </body>

</html>




Script.js

var firstName = document.getElementById("fname").value;

Output

TypeError: cannot read properties of null

Solution 3: Handle Property of Null Values

When we try to access a property of a null object, we face a type error that can crash our web application. Here we have the following ways to handle null values:

  1. Use the if structure
  2. Use the ternary operator
  3. Use the try-catch block

We have four ways to handle null values; now, let’s see these four ways one by one.

We can check whether the value is null with the help of most simple way, that is, if else statement. Now let’s see a piece of code to check null values:

Code

console.log("Handle null with if else statement");

let myvariable=null;

if (myvariable) 

{

  console.log("The value of variable is:" ,myvariable.value);

} else 

{

  console.log('Your variable contains null');

}


Output

Handle null with if else statement

Your variable contains null

We can use the ternary operator to handle a null value; it is a little more complicated than if statement. Now let’s understand it with the help of an example:

Code

console.log("Handle null with the ternary operator);

let myvariable=null;

const myval = myvariable? myvariable.value : 'default';

console.log("The value of the variable is:" , myval);

Output

Handle null with the ternary operator

The value of the variable is: default

Lastly, we can save our web application from crashing by simply putting a try-and-catch block. Now let’s see an example in which we use try catch to handle a null value:

Code

console.log("Handle null with ternary operator");

let myvariable=null;

try

{

    let myval = myvariable.value;

}

catch(err){

  console.log(err.message);

}

Output

Handle null with ternary operator

Cannot read property 'value' of null

Solution 4: Check if The Object Is Null or Undefined

Make sure that the object you are trying to access is not null or undefined. If it is, you will get this error.

Solution 5: Check for Typo Errors

Make sure you have typed the object and property names correctly. A common mistake is spelling the object or property name incorrectly.

Solution 6: Check if the object and property exist

Make sure that the object and property you are trying to access actually exist. If you are trying to access an object or property that does not exist, you will get this error.

Solution 7: Use Type Checking

You can use type checking to ensure that the object is not null or undefined before trying to access its properties. For example, you can use the “typeof” operator to check the type of the object, like this:

if (typeof object !== "undefined" && object !== null) {
    // access object properties
}

Conclusion

In conclusion, TypeError: cannot read properties of null is a common error that occurs in JavaScript when you try to access a value of null or commit a spelling mistake.

This article shows how to fix JavaScript’s “TypeError: cannot read properties of null” error. We have discussed all the reasons and their solutions, so now you can eliminate erroneous lines in your code.

Let’s have a quick recap of the topics discussed above.

  1. What is a Null?
  2. What is DOM?
  3. Causes of TypeError: cannot read properties of null in JavaScript.
  4. How can we fix TypeError: cannot read properties of null in JavaScript?

Finally, you significantly understand the “TypeError: cannot read properties of null” error in JavaScript; it’s time to remember the concepts; comment below 👇 the most straightforward way of handling null value.

Like this post? Please share to your friends:
  • Ошибка cannot open hasp driver
  • Ошибка cant load library engine dll
  • Ошибка cannot open file for writing log
  • Ошибка cant find world of tanks
  • Ошибка cannot open 7zxa dll