Strange behavior with JavaScript expressions

Can someone please explain to me why this is happening? And please, if anyone knows this behavior, edit the title.

With this code:

 const arr = ['RIPA'], varB = "RIPB";
let _params;
_params && Array.isArray(_params) ? arr.push(..._params) : 
arr.push(_params);

_params && console.log("I will never appear");
varB && console.log("I will appear");

arr.push(varB);
console.log('array',arr);
console.log("Type of the _params --> ", typeof _params);

      

Output:

array [ 'RIPA', undefined, 'RIPB' ]
Type of the _params -->  undefined

      

jsBIN: https://jsbin.com/bawepasivo/edit?js,console
repl.it: https://repl.it/GaHX

If _params

- undefined

, as far as possible the execution of the second expression, if the expression &&

returns the first false and the last trusted value.

+3


source to share


3 answers


Your expression runs like this:

(_params && Array.isArray(_params)) ? arr.push(..._params) : arr.push(_params);

But you probably meant the following:



_params && (Array.isArray(_params) ? arr.push(..._params) : arr.push(_params));

You just need to add parentheses.

+2


source


 false  && false                  ? never executed       : _params is undefined
_params && Array.isArray(_params) ? arr.push(..._params) : arr.push(_params);

      

another way:



if (_params && Array.isArray(_params)) { // (false && false) === false
    arr.push(..._params); // it will be never executed
} else {
    arr.push(_params); // _params is undefined
}

      

+1


source


let _params; // undefined

      

_params && Array.isArray(_params) ?

- false

, so the called code arr.push(_params);

, which results inarr.push(undefined);

0


source







All Articles