Iterator.prototype.take()
Baseline 2025Newly available
Since March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Thetake() method ofIterator instances returns a newiterator helper object that yields the given number of elements in this iterator and then terminates.
In this article
Syntax
take(limit)Parameters
limitThe number of elements to take from the start of the iteration.
Return value
A newiterator helper object. The returned iterator helper yields the elements in the original iterator one-by-one, and then completes (thenext() method produces{ value: undefined, done: true }) oncelimit elements have been yielded, or when the original iterator is exhausted, whichever comes first.
Exceptions
RangeErrorThrown if
limitbecomesNaNor negative whenconverted to an integer.
Examples
>Using take()
The following example creates an iterator that yields terms in the Fibonacci sequence, and then logs the first three terms:
function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; }}const seq = fibonacci().take(3);console.log(seq.next().value); // 1console.log(seq.next().value); // 1console.log(seq.next().value); // 2console.log(seq.next().value); // undefinedUsing take() with a for...of loop
take() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with afor...of loop:
for (const n of fibonacci().take(5)) { console.log(n);}// Logs:// 1// 1// 2// 3// 5Becausefibonacci() is an infinite iterator, using afor loop to iterate it without any logic to exit early (such as abreak statement) would result in an infinite loop.
Combining drop() with take()
You can combinetake() withIterator.prototype.drop() to get a slice of an iterator:
for (const n of fibonacci().drop(2).take(5)) { // Drops the first two elements, then takes the next five console.log(n);}// Logs:// 2// 3// 5// 8// 13for (const n of fibonacci().take(5).drop(2)) { // Takes the first five elements, then drops the first two console.log(n);}// Logs:// 2// 3// 5Lower and upper bounds of take count
When thelimit is negative orNaN, aRangeError is thrown:
fibonacci().take(-1); // RangeError: -1 must be positivefibonacci().take(undefined); // RangeError: undefined must be positiveWhen thelimit is larger than the total number of elements the iterator can produce (such asInfinity), the returned iterator helper has essentially the same behavior as the original iterator:
for (const n of new Set([1, 2, 3]).values().take(Infinity)) { console.log(n);}// Logs:// 1// 2// 3Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-iterator.prototype.take> |