I know that an expression produces a value while a statement is an action. However, I don’t understand why the ternary operator falls under the category of an expression.
From what I understand, the ternary operator is simply a shorthand version of an "if/else" statement. But that’s a statement. So why is it that the ternary operator not a statement like its longer counterpart?
2
Answers
It’s not ‘simply a shorthand version of an "if/else"’. It’s intended to be used when you want a conditional value, e.g.
instead of writing
Any expression can be used as a statement, so it’s possible to use a ternary as a shorthand
if/else
, e.g.You’ll often find this in minified or obfuscated code, but many programmers consider it poor style in regular code.
Not all
if/else
can be shortened like this, because the body ofif
can contain statements, but you can only use expressions in the sub-expressions of a ternary.An expression is a piece of code that results in (evaluates to) a value.
4 + 4
is an expression.a[ i ]
is an expression.We don’t always care about the value to in which it results. Still an expression, though.
x = y
is an expression.console.log( "Hi" )
is an expression.The conditional operator results in a value.
If it didn’t, it wouldn’t make sense to place it on the right-hand side of an
=
, like here:An if statement doesn’t result in a value. It can’t be used as an expression.