Iterating Over a Kit
In this lesson, you make a kit loopable in JavaScript, the way __iter__ does in Python. The checkout
desk lists a kit’s tools every time it’s loaned. In Python, the kit’s __iter__ method returns
iter(self.tools), so list() can walk any kit, as often as you ask, without knowing the tools sit in a list. JavaScript has no dunder names, so a
loop needs another hook.
A symbol is a key value that no string can equal, and brackets put a computed key in a class. Symbol.iterator
is the one built-in symbol whose method loops look for. Watch out: the key is the symbol
itself, so a string spelled "Symbol.iterator" is a different key, and no loop looks for it.
Suppose the port returns the tools array itself. Then it spreads the kit. Spread, three dots, works
like Python’s [*drilling]:
class Kit {
constructor(code, tools) {
this.code = code;
this.tools = [...tools];
}
[Symbol.iterator]() {
return this.tools;
}
}
const drilling = new Kit("KIT-17", ["drill", "bits"]);
console.log([...drilling]);