Skip to content

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 · 1 min read

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:

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

Need a 2D grid? Still one line:

Typescript
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.

Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.

Go further
Live cohort on Maven

Forward Deployed AI Engineering: From Customer Problem to Production Value

A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.

January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.

View the live cohort

Keep reading