Stefano Saitta
Stefano Saitta

Reputation: 2034

What's is the difference between Array.of(n) , Array(n) and array = [n]?

As the title, i'm wondering what's the difference between this 3 methods of initialization an array.

I'm actually more interested in the new Array.of() method provided from ES6, why they feel the needs of implements that?

Upvotes: 14

Views: 645

Answers (2)

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Array.of(2) will create an array with the element 2.

var temp = Array.of(2); // temp = [2]

Array(2) will create an array of 2 elements.

var temp = new Array(2); // temp = [undefined, undefined]

temp = [2] will create an array with the element 2.

var temp = [2]; // temp = [2]

Upvotes: 3

Pointy
Pointy

Reputation: 413996

The Array constructor can be called in two ways: a list of values to be used as values for array elements, or with a single numeric value giving the initial length:

var myArray = new Array("hello", "world"); // 2 elements
var otherArray = new Array(100); // 100 elements, all empty

Because there's an ambiguity when just one number is passed, that old API is considered badly designed. Thus, there's Array.of(), which is the same as the first option for the Array constructor:

var otherArray = Array.of(100); // 1 element

The third way to make an array is with an array initialization expression:

var otherArray = [100]; // 1 element

The array instances that are created by each of the above are functionally equivalent and completely interchangeable.

One more thing: why does Array.of() have to exist, given that we can use the array initialization expression? Well, Array.of() is a function, so it can be used as a value applied in functional-style programming. You can (as a slightly dumb example) copy an array with:

var copy = Array.of.apply(Array, original);

One reason that's dumb is that there's also (in ES2015) Array.from() to do the same thing:

var copy = Array.from(original);

That works on any sort of iterable original, so it's a good way to turn arguments or a NodeList into an array.

The MDN site has documentation on Array.of(). The constructor and the array initializer form have been around since forever, so any JavaScript reference will cover those (though possibly without reference to Array.of()).

Upvotes: 21

Related Questions