I have a JavaScript class that wraps an array. The class looks something like this.
class Store {
constructor() {
this._store = [];
}
}
I am trying to define a Symbol.iterator
, so a class instance can be iterated through with for example a for (... of ...)
loop.
The class is designed in such a way, that the _store
parameter can be null
. My solution for defining Symbol.iterator
function in compliance with this is as follows
class Store {
...
[Symbol.iterator]() {
return (this._store || [])[Symbol.iterator]();
}
}
The idea behind this is, that if the _store
holds an array, this code will return _store[Symbol.iterator]
, otherwise it will return iterator of an empty array.
If console.log
-ged, the following expression appears to be a function, as expected.
console.log( (this._store || [])[Symbol.iterator] )
However, once this function is called, the following error is thrown, which points to the code which called the function.
TypeError: Cannot convert undefined or null to object
Any ideas to why this is happening?