Short-circuit evaluation determines if the first value is falsey. If so, return the second value, as follows:
var x = y || z; // if y is falsey return z
Is there a way to disregard zero-values as being falsey when using short-circuit evaluation without resorting to if/else statements or ternary operators?
You could check first if y
is unequal to zero and take the numerical value and get the result of the default of z
for y
.
x = +(y !== 0) && (y || z)
How it works:
expression y part result result comment ---------------------- --------- ----------- ------ ---------------------------- +(y !== 0) && (y || z) complete expression +(y !== 0) 0 0 0 result found, omit next part because of falsy value +(y !== 0) 1 1 check next part 1 && (y || z) y y take y, omit default +(y !== 0) undefined 1 check next part 1 && (y || z) z z take z as default
function x(y, z) {
return +(y !== 0) && (y || z);
}
console.log(x(0, 42)); // 0
console.log(x(4, 42)); // 4
console.log(x(undefined, 42)); // 42
console.log(x(0, null)); // 0
console.log(x(4, null)); // 4
console.log(x(undefined, null)); // null
console.log(x(0, 0)); // 0
console.log(x(4, 0)); // 4
console.log(x(undefined, 0)); // 0
.as-console-wrapper { max-height: 100% !important; top: 0; }
You may wrap your number into a Number object and check so;
var x = new Number(0) || console.log("never gets printed");
console.log(parseInt(x));
//or
console.log(x.valueOf());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With