DEV Community

Discussion on: Javascript coding challange: explain output of ++[1,2,3][2]

Collapse
 
lexlohr profile image
Alex Lohr

The array selection has a higher operator precedence than the increment by one, so first the item with index 2 from the array is selected, which happens to be 3; this is then incremented by one so you get 4.

Collapse
 
ks_a4eb6224319 profile image
KS • Edited

Yup. That's exactly the case.
If you write as this then it all make sense :

const a  = [1,2,3]
++a[2]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lexlohr profile image
Alex Lohr

There's a tiny mistake in your adaption: x++ increments x, but returns the previous value, whereas ++x increments x, but returns the new value.