javascript · level 3 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
for...of asks an for one value at a time.
Arrays and strings are : for...of can walk through them. Behind the scenes it asks for an iterator, an object whose next() method returns { value, done }. The loop keeps calling next() until done is true.
The method that makes the iterator lives under a special key, . Give your own object that method, and for...of and spread both work with it, as if it were an array.
const countdown = {
[Symbol.iterator]() {
let current = 3;
return {
next() {
if (current === 0) { return { value: undefined, done: true }; }
current--;
return { value: current + 1, done: false };
}
};
}
};
for (const n of countdown) { console.log(n); }
console.log([...countdown]); Square brackets around a key, like [Symbol.iterator], use the value inside them as the key's name.
guess first
Calling next by hand. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const queue = ["Kai", "Lin"];
const turn = queue[Symbol.iterator]();
console.log(turn.next().value);
console.log(turn.next().value);
console.log(turn.next().done);
your turn
Your turn. Make a playlist loopable.
Name a song for the middle of the playlist. Then pick the index that matches track i, remembering that i has already gone up by one.
fix it
The fridge will not open. Can you fix it?
- The TypeError says
fridgeis not iterable. Which key doesfor...oflook for? - A method called
iteratoris an ordinary name. The loop only looks under the specialSymbol.iteratorkey. - Rename
iterator()to[Symbol.iterator]()on line 3, then press run.
nailed it
you looked inside for...of. :D
- An iterator's
next()returns{ value, done }objects. for...ofcallsnext()untildoneistrue.- A
[Symbol.iterator]method makes any object iterable.
new words in your collection
- iterable
- iterator
- Symbol.iterator
This lesson isn’t saved. A free account remembers every lesson you finish.