Closures 11.9 Flashcards
What is the difference between a bound variable and a free variable?
bound variables are defined within the scope, aka paramaters and local variables. free variables are defined outside of the scope., aka non-local variables
What is a closure
A closure is a function plus a connection to the variables that exist at the functions birth place or it’s lexical environment.
Explain what is happening here:
function funcFactory(value) {
return () => {
return value
}
}
const func = funcFactory(‘abc’)
assert.equal(func(), ‘abc’)
the return of funcFactory (a closure) is being assigned to variable func. because func is still connected to variables at it’s birthplace, it can still access the free ‘value’ variable )even though func escaped it’s scope).
What is a use case for closures?
you can use a closure to store states and make updates to them via function calls.