Why does (true ? false ? ‘1’ : ‘2’ : ‘3’) return 2?

Look up operator precedence.

Since the ternary operator is right – associative, the above expression gets parsed to this:

true ? (false ? '1' : '2') : '3'

Right – to – left associativity means the operator at the most right is executed first.

In our case the right – most ternary operator is the inner one, and is thus executed first.

Leave a Comment