Search code examples
javascriptternary-operator

Why do two javascript string expressions that evaluate fine apart not evaluate correctly together?


I cannot understand why

1) 'https://api.rest.com/v1/users/' + userId + '/resource/' and

2) resourceId ? resourceId : ''

both evaluate correctly.

But, when I try to evaluate on one line:

'https://api.rest.com/v1/users/' + userId + '/resource/' + resourceId ? resourceId : ''

it results in just the evaluation of the second original expression (2).

What is the reason for this?


Solution

  • It's called operator precedence. String concatenation has higher precedence than ternary operator.

    The parser understand the expression 'https://api.rest.com/v1/users/' + userId + '/resource/' + resourceId ? resourceId : '' as:

    Parse ternary:

    1. Condition clause: 'https://api.rest.com/v1/users/' + userId + '/resource/' + resourceId 1.1: this in turn uses the parse concatenation mode ¹
    2. If clause: resourceId
    3. Else clause: ''

    Tip: when you combine expressions, make use of parentheses to disambiguate operators, for instance 'https://api.rest.com/v1/users/' + userId + '/resource/' + (resourceId ? resourceId : '').

    ¹ there are modes for each precedence level, like *, &&, ===, etc.