I came across the new Array.of() method that\'s been finalized in ES6, and I was wondering when one might use:
var a = Array.of(\'foo\', \'bar\');
instantiating an Array with a number creates an array with that many slots.
new Array(2);
> [undefined x 2]
instantiating using Array.of creates an array with those elements.
Array.of(2)
> [2]
The point of Array.of is to solve the issue where you want to pass a type around that gets constructed later, which in the special case of array is problematic when it receives a single argument. For instance:
function build(myItem, arg){
return new myItem(arg);
}
Which would give:
console.log(build(Array, 2));
> [undefined x 2]
// ??? Can't pass the literal definition:
//console.log(build([, 1))
console.log(build(Array.of, 2));
> [2]
Or to use even more of ES6 as an example:
var params = [2,3];
console.log(new Array(...params));
// [2,3]
console.log(new Array.of(...params));
// [2,3]
params = [2];
console.log(new Array(...params));
// [undefined x2]
console.log(new Array.of(...params));
// [2]
Array.of consistently does what you expect.