When we are maintaining variables in our Javascript code, we must already know about the scope that determines the visibility of variables. There are three types of scope which are block, function, and global scope. A variable defined inside a function is not visible (accessible) from outside the function. But, the variable is visible to any blocks or functions inside the function.
When a function is created, it has access to variables in the parent scope and its own scope, and it is known as closure scope. For example, if we create a function (child) inside another function (parent), in the creation time the child function will also have access to variables declared in its parent.
Another way to think of closure is that every function in JavaScript has a hidden property called "Scope", which contains a reference to the environment where the function was created. The environment consists of the local variables, parameters, and arguments that were available to the function at the time of its creation. When the function is invoked, it can access those variables through its "Scope" property, even if they are not in the current execution context.
Let's take a look at an example.
function makeFunc() {
let n = 0;
return function () {
n++;
return n;
}
}
const myFunc = makeFunc();
We create a function named "myFunc
" by calling another function named "makeFunc
". Then, let's try to call the "myFunc
" function three times.
const a = myFunc();
const b = myFunc();
const c = myFunc();
console.log(a, b, c);
The result will be "1 2 3". It seems that the function maintains a variable which is outside the execution context. It is possible because of the invisible closure scope that still exists and lets the "myFunc
" function access and process the variable "n".
Comments
Post a Comment