A function and the lexical context in which it was declared are combined to form a closure. Specifically, it is an inner function that has access to the variables of the outside or surrounding function.
Functions that refer to independent (free) variables are called closures. The function specified in the closure, in other words, “remembers” the environment in which it was developed.
The closure has three scope chains –
- Own scope where variables defined between its curly brackets
- Outer function’s variables
- Global variables
Let’s look at a closure concept example.
function Welcome(name) {
var greetingInfo = function (message) {
console.log(message + " " + name);
};
return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr.John
According to the code above, even after the outer function has returned, the inner function (i.e. greetingInfo) can access the variables in the outer function scope (i.e. Welcome).