Exploring Array.from() in JavaScript

A Beginner’s Guide to Transforming Arrays, NodeList, and More

In the dynamic realm of JavaScript, the `Array.from` method emerges as a versatile tool, capable of transforming various data structures into arrays effortlessly.

This article will unravel the potential hidden within `Array.from`, focusing on array-like objects, NodeLists, and the often-overlooked second parameter.

Understanding Array-Like Objects: A Bridge to Arrays

Previously:

Before the advent of `Array.from`, developers often had to resort to manual iteration or use Array.prototype.slice.call() to convert array-like objects into actual arrays. This process was cumbersome and less intuitive.

// Before
var arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
var realArray = Array.prototype.slice.call(arrayLike);

// Now with Array.from
var newArray = Array.from(arrayLike);


const stringOld = "Hello";
// Before
const oldStringArray = stringOld.split('');
console.log(oldStringArray); // Output: ['H', 'e', 'l', 'l', 'o']

// Now with Array.from
const newStringArray = Array.from(stringNew);
console.log(newStringArray); // Output: ['H', 'e', 'l', 'l', 'o']

Navigating the NodeLists: Converting DOM Elements with Ease

Previously:

When dealing with DOM NodeLists, developers commonly employed for loops or Array.prototype.map.call() to convert NodeLists into usable arrays. This added unnecessary complexity to the code.


var nodeList = document.querySelectorAll('p');

// Before
var arrayFromNodeList = [];
for (var i = 0; i < nodeList.length; i++) {
arrayFromNodeList.push(nodeList[i]);
}

// Now with Array.from
var newArrayFromNodeList = Array.from(nodeList);

Mastering Arguments: Simplifying Function Input Handling

Previously:

Prior to `Array.from`, converting the “arguments” object into an array involved manual iteration or using Array.prototype.slice.call(arguments). This approach was less readable and could be error-prone.

// Before
function getArgumentsArray() {
return Array.prototype.slice.call(arguments);
}

// Now with Array.from
function getArgumentsArray() {
return Array.from(arguments);
}

Unveiling the Second Parameter: Tailoring Your Transformation

Previously:

Before the introduction of the second parameter in `Array.from`, developers had to rely on subsequent method calls or loops to transform each element of the array. This often led to less elegant and more verbose code.

// Before
var originalArray = [1, 2, 3];
var squaredArray = originalArray.map(function (num) {
return num * num;
});

// Now with Array.from and the second parameter
var newArray = Array.from(originalArray, function (num) {
return num * num;
});

//Example 2

// Before
function generateRangeOld(start, end) {
let result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}

const oldRange = generateRangeOld(1, 5);
console.log(oldRange); // Output: [1, 2, 3, 4, 5]

// After
// Using Array.from to generate a range of numbers
function generateRangeNew(start, end) {
// 1. Create an array-like object with a specified length
// { length: end - start + 1 } creates an object with a length property.
// For example, if start=1 and end=5, it becomes { length: 5 }.
// This object is not a real array but has a length property.

// When dealing with an object like { length: 5 },
// which represents an array-like object with a specified length,
// Array.from() essentially creates a new array and fills it with
// values based on the provided mapping function.

// 2. Apply Array.from to convert the array-like object to a real array.
// The second argument is a mapping function that runs for each element.
// It receives two parameters: _ (ignored) and index.
// The mapping function calculates the value for each array element.

// 3. The calculated value is start + index.
// If start=1 and index=0, the first element becomes 1 + 0 = 1.
// If start=1 and index=1, the second element becomes 1 + 1 = 2.
// This continues until the last element.

return Array.from({ length: end - start + 1 }, (_, index) => start + index);
}

// 4. Call the generateRangeNew function with start=1 and end=5.
const newRange = generateRangeNew(1, 5);

// 5. Print the result to the console.
console.log(newRange); // Output: [1, 2, 3, 4, 5]

In conclusion, the introduction of Array.from has undoubtedly enhanced the clarity and efficiency of working with iterable and array-like structures in JavaScript. Its versatility in handling various scenarios, from converting array-like objects to simplifying the transformation of strings into arrays, has significantly improved the developer experience.

#javascript #webdevelopment #frontenddevelopment #reactjs

--

--

राहुल मिश्रा
राहुल मिश्रा

No responses yet