In Javascript, we have two type of variables
- Local variable
- Global variable
A local variable can only be used within the function where its is defined whereas a global variable can be used by all the script within the page. What if we want to have a private variable?The answer is Javascript closure. Closure makes it possible for a function to have "private" variables.
The closure is an inner function that has access to the outer(parent) function's variable. So we can say that closure has three scope chains:
First one is, it can access all the variable defined in its own scope(local variable)
Second, it has access to the outer(parent) function’s variables and
The third one is, it has access to the global variables.
For Example:
function sayHello(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
return say;
}
sayHello('Bob');
// Hello Bob
Here you can see that text is a local variable, but the inner function can access outer functions' variable.
The inner function has access to the outer function’s variables along with the outer function’s parameters.
For Example:
function fullName (firstName, lastName) {
var name = "Your name is ";
function createFullName () {
return name + firstName + " " + lastName;
}
return createFullName();
}
fullName("Michael", "Jackson");
// Your name is Michael Jackson
In the example, above we have seen that closure function have access to the parent scope(variables and parameters). Closure function keeps a reference to the Parent function so that it can access variables and parameters from it even if the outer function is finished.
0 Comment(s)