Search code examples
javascriptshort-circuitingternary

Can the ternary operator be equivalent to short circuiting with the logical operators?


With short circuiting you can prevent the evaluation of part of an expression:

let x = "", y = 123;
x && alert("foo"); // ""
y || alert("bar") // 123

Since the logical ops form expressions you can use them in function invocations or return statements.

But ultimately, that's nothing more than conditional branching and can be easily reached with the ternary operator:

x ? alert("foo") : x; // ""
y ? y : alert("bar"); // 123

This is more readable and similarly concise. Is there a reason to utilize the short circuiting property of the logical operators except for the illustrative term?


Solution

  • It's true (well, almost true) that

    x ? x : y
    

    is logically equivalent to

    x || y
    

    However, they're not equivalent in terms of what happens when the code runs. In the ? : case, the sub-expression x may be evaluated twice. In x || y, it's definitely only evaluated once. For simple variable references, that doesn't matter, but if x is a function call, it might affect behavior and it'll certainly affect performance.

    (The fact that one of the expressions might be evaluated twice is what I meant by "almost" in the first sentence.)