liveBook · Manning

Array.from

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A JavaScript Array static method that creates a new array from an array-like or iterable object.

Need to use array methods on values returned by document.querySelectorAll? Array.from creates a real array from an array-like object, using its length and indexed properties. section 9.0 section 9.1

Convert function arguments

The arguments object is array-like, but it is not an array. Convert it before calling reduce: const args = Array.from(arguments); const sum = args.reduce((a, b) => a + b); return sum / args.length; section 9.1

Array.from also works with:

  • Strings, which become arrays of their indexed characters. section 9.1
  • Other objects with a length property; for example, Array.from({ length: 50 }) creates an array of length 50. section 9.1
let nodes = document.querySelectorAll('.accordian-panel');
let nodesArr = Array.from(nodes);
nodesArr.forEach(activatePanel);

Convert the NodeList returned by querySelectorAll, then use forEach to activate each panel. section 9.1

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Defines array-like inputs by length and indexed properties, with examples using arguments, strings, and custom objects.
Examples
Demonstrates converting arguments for an average function, turning strings into character arrays, and converting querySelectorAll results.
What you can do after
Apply Array.from to convert arguments or querySelectorAll results into arrays usable with methods such as reduce and forEach.
How it connects
Connects array-like objects with the arguments object, Array.prototype.slice, NodeList, and document.querySelectorAll.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.