I am a little confused with Array.from() in JavaScript. I know/think that is turns array-like values into arrays, but why, if Array is an object, do we not have to use the 'new' keyword to instantiate it before we can use it?
2 Answers
JavaScript has several collection types (HTMLCollection, NodeList, FileList, 'arguments', etc). The latter one being the variable containing all arguments passed to a function.
Imaging you have a function that requires data to be passed using an ordinary array - in that case Array.from(..) is super useful to convert any of the other collection types.
Comments
Array
is a function, functions are objects, objects have properties. from
is just a property on that object. That fact that Array
is a function and can be invoked with new
is irrelevant.
Example:
function foo() {}
foo.bar = function() {
console.log('hi');
}
foo.bar(); // hi
Presumably the primary reason for adding from
as property to Array
is to namespace it (instead of creating another global function).
3 Comments
Array.prototype
, not Array
. Think about Array.from
as a class method. It's defined on the class, not on its instances. Just like in my example above, if you did var f = new foo();
, f
wouldn't have the method bar
. To learn more about functions and prototypes, have a look at felix-kling.de/jsbasics/#/10 .
from
is not an instance method that fills an instantiated array, but rather a static method of theArray
class itself.