Ternary vs if...else

Is the Ternary operator better than if…else? and does Ternary operator works on all if…else situation?


Ternary operator is an expression, while if is a statement. You can use expressions where statement is expected, but not otherwise:

// Expressions with if statement will work
if (true) 42
else 38

// Statements with ternary operator (as well as any other operator) will throw
true ? let a = 42 : let b = 38

So replying to your question, you can always substitute ternary operator with if ... else but there are cases when you are not able to do otherwise.

1 Like