Rajesh Rajesh - 10 months ago 35
Javascript Question

Array.of vs "[ ]". When to use Array.of over "[ ]"?

I was doing a bit of reading when I found Array.of.

As per MDN,

The Array.of() method creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.

var a = Array.of(1,2,3,4,5);

But if I already know the values, I can also wrap them in
to get same output. So is there a specific scenario when we can/should use
? Also is there any benefit of using it over

Edit 1:

Objective of this question is difference between
and not
new Array

Answer Source

There is one subtle difference between Array.of() and Array() / [] constructor. Normally just like Array(), the this in Array.of() will be the Array object and it will use the Array.constructor which is function Array() to construct it's result.

However Array.of can behave differently by changing it's bound context. If the bound context can be used as a constructor (if the bound object is a function) it will use that function to construct. So let's bind the Array.of() to a function and see what happens.

function Test(n){console.log(n)}
Test.prototype.last = function(){return this[this.length-1]};

var what = Array.of.call(Test, [5,6,7], {a:0,b:1}, 42, null, "this is last");

So we got an array like thingy with access to all function methods plus the ones at our constructor's prototype.

It's best to remember it's definition;

NOTE 2 The of function is an intentionally generic factory method; it does not require that its this value be the Array constructor. Therefore it can be transferred to or inherited by other constructors that may be called with a single numeric argument.

OK this can be very handy for array sub-classing. I know array sub-classing is possible by involving Object.setPrototypeOf() or __proto__ but they are somewhat discouraged operations and we can still do a similar job with the help of Array.of(). So .. once known to be useless Array.of() here becomes a hero; may be one of the most useful Array methods. How come..? let's see...

function SubArr(){}
SubArr.prototype = Object.create(Array.prototype); // make SubArr.prototype's prototype Array.prototype
SubArr.prototype.last = function(){return this[this.length-1]}; // add prototype methods to SubArr

var what = Array.of.call(SubArr, 1, 2, 3, 4, "this is last");
console.log(what.map(e => e));
console.log(what instanceof Array);

I have also tried making SubArr.prototype.constructor = Array; but Array.isArray(what) still resulted false though.