Open In App

JavaScript Equivalent to Python's range() Function

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

In Python, the range() function is commonly used to generate a sequence of numbers. But in JavaScript, there is no direct equivalent to Python's range(). In this article, we will explore how we can achieve similar functionality using a variety of approaches in JavaScript.

Using a Generator Function

Starting from the simplest and most efficient method as we know is the generator function in JavaScript to create a range() is a powerful and efficient way to handle sequences of numbers.

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

// Example usage
console.log([...range(0, 5)]); 

Output
[ 0, 1, 2, 3, 4 ]

Let's explore various other methods in Javascript by which you can achieve similar functionality related to Python's range() functions.

Using for Loop

One of the easiest ways to create a range in JavaScript is by using a for loop. We can manually define the start, end, and step values.

JavaScript
let result = [];
for (let a = 0; a < 5; a++) {
// Add numbers to result array
    result.push(a);  
}
console.log(result); 

Output
[ 0, 1, 2, 3, 4 ]

Using Array.from() Method

If we want to avoid using a for loop, we can use JavaScript's built-in Array.from() method. This method can generate an array from a sequence of values, and we can use it to create a range.

JavaScript
// Example: Generate numbers from 0 to 4 (like range(5) in Python)
let result = Array.from({ length: 5 }, (a, i) => i);
console.log(result); 

Using map() on an Array

Another way to create a range in JavaScript is by using map() on an array. This method is a bit more complex but can still be useful for certain tasks.

JavaScript
// Example: Generate numbers from 0 to 4 (like range(5) in Python)
let result = [...Array(5)].map((_, a) => a);
console.log(result);  

Output
[ 0, 1, 2, 3, 4 ]

Creating a Custom range() Function

If we need more flexibility, we can write our own range() function. This function can take a start value, an end value, and a step size (just like Python's range()).

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

// Example: Generate numbers from 0 to 9 with a step of 2
let result = range(0, 10, 2);
console.log(result);  

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

Next Article
Article Tags :
Practice Tags :

Similar Reads