DEV Community

Discussion on: Using Python range() in JavaScript

Collapse
 
dabat profile image
Daniel Battaglia

Hey, thanks for sharing this @guyariely very timely, as I was just looking at JavaScript range and generator functions 🙂

One question I have is what is the advantage of using an iterator here, rather than a simple for n to n and returning and array?

I found this article (joshwcomeau.com/snippets/javascrip...) which uses a for n to generate the output, and seems to work just as well, and also, like @lukeshir mentioned, supports forEach because the return is an array.

const range = (start, end, step = 1) => {
  let output = [];
  if (typeof end === 'undefined') {
    end = start;
    start = 0;
  }
  for (let i = start; i < end; i += step) {
    output.push(i);
  }
  return output;
};
Enter fullscreen mode Exit fullscreen mode

Link to a sandbox comparison: codesandbox.io/s/range-4idy5?file=...

Anyhow, thanks again for sharing!

Collapse
 
guyariely profile image
Guy Ariely

Hey Daniel, The reason I used iterators was to match Python range structure.
Notice how in order to get the python list (or Array in JavaScript), you have to call list(). The same kind of structure and semantics can be achieved in JavaScript by using iterators.

I agree this isn't the greatest use case for iterators, but it's simple and opens up the door for further exploration of this great tool.