0
[1,2,4,8][0,1,2,3]
// equals to 8 (the last element of the indexing array (3) becomes the index)

Why is this not a SyntaxError error (a bad legacy or a purposeful feature)? (A possible duplicate, however I wasn't able to find an answer here.)

Update: Why the contents of the square brackets are treated as an expression?

Vidul
  • 10,128
  • 2
  • 18
  • 20

1 Answers1

5

The first part:

[1,2,4,8]

is interpreted as an array literal. The second part:

[0,1,2,3]

is interpreted as square bracket notation to access a member of the array. The contents of the square brackets are treated as an expression, which is seen as a sequence of comma separated values:

0,1,2,3 // or (0,1,2,3) as an independent expression

That expression returns the last value, so is effectively:

[1,2,4,8][3] // 8
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Yes, this is obvious from the question, which is (apologies for asking again): `why is it like this?`. – Vidul Jan 14 '16 at 01:07
  • @Vidul: because the syntax `x[y]` is actually interpreted as `reference[expression]`. Since the index is an expression, the comma is treated as an operator in the same way that a `+` or a `-` would be. The reason the index is an expression is to allow for things like: `x[y+1]`. That's why – slebetman Jan 14 '16 at 01:27
  • @slebetman Your comment makes perfect sense. Would you please post it as an answer? – Vidul Jan 14 '16 at 01:31
  • @Vidul: Unfortunately I can't as this question is closed and the duplicate one is not exactly asking what you are asking. – slebetman Jan 14 '16 at 02:16
  • @Vidul: I don't mind anyway. At close to 40k I don't need the points – slebetman Jan 14 '16 at 02:17