2

Why does the following not throw any syntax errors?

var a = [1, 2, 3, 4],
    b = a[2, 1, 0, 1];

console.log(b);

See fiddle:

http://jsfiddle.net/2eng5typ/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • Woops. I searched for an answer to this before asking, but I wasn't able to find that question. – SimpleJ Dec 23 '14 at 23:22

1 Answers1

4

1. The , is a comma operator in the above case. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

2. The first [] defines an array.

3. The a[...] dereference the ... element from the array, where ... is the last element which is 1

4. So basically this happens:

var a = [1, 2, 3, 4];
var b = a[1];
console.log(b); 

which is the same as:

var b = 2;
console.log(b);
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56