For x in Range JavaScript

In this tutorial, we will go through some of the different ways to build an array of a specific length in JavaScript, much like the for x in range(n) method in Python.

 

Build Array of a Set Length in JavaScript using the Array Keys Function

The cleanest equivalent of for x in range() in JavaScript is to use the Array().keys() function like this:

 

var res = [...Array(4).keys()];

console.log(res);
[0, 1, 2, 3]

 

Create Array of N Length using a for Loop in JavaScript

Here is an example of how to build an array to N length using a for loop and the Array().keys() function:

 

res = []

for (let i of Array(4).keys()) {
res.push(i);
}

console.log(res)
[0, 1, 2, 3]