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
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 to share