Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow for zero-value in short-circuit evaluation

Tags:

javascript

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?

like image 391
sookie Avatar asked Aug 23 '17 12:08

sookie


2 Answers

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; }
like image 50
Nina Scholz Avatar answered Oct 04 '22 15:10

Nina Scholz


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());
like image 28
Redu Avatar answered Oct 04 '22 13:10

Redu