Why does this work? [].concat[1,2,3]

[2016-11-12] dev, javascript
(Ad, please don’t block)

In this blog post, we look at a syntactic puzzle. This is just for fun; there is nothing useful you can do with what we examine. It may, however, make you more aware of how JavaScript works, syntactically.

Question  

What do you need to do to get the following result? And why does it work?

> [].concat[1,2,3]
[ 1, 2, 3 ]

Answer  

This expression looks very similar to:

[].concat([1,2,3])

But, actually, something completely different is going on:

  • First, the result of [].concat is computed. The result is the function stored in Array.prototype.concat.

  • Then the operand of the square bracket operator is evaluated. It consists of the comma operator (in this context, the comma is an operator, like +) applied to three numbers:

    > 1,2,3
    3
    
  • Lastly, property '3' of the function returned by [].concat is accessed.

Normally, that produces undefined:

> [].concat[1,2,3]
undefined

If, however, you make the following assignment, you’ll get the result shown at the beginning:

> Array.prototype.concat[3] = [1,2,3];
> [].concat[1,2,3]
[ 1, 2, 3 ]