# .take()

> The `.take()` JS method of the `Iterator` object returns a new iterator that yields a limited number of values.

## How do I take the first N values from an iterator?

The method that returns a new iterator yielding at most the given number of values from the original iterator, then finishing. Often used to get the first elements of an infinite generator.

- Topic: Iterator
- Type: method
- Browser support: Chrome 122+, Chrome Android 122+, Edge 122+, Firefox 131+, Firefox Android 131+, Safari 18.4+, Safari iOS 18.4+

## Example

Wrong:

```js
function* ids() {
  let id = 1;
  while (true) yield id++;
}
const first = [...ids()].slice(0, 3);
```

Right:

```js
function* ids() {
  let id = 1;
  while (true) yield id++;
}
const first = ids().take(3).toArray(); // [1, 2, 3]
```

Spreading an infinite generator never ends; `take()` stops after three values, so the array can be built.

## Common mistakes

- Calling `toArray()` on an infinite generator before `take()`, which hangs the page.

## Key points

- Infinite generators are limited with `take()` before `toArray()` or a loop.
- The limit is a non-negative number, otherwise `take()` throws a `RangeError`.

## Interview questions

### Does `take()` close the source iterator?

Yes. Once the limit is reached, `take()` calls `return()` on the source, so a generator's `finally` block runs.

### What if the iterator has fewer values than the limit passed to `take()`?

`take()` yields the values that exist and finishes, without an error.

## Related cards

- [.drop()](https://wonderium.dev/js/iterator-drop.md)
- [.toArray()](https://wonderium.dev/js/iterator-to-array.md)
- [Generator](https://wonderium.dev/js/generator.md)
- [Iterator](https://wonderium.dev/js/iterator.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/iterator-take
- Last updated: 2026-11-25
