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

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.
Array.from(arrayLike [, mapFunction [, thisArg]])
Want an array of three zeros? One line:
const arr = Array.from(Array(3), () => 0);
console.log(arr); // [0, 0, 0]
Need a 2D grid? Still one line:
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.
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 cohortKeep reading
- TypeScript Anti-Patterns That Cost You Twice: Build Time, Runtime, and the Interview
- The Frontend Toolchain Is Now Written in Rust and Go. What That Means for You
- oxlint vs ESLint: Why I Replaced ESLint with oxlint
- SystemJS Is Dead. Native ESM Finally Won.
- Replace Axios with a Simple Custom Fetch Wrapper (Production-Ready Guide)
- Stop Shipping ChatGPT Wrappers. Ship an Agent in TypeScript, or Don't Bother.