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:
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:
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);