1

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?

stackuser83
  • 2,012
  • 1
  • 24
  • 41
elight
  • 562
  • 2
  • 17

2 Answers2

4

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.

André Werlang
  • 5,839
  • 1
  • 35
  • 49
0

What the line

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

does is concatenate everything before the ternary operator, then evaluates that operation result as truthy or not (it is), and then returns the true branch result for the ternary operator.

Andre's answer suggestion that you use parentheses to get the order of operations that you expect will let you keep the single line formatting.

stackuser83
  • 2,012
  • 1
  • 24
  • 41