6

What does [1,2,3][1,2] means in Javascript? I do not understand what its supposed to do, and i have no clue how could i google such thing.

Any ideas?

I assume this is quite the newbie question, please forgive my ignorance.

Ricardo Jacas
  • 156
  • 12
  • 4
    [1,2,3][1,2] means nothing without context. Is it a variable? Is it part of a variable? Please provide some context. – Floris Dec 17 '13 at 21:38
  • 10
    `[1,2,3][1,2]` by itself evaluates to `[1,2,3][2]`. `[1,2,3]` is an array literal, and `[1,2]` is [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators#Bracket_notation) with `1,2` as expression. `1,2` is an application of the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) and evaluates to `2`. I.e. it accesses the third element of the array `[1,2,3]`. I don't know why you would want to write that though. – Felix Kling Dec 17 '13 at 21:39
  • Thank Felix, thats it. Its the same for any number of elements in the second array? – Ricardo Jacas Dec 17 '13 at 21:43
  • 1
    Careful, the "second array" is not an array. It *looks* like an array literal, but in this context it is isn't. This makes it clearer: `var arr = [1,2,3]; console.log(arr[1,2]);`. The comma operator evaluates each of operand and returns the last one. So if you had `arr[1,2,3,4,5]`, it would evaluate to `arr[5]`. – Felix Kling Dec 17 '13 at 22:06
  • possible duplicate of [Why does `[5,6,8,7][1,2] = 8` in JavaScript?](https://stackoverflow.com/q/7421013/1048572) – Bergi Jul 14 '17 at 16:42

1 Answers1

9

So the [1,2,3][1,2] as a whole accesses the index 2 of the array, and yields 3.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    And, just in case it isn't clear, doing this is gross obfuscation. – jwrush Dec 17 '13 at 22:18
  • 1
    @jwrush: Only the comma operator is. Using a member operator direclty on an array literal can be fine. – Bergi Dec 17 '13 at 22:19
  • 100% agreed. And, it would be worse if it were [1, [2, 3, 4], 5][1,2] as someone not versed in javascript might assume that the comma notation was short-hand nested array access. – jwrush Dec 17 '13 at 22:22
  • 1
    @jwrush: We can do better: `[1, [2, 3, [4]], 5][2, [1]][0]` - still working :-) – Bergi Dec 17 '13 at 22:24