Can a triple operator be equivalent to a short circuit using logical operators?

With a short circuit, you can prevent the evaluation of part of the expression:

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

Since logical expressions are ops, you can use them in function calls or in return statements.

But, ultimately, this is nothing more than conditional branching and can be easily achieved using the ternary operator:

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

It is more readable and similarly concise. Is there any reason to use the short circuit property of logical operators, with the exception of the illustrative term?

+4
source share
1 answer

It’s true (well, almost true) that

x ? x : y

logically equivalent

x || y

, . ? : x . x || y . , x - , , , , .

( , , - , "" .)

+8

Source: https://habr.com/ru/post/1627063/


All Articles