Open In App

JS Equivalent to Python Range

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, the range() function is used to generate a sequence of numbers, commonly for iteration in loops. JavaScript, however, doesn’t have a built-in range() function, but there are various ways to achieve similar functionality. In this article, we will explore how to replicate the behavior of Python’s range() function in JavaScript.

What is Python's range()?

In Python, the range() function is used to generate a sequence of numbers. It is particularly useful in for loops and can take up to three arguments:

range(start, stop, step)
  • start: The starting value of the sequence (inclusive).
  • stop: The end value of the sequence (exclusive).
  • step: The interval between numbers in the sequence.

Example of Python range() Function

Python
for i in range(2, 10, 2):
    print(i)

Output
2
4
6
8

Explanation:

  • In this example, range(2, 10, 2) generates numbers starting from 2 up to (but not including) 10, with a step of 2.

Using Negative Step in Python range() Function

Python
for i in range(10, 0, -2):
    print(i)

Output
10
8
6
4
2

Explanation:

  • Here, the range() function generates numbers starting from 10 and decrements by 2 until it reaches 1 (but doesn’t include 0).

JavaScript Equivalent to Python range()

Below are the approaches and methods by which we can compare the equivalence between JavaScript range and Python range():

Using Array.from() Method in JavaScript

In JavaScript, the most straightforward way to create a sequence of numbers similar to Python’s range() is by using the Array.from() method. This method can be used to generate an array of numbers based on the length and a mapping function.

Example of Array.from() Function in JavaScript

JavaScript
const range = (start, end, step = 1) => 
  Array.from({ length: Math.floor((end - start) / step) }, (v, i) => start + i * step);

console.log(range(2, 10, 2));

Output
[ 2, 4, 6, 8 ]

Explanation:

  • The Array.from() method creates an array with a specified length.
  • The length of the array is determined by the difference between stop and start, divided by step.
  • The mapping function ((v, i) => start + i * step) calculates each element in the array, starting from start and increasing by step for each iteration.

Using for Loop in JavaScript

For more control over the sequence or if we prefer an iterative approach, we can use a for loop to generate an array of numbers similar to Python’s range().

Example of Using a for Loop in JavaScript:

JavaScript
function range(start, end, step = 1) {
  const arr = [];
  for (let i = start; i < end; i += step) {
    arr.push(i);
  }
  return arr;
}

console.log(range(2, 10, 2));  

Output
[ 2, 4, 6, 8 ]

Explanation:

  • This approach initializes an empty array result.
  • The for loop starts at start and increments by step until it reaches (but does not include) stop.
  • The loop pushes each number into the result array.

Using map() Method with Range in JavaScript

JavaScript’s map() method can also be leveraged to create a sequence of numbers. This approach is a bit more functional and less imperative than using a for loop.

Example of Using map() Function in JavaScript

JavaScript
const range = (start, end, step = 1) => 
  [...Array(Math.floor((end - start) / step))].map((_, i) => start + i * step);

console.log(range(2, 10, 2));

Output
[ 2, 4, 6, 8 ]

Explanation:

  • The spread syntax ([...]) creates an array of a specific length, based on the difference between stop and start.
  • The map() function then generates the sequence by applying the calculation start + i * step for each index i in the array.

Using while Loop in JavaScript

For cases where a while loop is more appropriate (e.g., when we don’t know the length of the range ahead of time), we can also use this loop to generate a range of numbers.

Example of Using a while Loop in JavaScript

JavaScript
function range(start, end, step = 1) {
  const arr = [];
  while (start < end) {
    arr.push(start);
    start += step;
  }
  return arr;
}

console.log(range(2, 10, 2));  

Output
[ 2, 4, 6, 8 ]

Explanation:

  • The while loop continues as long as start is less than stop.
  • Each time, it pushes start into the result array and increments start by step.

Using Negative Steps (Descending Order) in JavaScript

Just like Python's range() supports negative steps, JavaScript solutions can easily handle this by adjusting the loop or array construction logic.

Example of Negative Step in JavaScript

JavaScript
function range(start, end, step = -1) {
  const arr = [];
  for (let i = start; i > end; i += step) {
    arr.push(i);
  }
  return arr;
}

console.log(range(10, 0, -2));

Output
[ 10, 8, 6, 4, 2 ]

Explanation:

  • When using a negative step, the loop decrements i until it goes below the stop value.

Using Generator Functions in JavaScript

JavaScript generators provide a powerful way to create iterators that can yield a sequence of numbers on demand. This approach is particularly useful if we need lazy evaluation or if the sequence is large.

Example of Generator Function in JavaScript

JavaScript
function* range(start, end, step = 1) {
  for (let i = start; i < end; i += step) {
    yield i;
  }
}

const it = range(2, 10, 2);
console.log([...it]); 

Output
[ 2, 4, 6, 8 ]

Explanation:

  • The range() function is now a generator, which yields each value in the sequence.
  • The yield keyword pauses the function and returns the current value, resuming the next time the generator is iterated.

Next Article
Article Tags :
Practice Tags :

Similar Reads