Creating Arrays

Array.from()

The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.

Array.from('hello')); // Array [ "h", "e", "l", "l", "o" ] Array.from([1, 2, 3, 4], x => x ** x)) // Array [1, 4, 27, 256]

Array.from() lets you create Arrays from:

  • array-like objects (objects with a length property and indexed elements)
  • iterable objects (objects such as Map and Set).

Array.isArray()

The Array.isArray() method determines whether the passed value is an Array.

instanceof vs isArray

When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes.

const iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; const arr = new xArray(1,2,3); // [1,2,3] // Correctly checking for Array Array.isArray(arr); // true // Considered harmful, because doesn't work through iframes arr instanceof Array; // false

Array.of()

The Array.of() method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.

The difference between Array.of() and the Array constructor is in the handling of integer arguments: Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7. (That implies an array of 7 empty slots, not slots with actual undefined values.)