1

The following works on the JavaScript runtimes I've checked (Node.js and Firefox):

let xs = [0, 1, 2]
let it = xs[Symbol.iterator]()
for (let x of it) console.log(x)

This works because the it iterator is itself iterable, i.e. it has a Symbol.iterator property. One could presume this is because Array.prototype[Symbol.iterator] is implemented as a generator.

My question is, can I rely on it being iterable? That is, is it required by the spec?

I've looked (this is the relevant part, I think) and I can't find anything that says that an array iterator should be iterable, or that it must be implemented with a generator.

1 Answer 1

3

You can! All standard iterators for core objects extend %IteratorPrototype% which specifically defines:

25.1.2.1 %IteratorPrototype% [ @@iterator ] ( )

The following steps are taken:

  1. Return the this value.

The value of the name property of this function is [Symbol.iterator].

So every builtin iterator will automatically return itself when used as an iterable, so using it in a for...of or any other iteration context is safe.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.