Member-only story
How to do cleanup in an Iterator in Javascript
In JavaScript, it’s common not to worry about memory management due to the presence of garbage collection, which automatically removes unreachable objects over time. However, it’s often more efficient to eliminate objects immediately when they are no longer needed.
Cleanup within an iterator becomes particularly crucial, as iterators may be referenced for a more extended period than regular functions. The longer the reference is retained, the more time it takes for garbage collecting them. Take a look at the great article “Memory Management in Javascript” by pandaquests for more in-depth information.
And please share this article to your friends for free using this link!
An iterator, as explained in the previous article “Iterables and Iterators in Javascript” doesn’t know when the caller of the iteration is done because the next() method can be called at any time, whether today or tomorrow. This is where the optional return() and throw() methods come into play. When invoked, these methods signal that the work with the iterator is complete.
The return value for both methods is an object with two properties: value and done, similar to the return value of next(). The value will default to undefined unless an argument is passed into the method, in which case it will return the provided value…





