Behavior of Array(n).join(s)

# Patrick Mulder (13 years ago)

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?

Thanks, Pat

# Tab Atkins Jr. (13 years ago)

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

# Brandon Benvie (13 years ago)

Array.prototype.join is one of the only (the only?) array method that works on sparse arrays in this manner.

# Rick Waldron (13 years ago)

On Mon, Jul 16, 2012 at 4: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?

Take a look at 15.4.4.5 Array.prototype.join: ecma-international.org/ecma-262/5.1/#sec-15.4.4.5

Specifically, #8 explains how undefined and null are treated and #10 A-E explain how the separator and items in the array are concatenated

# Rick Waldron (13 years ago)

Sorry about the echo, I didn't see the replies come in as I was typing