Understanding JavaScript's Array.from() Method: Key Uses and Examples



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

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

Converting a NodeList to an Array

const nodeList = document.querySelectorAll('.items');
const array = Array.from(nodeList);

Mapping Values from an Iterable Object

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

Creating a Range of Numbers

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

Handling Function Arguments

function sum() {
    const numbers = Array.from(arguments);
    return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3);

Creating Copies of Arrays or Array-Like Objects

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.


More Posts For You!


5 More HTML Tricks For You

5 HTML Tricks That You Can Use To Enhance Your Web Pages

Effortlessly Convert Excel to JSON with JavaScript: Streamline Your Data Management with Sheet Js

Integrating OCR Capabilities into Web Applications with JavaScript and AppScript

Efficient Text Extraction from PDFs: Implementing OCR with JavaScript and AppScript

Build a CRUD Application Using Google Sheets as Database with HTML, CSS, and JavaScript

Integrating OpenAI with Google Sheets using AppScript for Automated Responses

Upload Images to Google Drive and Google Sheets from HTML File Input: A Complete JavaScript and AppScript Guide

Convert HTML and CSS to PDF with JavaScript Using HTML2PDF.js

Create a Functional Contact Form Using HTML, CSS, JavaScript, and Google AppScript

Build a CRUD App Using HTML, CSS, JavaScript, and IndexedDB API

Reading Data From Google Sheets to HTML Using JavaScript and Apps Script

PrevNext