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?
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?
Share Improve this question edited Jan 11, 2016 at 14:31 Stefano Saitta asked Jan 11, 2016 at 14:25 Stefano SaittaStefano Saitta 2,0241 gold badge22 silver badges34 bronze badges 1- i already saw it, maybe my question was unclear i'm looking for a practical explaination of the usecases instead of a simple docs cut & paste. @AmmarCSE thank you for it anyway – Stefano Saitta Commented Jan 11, 2016 at 14:30
2 Answers
Reset to default 21The 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()
).
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]