We can make a regular (POJSO) JS Object iterable, like so:
const tempObj = {a: 1, b: 2, c: 3};
tempObj[Symbol.iterator] = function () {
const self = this;
const keys = Object.keys(self);
return {
next() {
const k = keys.shift();
return {
done: !k,
value: [k, self[k]]
}
}
}
};
now we can use for..of loop:
for (let [k,v] of tempObj) {
console.log(k,v);
}
and we get:
a 1
b 2
c 3
my question is - is there another method we need to implement besides next()? if not, why did the iterator spec choose to return an object instead of just returning a function? why isn't the spec simply:
tempObj[Symbol.iterator] = function () {
return function next {
return {
done: Object.keys(this).length === 0,
value: Object.keys(this).shift()
}
}
};
my only guess is that by returning an object, it leaves room for updates/changes.