Skip to main content

What does Array.from() do?

The Array.from() method is a universal way to create a new array from an iterable (for example, a string, Set, Map) or an array-like (arguments, NodeList) object.

It also lets you transform elements on the fly while creating the array.


Syntax:

javascript
Array.from(arrayLike, mapFn, thisArg);
ParameterDescription
arrayLikeAn iterable object (string, Set, Map, arguments, NodeList, etc.)
mapFn (optional)A function that transforms each element
thisArg (optional)The this context for mapFn

Usage examples:

1. From a string → an array of characters

javascript
const str = "hello"; const arr = Array.from(str); console.log(arr); // ["h", "e", "l", "l", "o"]

2. From a Set

javascript
const set = new Set([1, 2, 3]); const arr = Array.from(set); console.log(arr); // [1, 2, 3]

3. From an array-like (arguments)

javascript
function example() { const args = Array.from(arguments); console.log(args); // [10, 20, 30] } example(10, 20, 30);

arguments is not a real array, but Array.from() turns it into a regular array.


4. With element transformation (via mapFn)

javascript
const arr = Array.from([1, 2, 3], x => x * 2); console.log(arr); // [2, 4, 6]

Similar to map(), built right into array creation.


5. From length: creating an array by length

javascript
const arr = Array.from({ length: 5 }, (_, i) => i + 1); console.log(arr); // [1, 2, 3, 4, 5]

Very handy for generating numeric sequences.


Important:

  • Returns a new array.
  • Does not change the original object.
  • If arrayLike is not iterable and has no length property, it throws an error.

Comparison with similar tools:

MethodWhat it does
Array.of(1, 2, 3)creates an array from arguments
Array.from('abc')creates an array from an iterable object
[...iterable]copies an iterable object (no transform function)

In short:

What it doesCreates an array from an iterable or array-like object
ReturnsA new array
Changes the originalNo
Has a transform functionYes
ExampleArray.from("hi") → ["h","i"]

Summary: Array.from() is a powerful and flexible way to create an array from anything that can be "iterated over", and, if needed, transform elements right during creation.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.