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 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.
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
- What is TypeError: Cannot read property ‘length’ of null?
- How to fix TypeError: Cannot read property ‘length’ of null?
- Solution 1: Providing the default fallback value
- Solution 2: Checking data type before using the length property
- 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.
- Provide a fallback value in case the length is not defined or null.
- 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.
Introduction
Problem:
A user may encounter the following error during a terraform run on TFE:
Error fetching plan data
Cannot read properties of null (reading 'length')
Cause:
This is a known issue affecting TFE releases prior to 202210-1 . It is triggered when JSON-encoded arrays are compared with null values.
Overview of possible solutions
Solutions:
1. Switch the Workspace’s User Interface Setting from Structured Run Output to Console UI.
OR
2. Upgrade to Terraform Enterprise 202210-1 (659) or later.
Outcome:
After applying one of the solutions, retry the failed run and it should not run into this error.
Additional Information
- Settings — Workspaces — Terraform Cloud | Terraform | HashiCorp Developer
-
Terraform Enterprise v202210-1 Release Notes