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?
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:
'https://api.rest.com/v1/users/' + userId + '/resource/' + resourceId
1.1: this in turn uses the parse concatenation mode ¹resourceId
''
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.