The JavaScript Array.from() method is a built-in static method that creates a new array from an iterable object or an array-like object. It allows developers to convert different types of data into standard JavaScript arrays, making them easier to access, manipulate, and process using array methods.
In JavaScript, some values look like arrays but are not actual arrays. For example, strings, Set objects, Map objects, and DOM collections can contain multiple values. However, they do not all provide the complete set of array methods. The Array.from() method helps convert these values into real arrays.
Consider the following example:
const text = "JavaScript";
const result = Array.from(text);
console.log(result);
Output:
["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
In this example, Array.from() converts the string into an array containing individual characters.
Another example uses a Set:
const numbers = new Set([10, 20, 30, 40]);
const result = Array.from(numbers);
console.log(result);
Output:
[10, 20, 30, 40]
The method creates a new array containing the values from the Set.
One important characteristic of Array.from() is that it does not modify the original iterable or array-like object. Instead, it returns a newly created array.
Syntax and Parameters
Array.from(items) Array.from(items, mapFn) Array.from(items, mapFn, thisArg)
Parameters
-
items— The iterable or array-like object to convert. -
mapFn(optional) — A mapping function invoked for every element. Receives two arguments:elementandindex. Note: UnlikeArray.prototype.map,mapFndoes not receive the source array as a third argument, because the array is still under construction . -
thisArg(optional) — Value to use asthiswhen executingmapFn.
Return Value
A new Array instance. The result is always dense: missing indices in the source become undefined in the output, never holes .
Creating an Array from a String
A string is an iterable value in JavaScript. The Array.from() method can convert a string into an array of characters.
const language = "JavaScript";
const characters = Array.from(language);
console.log(characters);
Output:
[
"J", "a", "v", "a", "S",
"c", "r", "i", "p", "t"
]
Each character becomes an individual element in the resulting array.
You can access the individual characters using their indexes:
const language = "JavaScript";
const characters = Array.from(language);
console.log(characters[0]);
console.log(characters[4]);
console.log(characters.length);
Output:
J
S
10
This is useful when you need to work with characters individually using array methods.
Converting a String Containing Spaces
The Array.from() method also preserves spaces as individual elements.
const message = "Hello World";
const result = Array.from(message);
console.log(result);
Output:
[
"H", "e", "l", "l", "o",
" ", "W", "o", "r", "l", "d"
]
The space between the two words is included in the resulting array.
Creating an Array from an Array-Like Object
An array-like object is an object that has a length property and indexed properties. It does not necessarily have to be an actual array or an iterable object.
For example:
const arrayLike = {
0: "HTML",
1: "CSS",
2: "JavaScript",
length: 3
};
const result = Array.from(arrayLike);
console.log(result);
Output:
["HTML", "CSS", "JavaScript"]
The Array.from() method reads the length property and obtains the indexed values to create a new array.
The original object remains unchanged.
Array.from() vs. Array.prototype.map() on Sparse Arrays
A subtle but important behavioral difference: Array.from() never creates sparse arrays. If the source is a sparse array (e.g., new Array(5)), Array.from() treats every index as present and assigns undefined where the source has a hole. In contrast, map() skips holes and preserves sparseness .
const sparse = new Array(3); // [empty × 3] console.log(0 in sparse); // false // Array.from densifies const densified = Array.from(sparse); console.log(0 in densified); // true console.log(densified); // [undefined, undefined, undefined] // map preserves holes and skips callback let calls = 0; const mapped = sparse.map(() => { calls++; return 1; }); console.log(calls); // 0 (callback never invoked) console.log(1 in mapped); // false (still sparse)
Generic Behavior: Works on Any Constructor
Array.from() is a generic factory method. It does not require this to be the Array constructor. If a subclass of Array inherits from(), the inherited method returns instances of the subclass, not Array .
class MyArray extends Array {} const instance = MyArray.from([1, 2, 3]); console.log(instance instanceof MyArray); // true console.log(instance instanceof Array); // true
The this value can be any constructor function that accepts a single numeric argument (the length). This makes Array.from() useful in custom collection classes that want to provide a static factory method.
Creating Arrays from Generator Functions
JavaScript generator functions provide another way to create iterable sequences. A generator function uses the function* syntax and produces values one at a time with the yield keyword. Since generator objects are iterable, they can be converted into arrays using Array.from().
Consider the following example:
function* generateNumbers() {
yield 10;
yield 20;
yield 30;
yield 40;
}
const numbers = Array.from(generateNumbers());
console.log(numbers);
Output:
[10, 20, 30, 40]
In this example, generateNumbers() returns a generator object. The Array.from() method iterates through the generator and collects all yielded values into a new array.
You can also transform generator values during conversion:
function* generateNumbers() {
yield 1;
yield 2;
yield 3;
yield 4;
}
const result = Array.from(
generateNumbers(),
number => number * 10
);
console.log(result);
Output:
[10, 20, 30, 40]
The mapping callback receives each generated value and returns the transformed value. This allows you to convert and process generator output in one operation.
Remember that converting a generator into an array consumes its values until the generator finishes. An infinite generator cannot finish naturally, so attempting to convert one completely will not produce a completed array.
Creating Arrays from the keys() and values() Methods
JavaScript objects such as Map and Set provide methods that return iterable objects. You can use Array.from() to convert these iterators into ordinary arrays.
Converting Map Keys into an Array
The keys() method of a Map returns an iterator containing all keys.
const user = new Map([
["name", "John"],
["age", 25],
["country", "Bangladesh"]
]);
const keys = Array.from(user.keys());
console.log(keys);
Output:
["name", "age", "country"]
The returned array contains all keys in their insertion order.
Converting Map Values into an Array
The values() method returns an iterator containing the values stored in a Map.
const user = new Map([
["name", "John"],
["age", 25],
["country", "Bangladesh"]
]);
const values = Array.from(user.values());
console.log(values);
Output:
["John", 25, "Bangladesh"]
You can also use a mapping function while converting the values:
const numbers = new Map([
["first", 10],
["second", 20],
["third", 30]
]);
const result = Array.from(
numbers.values(),
value => value * 2
);
console.log(result);
Output:
[20, 40, 60]
Converting Set Values into an Array
A Set provides keys(), values(), and entries() methods. For a Set, keys() and values() return equivalent iterators.
const colors = new Set(["Red", "Green", "Blue"]);
const result = Array.from(colors.values());
console.log(result);
Output:
["Red", "Green", "Blue"]
These methods make it easy to extract specific parts of a collection and convert them into arrays.
Creating an Array of Objects with Array.from()
The mapping function can create objects instead of returning simple numbers or strings. This is useful when generating structured data dynamically.
const users = Array.from(
{ length: 3 },
(_, index) => ({
id: index + 1,
name: `User ${index + 1}`,
active: true
})
);
console.log(users);
Output:
[
{ id: 1, name: "User 1", active: true },
{ id: 2, name: "User 2", active: true },
{ id: 3, name: "User 3", active: true }
]
The method creates three objects with different IDs and names. Each callback invocation returns a new object, so every array position contains a separate object.
You can also generate product records:
const products = Array.from(
{ length: 4 },
(_, index) => ({
productId: 1001 + index,
productName: `Product ${index + 1}`,
price: (index + 1) * 500
})
);
console.log(products);
Output:
[
{ productId: 1001, productName: "Product 1", price: 500 },
{ productId: 1002, productName: "Product 2", price: 1000 },
{ productId: 1003, productName: "Product 3", price: 1500 },
{ productId: 1004, productName: "Product 4", price: 2000 }
]
This approach provides a convenient way to construct structured collections with predictable properties.