Stage 2
Classification: API Change
Human Validated: KW
Title: Iterator.range
Authors: Jack Works
Champions: Jack Works
Last Presented: April 2024
Stage Upgrades:
Stage 1: 2020-04-01
Stage 2: 2023-03-22
Stage 2.7: NA
Stage 3: NA
Stage 4: NA
Last Commit: 2025-02-05
Topics: iterators numbers
Keywords: iterator arithmetic bigint integer
GitHub Link: https://github.com/tc39/proposal-iterator.range
GitHub Note Link: https://github.com/tc39/notes/blob/main/meetings/2024-04/april-09.md#iteratorrange-for-stage-27

Proposal Description:

Iterator.range

Champions: Jack Works

Author: Jack Works

Stage: 2

This proposal describes adding Iterator.range to JavaScript.

See the rendered spec at here.

Compare with other languages (Work in progress)

Playground

Polyfill

Motivation

  • because we don’t have it yet™

Without these functions, the language feels incomplete, and is a paper cut to what could be a very polished experience. Bringing this into the platform will improve performance of the web, and developer productivity as they no longer have to implement these common functions.

—— String.prototype.{padStart,padEnd}

range is a very useful function. For example in Python:

for i in range(5):
    # ...

At least 20 different implementations in a single stackoverflow question.

Tons of libraries providing a range: math.js, lodash, underscore.js, ramda, d3, range, fill-range, multi-integer-range, ……

Goals

  • Arithmetic Sequence
    • Incremental (0, 1, 2, 3, …)
    • Decremental (0, -1, -2, -3, …)
    • Step (0, 2, 4, 6, …)
      • Decimal step (0, 0.2, 0.4, …)
  • BigInt Support
    • Same as Arithmetic Sequence
  • Infinite Sequence Iterator.range(0, Infinity) (0, 1, 2, 3, …)

Non-goals

  • New Syntax
  • String Sequence (a, b, c, d, …)
  • Magic
    • E.g. if (x in Iterator.range(0, 10)) (Kotlin has this feature)

Examples

See tests to learn about more usages.

for (const i of Iterator.range(0n, 43n)) console.log(i) // 0n to 42n
 
Iterator.range(0, Infinity)
    .take(1000)
    .filter((x) => !(x % 3))
    .toArray()
 
function* even() {
    for (const i of Iterator.range(0, Infinity)) if (i % 2 === 0) yield i
}
;[...Iterator.range(1, 100, 2)] // odd number from 1 to 99

Presentations

Signature

See global.d.ts