Fraser Hamilton

How to generate an array from 0 to N in JavaScript

June 19, 2020

Sometimes to we need to generate an array of numbers of a specific length in JavaScript that we can use our favourite Array.prototype functions on. I often find myself doing exactly that when I’m generating test data to populate my database with. Here’s a simple example using the from and keys methods:

const array = Array.from(Array(10).keys())

console.log(array)

// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

With the introduction the spread operator in ES6 we can actually make this snippet even shorter like so:

const array = [...Array(10).keys()]

console.log(array)

// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2020, Fraser Hamilton