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.
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'
.