Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.from instead of Array.prototype.from [duplicate]

Tags:

javascript

As far as I have seen any array related method it has to be accessed from its prototype, e.g. Array.prototype.slice.

Why is the from method called on Array object as in Array.from instead of being called as Array.prototype.from?

like image 272
aryan singh Avatar asked Oct 16 '25 05:10

aryan singh


1 Answers

You can look at Array.from as a constructor for arrays. The important thing here is that it can create an array from both array-like structures (having array-like properties like indexes and .length) and also iterables (objects with .next() or in other words - having a registered iterator).

There is absolutely no point in having the .from() method attached to the prototype like [1, 2, 3].from(). What do you expect this method to do exactly in this context? It serves no purpose.

In general, the instance (prototype) methods manipulate a specific already existing instance of an array. Static ones like Array.from(), Array.of() and Array.isArray() don't (and shouldn't) require an instance.

This is true not only for arrays but for general class/prototype design especially in data-structures.

like image 54
zhulien Avatar answered Oct 17 '25 18:10

zhulien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!