The JavaScript Array.from()
method creates a new array instance from an array-like or iterable object. It allows you to convert objects that resemble arrays (such as NodeLists, Strings, Maps, Sets, etc.) or iterable objects (such as the arguments object or custom iterables) into proper arrays. The method takes two optional arguments: a mapping function and a this value to be used within the mapping function.
const nodeList = document.querySelectorAll('.items');
const array = Array.from(nodeList);
const numbers = [1, 2, 3, 4, 5];
const multiplied = Array.from(numbers, num => num * 2);
const range = Array.from({ length: 5 }, (_, index) => index + 1);
function sum() {
const numbers = Array.from(arguments);
return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3);
const originalArray = [1, 2, 3];
const copyArray = Array.from(originalArray);
These examples illustrate how versatile the Array.from()
method can be in various programming scenarios. Whether transforming NodeList into arrays, manipulating number ranges, handling function arguments, or simply copying arrays, Array.from()
proves to be an invaluable tool in any JavaScript developer's toolkit.