Why does Array.of
exist? AFAIK it simply creates an array from the arguments passed (i.e Array.of(1,2,3) -> [1,2,3]).
This JSPerf shows that this simple replacement function (which works exactly the same way) performs 80-90% faster than Array.of
const array_of = (...args) => [...args];
^ this is valid ES6 and so is Array.of
3
Answers
That’s totally OK. Passing a lot of parameters to a function and creating its stack frame is just an expensive operation.
Also if you refer to the documentation, it’s a static method of
Array
:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
So there’re additional scenarios how to use it, like subclassing
Array
so you can create instances of your subclass ofArray
. That could be useful, like passing it by reference as a factory for your subclass.While its less performant that could be not important on usual data sizes used in web app.
I can also say that it is because of
Array.of
can be used in older browsers that do not support the spread operator. It is the part of ECMAScript 6 (ES6) as built-in object. It is more consistent with other built-in methods, such asArray.from
andArray.map
.This above means that when you create
Array(3)
it creates an empty array length 3, not an array with single element, 3. In case ofArray.of
It always creates an array with the arguments you pass to it. which is good to not making unexpected results.Fair question. I will try to give it a fair answer
My argument is that
Is more clear than
Why?
In both cases we are creating a new array. This is crucial because arrays are handled by reference. Long story short: we all agree that the below code will update both arrays
Both x and y arrays has now 4 elements, because y is only a reference to the already created x array. Any modification in y will address the instance referenced by both x and y
That is why, when we are cloning complex types (not primitives) we intend the new instance to be separated and not affect the original value. In our example, will will make the following modification to get more excepted results
It is clear that y is a clone of x, for me at least, way more than just
My question is: why stopping here? What if we need to clone an object instead?
While some argue that this is a cool way to do it
I think that the classic way is more readable
You don’t have to be javascript master in order to understand it
Also, it worth mentioning that for both cases you can make a clone by using
Which is a very simple way (or a dirty hack) to serialize and desterilize an object, creating a perfect clone of it
In conclusion:
When performance matters, the performance of the team is crucial as well. Most chances that they will understand and also appreciate more performant code (and will probably be bitter whenever they encounter
forEach
loop)In any other case, keep it simple for other humans to maintain your code base
Cheers