Array.from()

ES6+

Creates a new Array instance from an array-like or iterable object.

Syntax

Array.from(arrayLike, mapFn, thisArg)

Parameters

arrayLike ArrayLike | Iterable

An array-like or iterable object to convert to an array

mapFn Function optional

Map function to call on every element of the array

Return Value

Array

A new Array instance

Examples

JavaScript
console.log(Array.from('hello'));
console.log(Array.from([1, 2, 3], x => x * 2));
Output:
// ['h', 'e', 'l', 'l', 'o'] [2, 4, 6]

📌 When to Use

Use Array.from() when you need to create an array from array-like objects (NodeList, arguments), iterables (Map, Set, String), or when you need to generate arrays with a mapping function. It's the most versatile array creation method.

⚠️ Common Mistakes

Using Array.from() when spread operator would be simpler: [...nodeList] vs Array.from(nodeList)

Forgetting the second map argument can transform during creation, saving an extra map() call

Confusion between Array.from({length: n}) and Array(n) - Array(n) creates sparse array

✅ Best Practices

Create ranges: Array.from({length: 5}, (_, i) => i) gives [0,1,2,3,4]

Convert NodeList to array with map in one step: Array.from(elements, el => el.id)

Use for generating unique objects: Array.from({length: 3}, () => ({id: Math.random()}))

⚡ Performance Notes

Array.from() is slightly slower than spread operator for simple conversions, but offers more flexibility with the map function. For creating arrays of specific lengths, Array.from({length: n}) is more reliable than new Array(n) as it creates a dense array.

🌍 Real World Example

Converting DOM NodeList and Generating Sequences

Convert a NodeList to an array for iteration, and generate number sequences

// Convert NodeList to array (enables array methods)
const buttons = document.querySelectorAll('button');
const buttonTexts = Array.from(buttons, btn => btn.textContent);

// Generate a range of numbers [1, 2, 3, 4, 5]
const range = Array.from({length: 5}, (_, i) => i + 1);

// Generate alphabet array
const alphabet = Array.from({length: 26}, (_, i) =>
  String.fromCharCode(65 + i)
);
// ['A', 'B', 'C', ..., 'Z']

// Convert string to array of characters
const chars = Array.from('Hello');
// ['H', 'e', 'l', 'l', 'o']

Related Methods