15 ms·
I'm interested in this simple closure code from the article: function getGetNext() { let i = 2; return function getNext() { const n
by SeanLuke 8y ago
I'm interested in this simple closure code from the article:
function getGetNext() {
let i = 2;
return function getNext() {
const next = i;
i = i * 2;
return next;
}
}
As a lisp coder [and not a JS coder], I'm wondering: why does the function getNext() have to be named? Why not just say something like:
function getGetNext() {
let i = 2;
return function() {
const next = i;
i = i * 2;
return next;
}
}
- kangoo1707 8y agoIt doesn't have to be named, your second example still works
- wbrasky 8y agonaming anonymous functions can provide some clarity in stack traces however
- SeanLuke 8y agoI got the syntax right? Was completely guessing.
- basil-rash 8y agoYep. Nowadays you'd be more likely to see it as: return () => { const next = i; i = i * 2; return next; } But in this case the two are equivalent.
- interesthrow2 8y agoOr as an alternative one can use a generator, they are built for that purpose AND are supported by a wide range of other JS constructs without any need to create iterators manually and all that. function * getNext(){ let i = 2; while(true){ i = i * 2; yield i; } } Here, no closure needed. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid...
- eithed 8y agoI think that's no longer getter-getter and the example was to show a function that explicitly returns a function.
- netghost 8y agoThe name is optional, and probably just to help explain the code.