Ads by adsterra

Explanation and Five Common Use Cases of Array.from() In JavaScript

Array.from() Method

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.

Use Cases

  1. Converting a NodeList to an Array

    const nodeList = document.querySelectorAll('.items');
    const array = Array.from(nodeList);
  2. Mapping values from an iterable object

    const numbers = [1, 2, 3, 4, 5];
    const multiplied = Array.from(numbers, (num) => num * 2);
  3. Creating a range of numbers

    const range = Array.from({ length: 5 }, (_, index) => index + 1);
  4. Handling function arguments

    function sum() {
      const numbers = Array.from(arguments);
      return numbers.reduce((total, num) => total + num, 0);
    sum(1, 2, 3);
  5. Creating copies of arrays or array-like objects

    const originalArray = [1, 2, 3];
    const copyArray = Array.from(originalArray);

array javascript
Newer Post Older Post Home

Popular Posts