Over a million developers have joined DZone.
Platinum Partner

Array.prototype.concat is not generic

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix. Download this Forrester Report to gain a better understanding of the low-code platform market and how to make a strategic platform selection you won’t regret.

The ECMAScript 5.1 specification states that the array method concat is generic [1]. This post argues that that isn’t true in practice.

§15.4.4.4 of the ECMAScript 5.1 specification states:

The concat function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method.
The code in this post uses [] as a shortcut for Array.prototype. That is a common technique, but it is slightly dirty: You access the methods of Array.prototype via an instance. However, this access is very fast in modern JavaScript engines, I suspect that some of them don’t even create an array instance, any more. All of the examples have been tried on Firefox and V8.

Let’s check the assertion that concat is generic: Its result must be the same regardless of whether this is a real array or just array-like (with a property length and indexed access to elements). We first try concat with an array as this:

    > ["hello"].concat(["world"])
    ["hello", "world"]

    > [].concat.call(["hello"], ["world"]) // same as above
    ["hello", "world"]
Next, we do the above concatenation with an array-like object. The result should be the same.
    > [].concat.call({ 0: "hello", length: 1 }, ["world"])
    [ { '0': 'hello', length: 1 }, 'world' ]
The special variable arguments is also array-like. The result is again not what we would expect from a generic method:
    > function f() { return [].concat.call(arguments, ["world"]) }
    > f("hello")
    [ { '0': 'hello' }, 'world' ]
To see a truly generic method in action, you just need to look at push:
    > var arrayLike = { 0: "hello", length: 1 };
    > [].push.call(arrayLike, "world")
    2
    > arrayLike
    { '0': 'hello', '1': 'world', length: 2 }
Reference:
  1. Uncurrying `this` in JavaScript” [explains what generic methods are]

The Web Dev Zone is brought to you in partnership with Mendix. Better understand the aPaaS landscape and how the right platform can accelerate your software delivery cadence and capacity with the Gartner 2015 Magic Quadrant for Enterprise Application Platform as a Service.

Topics:

Published at DZone with permission of Axel Rauschmayer , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}