Array.from & Array.of
Array.from & Array.of in Modern JavaScript
ES6 introduced static factory methods on the Array constructor—Array.from() and Array.of()—to resolve long-standing quirks with the legacy Array() constructor and simplify conversion of array-like and iterable objects.
1. The Pitfall of the Array Constructor
The legacy new Array() constructor behaves inconsistently depending on the number and type of arguments:
This unpredictability caused subtle bugs. ES6 introduced Array.of() and Array.from() as standard solutions.
2. Array.of(): Predictable Array Instantiation
Array.of() creates a new Array instance with a variable number of arguments, regardless of number or type:
3. Array.from(): Converting Iterables and Array-Likes
Array.from() creates a new, shallow-copied Array instance from an iterable object (Map, Set, String) or an array-like object (an object with a .length property and indexed elements, such as DOM NodeLists or arguments).
Converting a Set to an Array (Removing Duplicates)
Converting DOM NodeLists
4. Built-in Mapping Function
Array.from() accepts a second optional parameter: a mapFn that executes on every element during conversion. This avoids allocating an intermediate array.
Generating Number Ranges (Range Generator)
Practice Quiz
Deep Copy vs Shallow Copy
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| find, some, every | Deep Copy vs Shallow Copy |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.