DEV Community

KS
KS

Posted on

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

Here is a javascript trivia problem that gives you something to think about.

Go to your console and run below line.

++[1,2,3][2]
Enter fullscreen mode Exit fullscreen mode

Can you exaplain the output ?

Top comments (4)

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.

Collapse
 
lalit64 profile image
Lalit Yalamanchili

I get 4 and am not sure how to explain the output 🙃