javascript - Can the ternary operator be equivalent to short circuiting with the logical operators? -
with short circuiting can prevent evaluation of part of expression:
let x = "", y = 123; x && alert("foo"); // "" y || alert("bar") // 123 since logical ops form expressions can use them in function invocations or return statements.
but ultimately, that's nothing more conditional branching , can reached ternary operator:
x ? alert("foo") : x; // "" y ? y : alert("bar"); // 123 this more readable , concise. there reason utilize short circuiting property of logical operators except illustrative term?
it's true (well, true) that
x ? x : y is logically equivalent to
x || y however, they're not equivalent in terms of happens when code runs. in ? : case, sub-expression x may evaluated twice. in x || y, it's evaluated once. simple variable references, doesn't matter, if x function call, might affect behavior , it'll affect performance.
(the fact 1 of expressions might evaluated twice meant "almost" in first sentence.)
Comments
Post a Comment