A recent question has been re-directed here, and although I agree that the central question has been answered accurately at a high level, part of the newer question seems to be asking about the difference between logical OR and the ternary operator in Javascript.
I would like to offer a low-level example to demonstrate the difference because I wrote most of this before the question was redirected, and the concept of a null-coalescing operator
is rather abstract.
Consider these functions, which can be run in the browser console or any repl:
let logicalOrTest = function(val) {
let a = 2;
let b = 3;
console.log(val === a);
console.log(val === b);
console.log(val === (a || b));
console.log(val !== (a || b));
}
Expect logicalOrTest(2)
to log true false true false
Expect logicalOrTest(3)
to log false true false true
Expect logicalOrTest(4)
to log false false false true
This reveals that comparing any value val
to (a || b)
will return true
when the value is equivalent to the first condition, and false
for any other value, including the second.
To put it simply, if condition a
is met, condition b
is not even considered. On the other hand, if condition a
is not met, b
will be considered before determining what to do.
Now let's look at the ternary operator:
let ternaryTest = function(val) {
let a = 2;
let b = 3;
val === a ? console.log(true) : console.log(false);
val === b ? console.log(true) : console.log(false);
val === (a || b) ? console.log(true) : console.log(false);
val !== (a || b) ? console.log('neither condition was met') : console.log('wat');
}
Expect ternaryTest(2)
to log true false true "wat"
Expect ternaryTest(3)
to log false true false "neither condition was met"
Expect ternaryTest(4)
to log false false false "neither condition was met"
Like logical OR (||
), the ternary operator x ? x : y
will pass any falsy value into the scope of the second expression, which also includes values equivalent to the second condition. If condition a
is met, condition b
is not considered.
The difference is that if condition a
is not met in a ternary operation, expression a
will be ignored and expression b
will always be executed.
So, while they can be used for similar purposes, it's important to understand which one is more efficient--especially if you are triggering large blocks of code within the scope of your operation.