Is there any suggestion around adding inclusive / exclusive ranges descriptors in JavaScript

m..n (exclusive)
m..=n (inclusive)

For instance, 1..3 means for [1, 2], while 1..=3 means for [1, 2, 3]:

for (const val of 1..3) console.log(val); // => 1, 2
for (const val of 1..=3) console.log(val); // => 1, 2, 3

References:

We already have a GitHub - tc39/proposal-Number.range: A proposal for ECMAScript to add a built-in Number.range() proposal which allows for both inclusive and exclusive ranges.

Not sure whether having syntactic sugar for Number.range would be necessary. I'm also assuming that you'd want syntactic sugar for BigInt.range too. For example, 1n..3n and 1n..=3n for exclusive and inclusive ranges respectively.

Also note that 1..3 could be interpreted as a property access. For example, 1..toString() is valid JavaScript. The literal is 1. and the .toString() is the method invocation. Hence, this syntax might be confusing.

Next, what if I want to generate a sequence with a step other than 1? For example, if I want to generate the sequence 0,2,4,6,8 or the sequence 5,4,3,2,1? What should be the syntax for such sequences?

Finally, would it make sense for the syntactic sugar to create an iterator or should it create an array? That is should 1..3 evaluate to [1,2] or should it evaluate to Number.range(1, 3)? The latter of course being an iterator. That way, we can create infinite sequences without having to allocate space.

If we explicitly want an array then we could have [1..3]. Similarly, if we wanted a set we could have new Set(1..3). Would this be more desirable?

3 Likes

To some extent, a syntactic sugar like this should make the code more simple to read.

When it comes to how to generate a reversed sequence like 5, 4, 3, 2, 1, we can define the order as sensitive order between m and n, and 5..=1 is not equivalent to 1..=5.

Step of a sequence is not an often case, and we can ignore it. For me, I intend to consider whether such a sugar should be limited to a sub-sequence of natural numbers.