Home > Back-end >  TypeError: Cannot read property length from undefined
TypeError: Cannot read property length from undefined

Time:05-20

I am having two arrays of strings which may be undefined or defined with some value.

var a ; // [Array of strings]
var b ; // [Array of strings]
var c; // result array

I need to push some static value like "abc" in a third array like var c whenever either of the array a or array b are defined and their length > 0. But my script is breaking , this is the line of code below.

if((typeof a !== 'undefined' ||typeof b !== 'undefined' ) && (a.length > 0 || b.length > 0) )

The above loc fails when I am assigning some value to 'a' and b is undefined. Error logs show me the below.

by: javax.script.ScriptException: TypeError: Cannot read property \"length\" from undefined\n\tat 

How can I change this condition to satisy my requirements.Is there a better away to achieve this.Also, I am using Rhino JS engine 1.13 ver.

CodePudding user response:

You could rewrite it like

if((a !== undefined && a.length > 0) || (b !== undefined && b.length > 0)) {
  c = ...
}

To ensure you only check the length of each variable only if they are not undefined.

By the way, if you are using 'use strict' mode, you can just use a !== undefined instead of typeof a !== 'undefined'.

CodePudding user response:

You should group a tests then group b tests.

if (
       a !== "undefined" && a.length && a.length > 0
    || b !== "undefined" && b.length && b.length > 0
) {
    c.push("abc");
}

And if Rhino supports Array.isArray(), here is a smaller code:

if (Array.isArray(a) && a.length > 0 || Array.isArray(b) && b.length > 0) {
    c.push("abc");
}

Does it work in Rhino JS Engine?

CodePudding user response:

The problem I see in your code is the first evaluation

(typeof a !== 'undefined' ||typeof b !== 'undefined' )

It returns true when either a or b is 'undefined'. For instance, imagine an instance where a is undefined but b is an array; (typeof a !== 'undefined' ||typeof b !== 'undefined' ) evaluates to true.

The second evaluation which uses an OR (||) operation which starts from left to right;

(a.length > 0 || b.length > 0)

starts by evaluating

a.length

but a is 'undefined' and hence the error.

I would use this

if((a !== undefined && a.length > 0) || (b !== undefined && b.length > 0)) {
  // Do something
}

CodePudding user response:

In Javascript, you can also check whether the value of the variable is null or undefined with the below way.

I guess this will help you. Try this:

if(a?.length > 0 && b?.length > 0){
    // Code here
}
  • Related