. Advertisement .
..3..
. Advertisement .
..4..
JavaScript is an ECMAScript-compliant high-level, frequently just-in-time compiled language. It features first-class functions, prototype-based object orientation, and dynamic typing. It offers application programming interfaces (APIs) for using the Document Object Model, regular expressions, dates, and standard data structures (DOM). Cannot read property ‘length’ of Undefined in JS is a common error. In this blog, we will give you some solutions to fix it. Read on.
When Do You Get The Error “Cannot read property ‘length’ of Undefined” In JS?
When you run your program, you easily get the following error:
cannot read property 'length' of Undefined
Due to how frequently the length attribute of a string or array is referenced when developing software, this error might occur for many other reasons. For instance, you would get this error if a function that acts on a string parameter was called without a string.
How To Solve The Error “Cannot read property ‘length’ of Undefined” In JS?
Aprroach 1: Provide a fallback for the value
Before accessing the length property, provide a fallback for the value or ensure it is the right type to fix the error “Cannot read property ‘length’ of Undefined” in JS.
Below are a few illustrations of how to fix the problem while accessing an array’s or string’s length property.
// with ARRAYS
// const fromDb = undefined;
// Provide empty array fallback
const arr = fromDb || [];
// Using optional chaining
const result1 = arr?.length;
console.log(result1);
// undefined
// Provide `0` as fallback if `undefined`
const result2 = arr?.length || 0;
// Use Array.isArray
if (Array.isArray(arr)) {
const result3 = arr.length;
} else {
console.log('arr is NOT an array');
}
// Provide fallback in place
const result4 = (arr || []).length;
The exact solutions are demonstrated for strings in the following code snippet.
// with STRINGS
// const fromDb = undefined;
// Provide empty string fallback
const str = fromDb || '';
// Using optional chaining
const result5 = str?.length;
// Provide `0` as fallback if `undefined`
const result6 = str?.length || 0;
// Use typeof
if (typeof str === 'string') {
const result7 = str.length;
} else {
console.log('str is NOT a string');
}
// Provide fallback in place
const result8 = (str || '').length;
To offer a backup in case the value to the left is false, we employed the logical OR (||) operator (for example, undefined).
const fromDb = undefined;
const arr = fromDb || [];
const str = fromDb || '';
The logical OR (||) operator returns the value to the right if the value to the left is false. The following example demonstrates how to short-circuit if the reference is equal to undefined or null by using the optional chaining (?.) operator.
const fromDb = undefined;
const result1 = arr?.length;
const result5 = str?.length;
Before accessing the length property, you can alternatively check to see if the value is an array by using the Array.isArray method or a string by using the typeof operator.
const fromDb = undefined;
if (Array.isArray(arr)) {
const result3 = arr.length;
} else {
console.log('arr is NOT an array');
}
if (typeof str === 'string') {
const result7 = str.length;
} else {
console.log('str is NOT a string');
}
The final illustration demonstrates how to set a fallback value in advance of accessing the length property.
const fromDb = undefined;
const result4 = (arr || []).length;
const result8 = (str || '').length;
The ternary operator, which is much like an if/else sentence, can also be used.
const str = undefined;
const result = str ? str.length : 0;
console.log(result); // 0
The operator returns the value to the left of the colon if the value to the left of the question mark is false; otherwise, it returns the value to the right of the colon.
Approach 2: Add Defensive Checking
Adding Defensive Checking is not a bad solution for you to solve the error “Cannot read property ‘length’ of Undefined” in JS.
It would help if you always were defensively verifying that arguments have the right shape whenever you can’t entirely control the input into your function. Users act in the worst possible ways, functions are modified, and API responses alter.
For instance, you might have a protective check that appears as follows if your fetch request receives a JSON response containing the string attribute for:
fetch("https://example.com/api")
.then(resp => {
return resp.json();
})
.then(json => {
if (!json || typeof json.foo != 'string') {
// The payload is not the desirable shape, so you have to record an error.
}
});
Conclusion
Individual solutions provided in these tools are some of the most fundamental for anyone faced with the question Cannot read property ‘length’ of Undefined in JS. If you still need assistance or have basic Python questions, a growing community of people are usually willing to assist you. In addition, we anticipate a more creative day filled with new ideas and code.
Read more
→ Fix the error “Uncaught referenceerror: require is not defined” in Javascript
Leave a comment