JavaScript Array.from(), Array.of() and Array.at()
Quick answer
Array.from constructs an array from an iterable or array-like object. Array.of constructs an array from individual arguments without the single-number length ambiguity.
How it works
Array.from(source, mapFn?, thisArg?) uses iteration when available, otherwise indexed reads up to length. Its optional mapper receives value and index. Array.of(3) contains the number 3; Array(3) has length 3 with holes. array.at(-1) reads the last value; out-of-range returns undefined.
const a = Array.from({length: 3}, (_, i) => i * 2);console.log(a.join(","));Expected output in Node.js:
0,2,4The mapper generates values using zero-based indices.
console.log(Array.of(3).length, Array(3).length, [4,9].at(-1));Expected output in Node.js:
1 3 9Array.of interprets the argument as a value; at counts from the end.
Common mistakes
An array-like object is not necessarily iterable. Array.from can read it; array spread requires iteration. The mapper is not given the constructed array.
Practice
Generate a sequence of five consecutive indices with Array.from and read its final element.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Array.from(), Array.of() and Array.at() — Knowledge Check
Apply the taught concept and predict the output.
What is Array.from priority if a source is both iterable and array-like?
What is Array.of(5)?
What does [4,9].at(-3) return?
What is the exact console output in JavaScript Array.from(), Array.of() and Array.at() example 1?
const a = Array.from({length: 3}, (_, i) => i * 2);console.log(a.join(","));What is the exact console output in JavaScript Array.from(), Array.of() and Array.at() example 2?
console.log(Array.of(3).length, Array(3).length, [4,9].at(-1));