skip to Main Content

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


  1. 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.

    variable = condition ? value1 : value2;
    

    instead of writing

    if (condition) {
        variable = value1;
    } else {
        variable = value2;
    }
    

    Any expression can be used as a statement, so it’s possible to use a ternary as a shorthand if/else, e.g.

    condition ? console.log("True") : alert("False");
    

    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 of if can contain statements, but you can only use expressions in the sub-expressions of a ternary.

    Login or Signup to reply.
  2. 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.

    cond ? 123 : 456   // Results in either `123` or `456`.
    

    If it didn’t, it wouldn’t make sense to place it on the right-hand side of an =, like here:

    val = cond ? 123 : 456;   // `val` is now `123` or `456`.
    

    An if statement doesn’t result in a value. It can’t be used as an expression.

    val = if ...    // WRONG!
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search