TypeScript

Exploring Array.from() in TypeScript

I needed to initialize a 2D grid of zeros for a pathfinding algorithm. My first instinct was nested for loops. Then I remembered Array.from() exists.

5 May 2024

Exploring Array.from() in TypeScript

I needed to initialize a 2D grid of zeros for a pathfinding algorithm. My first instinct was nested for loops. Then I remembered Array.from() exists.

Array.from() creates a new array from anything array-like or iterable. Think of it as a factory function: you hand it a shape and a recipe, and it builds the array for you.

Text
Array.from(arrayLike [, mapFunction [, thisArg]])

Want an array of three zeros? One line:

Text
const arr = Array.from(Array(3), () => 0);
console.log(arr); // [0, 0, 0]

Need a 2D grid? Still one line:

Text
const grid = Array.from(Array(2), () => Array.from(Array(4), () => 0));
// [[0, 0, 0, 0], [0, 0, 0, 0]]

When it shines

  • Generating sequences: Array.from({ length: 5 }, (_, i) => i) gives you [0, 1, 2, 3, 4].
  • Converting NodeLists, Sets, or Maps into plain arrays.
  • Creating arrays with computed values without mutable loop variables.

The trade-off

Array.from() is more expressive than a for loop, but it allocates intermediate structures. For hot paths with millions of iterations, a plain loop still wins on performance.

For everything else, Array.from() makes your intent obvious at a glance. That matters more than saving a few microseconds.