3

I was going through one of the interview process this is question poped up

var arr = ["a", "b", "c", "d"][1, 2, 3]

when I did console.log it is printing "d" and I tried

var arr = ["a", "b", "c", "d", "e"][1, 2, 3] 

even it is printing "d".

Please explain with some documents if you can ?

Itay
  • 16,601
  • 2
  • 51
  • 72
  • if you get the solution please let me know – Saurabh Agrawal Feb 09 '17 at 05:34
  • 3
    The [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) strikes again. – Gerrit0 Feb 09 '17 at 05:39
  • I found the duplicate by searching for [`[javascript] array multiple index comma`](http://stackoverflow.com/search?q=%5Bjavascript%5D+array+multiple+index+comma), which let me find http://stackoverflow.com/questions/29249371/array-behavior-confusion/29249412#29249412, which is closed as a duplicate as well. – Felix Kling Feb 09 '17 at 05:54

2 Answers2

4

The first set is interpreted as an array, the second set is evaluated as an indexer to the first.

["a", "b", "c", "d"][1, 2, 3] => "d"
["a", "b", "c", "d"][1, 2] => "c"
["a", "b", "c", "d"][1] => "b"
["a", "b", "c", "d"][0] => "a"
["a", "b", "c", "d", "e"][3] => "d"
(1, 2, 3) => 3

thus:

["a", "b", "c", "d"][1, 2, 3] =>
["a", "b", "c", "d"][(1, 2, 3)] =>
["a", "b", "c", "d"][3] =>
"d"
Ehryk
  • 1,930
  • 2
  • 27
  • 47
1

The comma operator usage at bracket notation is allowing result of reference to last element of array. For example var arr = ["a", "b", "c", "d", "e"][1, 2]; arr // c

guest271314
  • 1
  • 15
  • 104
  • 177