Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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); console.log(a)

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 Array.of? Also is there any benefit of using it over []?

Edit 1:

Objective of this question is difference between Array.of vs [] and not new Array vs Array.of

like image 273
Rajesh Avatar asked Oct 10 '16 06:10

Rajesh


People also ask

What is difference between a [] and a {}?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

When would you use an array of objects?

Arrays are best to use when the elements are numbers. objects are best to use when the elements strings (text).

What is the difference between array and array of objects?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

What is array of in JS?

The Array. of() method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments. The difference between Array. of() and the Array constructor is in the handling of integer arguments: Array.


2 Answers

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.

like image 123
Redu Avatar answered Sep 18 '22 15:09

Redu


Although this method might have been standardized, it does appear to be unsupported in a number of browsers, so using it seems risky and, as you note, pretty much pointless.

The utility of this function seems to be for cases where you need to declare an array but don't want to assemble it out of parts. That is, you want to be able to pass a number of arguments to some function that then returns an Array.

If you follow the links to the justification of that method you get this:

The use-case is when you can't write a literal, because you are passing a function-that-constructs as a funarg, and the eventual caller may pass only one number arg, or several args. In that case, Array will not do the right thing in the one-number-arg case.

That's basically a way of saying "this function can receive variable length argument lists and will consistently return arrays populated with the correct values", but as in practice that converts an array to...an array, I'm not entirely convinced this thing needs to exist and apparently many browser implementors are of a similar mindset.

The push for Array.of largely a response to the fact that new Array() behaves inconsistently:

new Array(2); // [ , ] 2-element array that's unpopulated  new Array(1,2); // [1,2] 2-element array populated with the provided values 

Array.of will always operate like the latter version.

like image 41
tadman Avatar answered Sep 20 '22 15:09

tadman