-1

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?

1
  • from is not an instance method that fills an instantiated array, but rather a static method of the Array class itself. Commented Sep 29, 2016 at 20:57

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Thanks. One quick thing though, and it may be a silly question - probably is - but if Array is a static function with methods on it, does that mean that Arrays I declare also have available the .from() method, because they are of type Array? Even though having that method would be useless on an array... Am I making any sense at all?
No. Arrays "inherit" all the methods defined on 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 .
And a secondary reason might be to allow subclassing :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.