Programming Useful

Use Array.from() to Convert Iterables

Converting NodeLists, Sets, or strings to arrays requires complex manual conversion. Use Array.from() to convert any iterable into an array with optional mappin...

Problem

Converting NodeLists, Sets, or strings to arrays requires complex manual conversion.

Solution

Use Array.from() to convert any iterable into an array with optional mapping.

Benefit

Universal conversion solution that works with all iterable types.

Code Example

// Convert NodeList to Array
const divs = Array.from(document.querySelectorAll('div'));

// Create array from string
const chars = Array.from('hello'); // ['h','e','l','l','o']

// Create array with mapping
const squares = Array.from({length: 5}, (_, i) => i * i);
// [0, 1, 4, 9, 16]

ES
Edrees Salih
6 hours ago

We are still cooking the magic in the way!