Array.of vs “[ ]”. When to use Array.of over “[ ]”?

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");
console.log(JSON.stringify(what,null,2));
console.log(what.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(JSON.stringify(what,null,2));
console.log(what.last());
console.log(what.map(e => e));
console.log(what instanceof Array);
console.log(Array.isArray(what));
console.log(Object.prototype.toString.call(what));

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

Leave a Comment