Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between generators and closures in JavaScript?

Tags:

People also ask

What is the difference between scope and closure in JavaScript?

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.

What are generators in JavaScript?

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.

Is generator a closure?

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.

What are closures in JavaScript?

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?

Closure Method

const numberIncrementer = startValue => () => startValue++
const getNextNumber = numberIncrementer(0)

console.log(getNextNumber())
// 0

console.log(getNextNumber())
// 1

console.log(getNextNumber())
// 2

Generator Method

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?