When you declare a variable in a function, you can only access it in the function. These variables are said to be scoped to the function. If you define any inner function within another function, this inner function is called a closure. It retains access to the variables created in the outer function.
A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a generator function, which returns an iterable Generator object.
Generators emulate the behavior of a closure where they wrap an initial value then can take subsequent values through next to yield something based on that initial wrapped value. This lesson walks through creating a closure then re-creating the same behavior with a generator.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
What's the difference between doing these two solutions to the same problem?
const numberIncrementer = startValue => () => startValue++
const getNextNumber = numberIncrementer(0)
console.log(getNextNumber())
// 0
console.log(getNextNumber())
// 1
console.log(getNextNumber())
// 2
const numberIncrementer = function*(startValue) {
while(true) {
yield startValue++
}
}
const numberFactory = numberIncrementer(0)
const getNextNumber = () => numberFactory.next().value
console.log(getNextNumber())
// 0
console.log(getNextNumber())
// 1
console.log(getNextNumber())
// 2
Viewing these two methods, what reason do I have to choose one over the other?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With