I was just playing a code, and I found a little mysterious behavior with my code while turning the ternary operator into &&
and ||
operator:
let a = 3;
a = a > 1 && 2 || a;
console.log(a);
let b = 3;
b = b > 1 ? 2 : b;
console.log(b);
// a and b both are same. It's fine.
const getAdjacentHighestProduct = (arr) => {
let max = -Infinity;
arr.reduce((a, c) => {
let product = a * c;
max = product > max ? product : max;
return a = c;
});
return max;
};
const aProduct = getAdjacentHighestProduct([1, 0, 1, 0, 1000]);
console.log(aProduct);
const getAdjacentHighestProduct2 = (arr) => {
let max = -Infinity;
arr.reduce((a, c) => {
let product = a * c;
max = product > max && product || max;
return a = c;
});
return max;
};
const aProduct2 = getAdjacentHighestProduct2([1, 0, 1, 0, 1000]);
console.log(aProduct2);
// aProduct, aProduct2 are not the same. It's not okay.
Also, here I can see the result is -Infinity
for aProduct2. But while trying the same code in a test case, I am seeing the result is null
, maybe it's due environment (browser vs node.js).
So, I am curious why both results are not the same and why is it returning -Infinity
or null
rather than 0
?
So, what's exact difference between using a ternary operator and && ||
operator?
Here's the screenshot of the test result: