Behavior of Array(n).join(s)

Tab Atkins Jr. jackalmage at gmail.com
Mon Jul 16 13:44:59 PDT 2012


On Mon, Jul 16, 2012 at 1:39 PM, Patrick Mulder
<mulder.patrick at gmail.com> wrote:
> Hello,
>
> I am rather new to ES and this group, but I am surprised by this behavior:
>
> When I do:
>
> Array(4)
>>>> [undefined, undefined, undefined, undefined]
>
> And when I do:
>>>> Array(4).join(" * ")
> " * * * "
>
> In other languages, I would not be able to join undefined objects.
> Also, if it would be, I am surprised that I get only 3 x * whereas
> above, I have 4 undefined. Anyone has some pointers, what I am
> missing?

The Array#join method stringifies all of the entries, then combines
them together in order, inserting the join() argument between each
pair.  That's why you get 3 asterisks - it's inserted *between* the
elements, and there are 3 gaps between 4 elements.

Though undefined usually stringifies to "undefined", .join()
specifically stringifies it to "" (the empty string).  So, calling
.join() on an array full of undefined just creates multiple copies of
the join argument.

Calling Array(n).join('foo') is a common trick to repeat a string n-1
times, like so:

String.prototype.repeat = function(n) { return Array(n+1).join(this); }

~TJ


More information about the es-discuss mailing list