Skip to content

OutputNot attempted

A hand-written iterator

const range = {
start: 1,
end: 3,
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next: () => (current <= end ? { value: current++, done: false } : { value: undefined, done: true }),
};
},
};
console.log([...range]);
console.log(Math.max(...range), Array.from(range, (x) => x * 10));

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Anything with a [Symbol.iterator]() returning { next() } is iterable, so spread, for...of, Array.from and destructuring all work on it. Because a new iterator is created each time, the object can be iterated repeatedly.