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

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.
AI Transformation for Organisational Leaders
For directors, heads of function and founders: eight live evening sessions with Ehsan Gazar and Anoosh Zeighami, ending with a one-page 2027 AI plan for your organisation, built on a real workflow and ready for your leadership team.
$1,495, or $1,045 with code EARLYBIRD until 23 Oct.
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.