A closure is the combination of a function enclosed with references to its surrounding state (lexical environment). It gives you access to an outer function’s scope or environment from an inner function.
Consider the following code snippet:
function outerFunction() {
let innerVar = "I'm inside outerFunction"
function innerFunction() {
console.log(`${innerVar}, but I can be accessed from innerFunction too!`)
}
innerFunction()
}
outerFunction()
// > "I'm inside outerFunction, but I can be accessed from innerFunction too!"
In the above code snippet, outerFunction
creates a variable called innerVar
, and a function called innerFunction
. The innerFunction
function is enclosed inside, and is only available within, outerFunction
. innerFunction
has no local variables of its own, but is able to access innerVar
because they are both within the lexical scope of outerFunction
.
#javascript #developer