Range Operator

for (let i = 0; i < 10; i += 2) {
  // Whatever
}

I mean, come on. It's 2023! Why do we still have to write code like that?

Python, for e.g., has its awesome range() function which returns an iterable sequence of numbers within the provided range. Rust also has a range operator (0..10) that does the same thing.

JS too could really use a range operator.

One that would return a new special Range iterable which could be looped over like

for (let i of :10:2) {
  // Whatever
}

Isn't that cool? A few examples for you to catch the semantics

1:10  // 1, 2, 3, ..., 9
:10   // 0, 1, 2, ..., 9
10:   // 10, 11, 12, ..., Infinity
:     // 0, 1, 2, ..., Infinity
:10:2 // 0, 2, 4, ..., 9
1:10: // 1, 2, 3, ..., 9
::2   // 0, 2, 4, ..., Infinity
::    // You know this

Very like Python's array slice notation.
Speaking of arrays, it's also quite common to need an array with an arithmetic sequence of numbers. Maybe we could 'magically spread' the Range iterable into an array for that?

const numbers = [...1:10] // [1, 2, 3, ..., 9]

That's two birds with one stone. What do u think?

1 Like
3 Likes

Yeah, nice to see that people have given the problem attention. All the same, I would prefer an operator over a function.

1 Like

Syntax has a much higher barrier to entry, so unless there's a stronger motivation than "it saves a few characters" it's unlikely to get approval.

1 Like

[a..b] and [a..n..b] syntax ยท Issue #20 ยท tc39/proposal-iterator.range ยท GitHub covers some syntax suggestions. The issue concluded with:

I think if a new syntax is really necessary, we can add it in the future after all. The current proposal should focus on the API shape and runtime semantics.