creation
Array.from
Creates a new Array from an iterable or array-like object, optionally mapping each element as it is copied (ES2015). Reach for it to materialize a NodeList, Set, string, or `{length}` array-like into a real array.
Array.from(iterableOrArrayLike[, mapFn[, thisArg]]) Parameters
| Parameter | Purpose |
|---|---|
| iterableOrArrayLike | Iterable (Set/Map/string) or array-like (has numeric `length`) |
| mapFn(element, index) | Optional map function applied during construction (skips an intermediate array) |
| thisArg | Value used as `this` inside mapFn |
Examples
console.log(Array.from('abc')); Logs: ['a', 'b', 'c']
console.log(Array.from(new Set([1,1,2,3]))); Logs: [1, 2, 3] (dedupe idiom)
console.log(Array.from({length: 3}, (_, i) => i * 2)); Logs: [0, 2, 4] (build range from array-like)
console.log(Array.from({length: 3}, () => [])); Logs: [[], [], []] (distinct references, unlike fill)
Gotcha
Array-like arguments need a numeric `length` property; plain objects without one become `[]`. Prefer `Array.from({length}, mapFn)` over `new Array(n).fill(...).map(...)` when you need distinct object slots.
Related methods
Array.isArray
Returns true if the value is an Array (works across realms/iframes, unlike `instanceof Array`). Reach for it as the canonical type check before running array-only methods.
Array.prototype.map
Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.
Array.prototype.flatMap
Maps each element with a callback, then flattens the result by one level (ES2019). Reach for it when a mapper naturally returns arrays and you want a single flat list back.