Someone can explain to me why this happen? And please, if someone know this behavior name, please 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 the _params
is undefined
, how possible is of executing the second expression, if the &&
expression returns the first false and the last trusty value.
false && false ? never executed : _params is undefined
_params && Array.isArray(_params) ? arr.push(..._params) : arr.push(_params);
other way:
if (_params && Array.isArray(_params)) { // (false && false) === false
arr.push(..._params); // it will be never executed
} else {
arr.push(_params); // _params is undefined
}
Your expression is executed like this:
(_params && Array.isArray(_params)) ? arr.push(..._params) : arr.push(_params);
But you meant probably this:
_params && (Array.isArray(_params) ? arr.push(..._params) : arr.push(_params));
You just have to add parentheses.
let _params; // undefined
_params && Array.isArray(_params) ?
is false
, so the called code is arr.push(_params);
, resulting in arr.push(undefined);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.