How to use Python’s range in Javascript

If you are used to pythons range, you could be disappointed not having a same way to go through for loops with it when you write javascript code. So if it happens to write javascript and you miss range, here is the function that will replace it so that you can use it like you do in python:

// this is a javascript emulation of range in python
function range(start, stop, step) {
    if (typeof stop == 'undefined') {
        // one param defined
        stop = start;
        start = 0;}
    if (typeof step == 'undefined') {
        step = 1;}
    if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
        return [];}
    var result = [];
    for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
        result.push(i);}
    return result;
};

and a simple example of usage, similar to Python

for (i in range(10)) console.log(i);

output

0 
1 
2 
3 
4
5  
6 
7 
8
9


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.