Priya’s weather station sends readings one at a time, and her Python service iterates over them with a Feed class. Today’s six, in degrees Celsius, are 12.5, 13.1, a dropped read stored as null, 14.0, 13.6, and 15.2. The dashboard is moving to JavaScript, and the feed goes first, because every chart loops over it.
A class that only wraps an array can hand out the built-in iterator returned by the array’s .values() method, as a Python __iter__() can return iter(self.values). Priya’s iterator keeps its own position instead, and porting it by hand shows what for...of asks of an iterator and where two Python habits break it.
Port the Python Iterator
In Python, Feed.__iter__() returns a fresh FeedIterator, which remembers an index and hands back one reading per __next__() call, then raises StopIteration:
from collections.abc import Iterator
class FeedIterator(Iterator):
def __init__(self, values):
self.values = values
self.index = 0
def __next__(self):
if self.index < len(self.values):
value = self.values[self.index]
self.index += 1
return value
raise StopIteration
class Feed:
def __init__(self, values):
self.values = values
def __iter__(self):
return FeedIterator(self.values)
Subclassing Iterator gives FeedIterator an __iter__() that returns self. You’ll use this behavior in the last section.
JavaScript has no dunder names. A loop looks for a method keyed by the built-in symbol Symbol.iterator, a key no string can clash with. You write the method name in square brackets. The method returns an iterator, an object whose .next() returns a result object such as { value: 12.5, done: false }.
The port needs no second class. [Symbol.iterator]() returns an object literal whose .next() keeps using the local i and values, as a Python closure keeps its outer names, but it can reassign i without nonlocal. Postfix i++ hands back the old i, then adds one, so values[i++] folds self.values[self.index] and self.index += 1 into one expression.
The local copy of this.values is there because a method’s this is the object it’s called on. The loop calls .next() on the object literal, so this.values there would miss the feed’s readings. Finally, Python signals the end of the data with an exception, so a first try turns raise StopIteration into a throw:
class Feed {
constructor(values) {
this.values = values;
}
[Symbol.iterator]() {
let i = 0;
const values = this.values;
return {
next() {
if (i < values.length) {
return { value: values[i++], done: false };
}
throw new Error("StopIteration");
},
};
}
}
const readings = [12.5, 13.1, null, 14.0, 13.6, 15.2];
for (const reading of new Feed(readings)) {
console.log(reading);
}
Python’s loop would stop quietly after 15.2. Before reading on, predict what for...of does when .next() throws. Here’s the real run. This shortened output omits the source context and stack trace:
12.5
13.1
null
14
13.6
15.2
...
Error: StopIteration
...
JavaScript numbers don’t split into int and float, so 14.0 prints as 14. On the seventh request, .next() threw, and the error escaped the loop and stopped the program.
End With a Done Result
Python’s for catches StopIteration to end the loop. JavaScript’s for...of catches nothing: the iterator ends the loop by returning a result whose done is true. To for...of, a throw always means something went wrong.
The fix returns one more result object instead, with done: true and no reading in value. Spread syntax, written as three dots inside an array literal, works like Python’s [*feed], so spreading the feed twice checks that it ends cleanly and that each pass starts over:
class Feed {
constructor(values) {
this.values = values;
}
[Symbol.iterator]() {
let i = 0;
const values = this.values;
return {
next() {
if (i < values.length) {
return { value: values[i++], done: false };
}
return { value: undefined, done: true };
},
};
}
}
const feed = new Feed([12.5, 13.1, null, 14.0, 13.6, 15.2]);
console.log([...feed]);
console.log([...feed]);
Both passes list the whole day:
[ 12.5, 13.1, null, 14, 13.6, 15.2 ]
[ 12.5, 13.1, null, 14, 13.6, 15.2 ]
Each spread calls [Symbol.iterator]() again, starting a new i at zero, as each iter(feed) builds a new FeedIterator. The done result is an ordinary return value, so nothing has to catch it.
Watch out: .next() must return a result object on every call, the last one included, so returning the bare reading or letting the method end without a return breaks every loop over the feed.
Make the Iterator Iterable Too
The dashboard shows the first reading as the opening value, then charts the rest. In Python, Priya takes one value with next() and lets a for loop continue from the same iterator:
readings = [12.5, 13.1, None, 14.0, 13.6, 15.2]
cursor = iter(Feed(readings))
print("Opening", next(cursor))
for reading in cursor:
print(reading)
The loop calls iter(cursor), gets cursor itself back from the inherited __iter__(), and carries on from 13.1.
Watch out: JavaScript has no global iter() or next(), so you call the feed’s [Symbol.iterator]() and the cursor’s .next() yourself. The class is unchanged from the previous section, and the port follows it:
class Feed {
constructor(values) {
this.values = values;
}
[Symbol.iterator]() {
let i = 0;
const values = this.values;
return {
next() {
if (i < values.length) {
return { value: values[i++], done: false };
}
return { value: undefined, done: true };
},
};
}
}
const feed = new Feed([12.5, 13.1, null, 14.0, 13.6, 15.2]);
const cursor = feed[Symbol.iterator]();
console.log("Opening", cursor.next().value);
for (const reading of cursor) {
console.log(reading);
}
Python’s loop carried on from 13.1. Here’s what this one prints after the opening value. This shortened output omits the source context and stack trace:
Opening 12.5
...
TypeError: cursor is not iterable
...
The error names the cursor. Before the loop’s first .next() call, for...of asks its target for [Symbol.iterator](), as Python’s for calls iter(). In Python, the Iterator base class provides def __iter__(self): return self for you. The object literal has no base class, so this iterator follows the convention only if you add the method.
The fix is the JavaScript spelling of that method, added after .next() in the object literal. When for...of calls cursor[Symbol.iterator](), this is the cursor, so the loop gets the same iterator back, partway through the readings:
class Feed {
constructor(values) {
this.values = values;
}
[Symbol.iterator]() {
let i = 0;
const values = this.values;
return {
next() {
if (i < values.length) {
return { value: values[i++], done: false };
}
return { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
},
};
}
}
const feed = new Feed([12.5, 13.1, null, 14.0, 13.6, 15.2]);
const cursor = feed[Symbol.iterator]();
console.log("Opening", cursor.next().value);
for (const reading of cursor) {
console.log(reading);
}
The loop now picks up where .next() left off:
Opening 12.5
13.1
null
14
13.6
15.2
Built-in iterators, such as the one an array’s .values() returns, already return this, so they’re iterable iterators. Yours should be too, or for...of and spread can’t use it. Later in the course, generators build this whole object for you.
In the next exercise, Replay a Day’s Readings, you’ll write the same kind of iterator for the station’s wind log, one the dashboard can replay as often as needed, continue after taking one reading by hand, and finish cleanly when it’s empty.