+ 5
Associativity of ternary operator in javascript
Can someone plz explain me associativity of ternary operator in js as mdn doc says it is from right to left. But how?? In general it seems it executes from left to right
2 Réponses
+ 4
Associativity tells us how we should insert parentheses () if none are present. For example, `+` is left-associative:
a + b + c == (a + b) + c
and not `a + (b + c)`. But ok, for `+` it doesn't really matter which way the parens go. `.` is left-associative too:
obj.foo.bar == (obj.foo).bar
and not `obj.(foo.bar)` because that wouldn't make sense.
`**` is right-associative.
2**2**3 == 2**(2**3)
Because that's how it is in maths.
The ternary operator is is right-associative too. It's weird because it consists of 3 parts, but it's the same thing:
a ? b : c ? d : e == a ? b : (c ? d : e)
and not! `(a ? b : c) ? d : e`.
In PHP, the ternary operator is left-associative but that's dumb, because right-associativity allows us to chain ternaries like so:
var x = a == 1 ? 'one' :
a == 2 ? 'two' :
a == 3 ? 'three' : 'neither';
Left-associative ternaries would group this expression like
var x = (a == 1 ? 'one' : a == 2) ? ...
which makes no sense.
+ 2
Very well explained thank you sir😊