Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

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.


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

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


This expression looks very similar to:


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
  • Lastly, property '3' of the function returned by [].concat is accessed.

Normally, that produces undefined:

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

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 ]