What is this?
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. In JavaScript, closures are created every time a function is created, at function creation time.
Example:
function sum(x){
// outer functions scope
return function(y){
// inner functions scope
return x + y
}
}
const addSum = sum(3);
console.log(addSum(6)) // print 9
In this example, we have defined a function sum(x), that takes a single argument y and returns the sum of x and y.
The
sum
is a function factory. It creates functions that can add a specific value to their argument.In the example above, the function factory creates two new functions, one that adds three to its argument.
addSum
is closure. They share the same function body definition but store different lexical environments. In addSum
's lexical environment, x
is 3.
And then we call addSum(6)
the function return sum is 9, because addSum
already have x is 3 (share function body definition) and lexical environment received the argument y is 6 and it's a return sum of 3 and 6.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Top comments (0)