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).
Recommended Posts
View AllDifference between var and let in JavaScript
Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...
What is the difference between Call, Apply and Bind
Looking to learn about the differences between Call, Apply, and Bind in JavaScript? This article breaks down the nuances of each method and provides c...
What is the purpose of the array slice method
The array slice method is a powerful tool in JavaScript used to extract a section of an array and return a new array. In this article, you'll learn ab...
What is prototype and prototype chaining in JavaScript
This article explains the concept of prototype and prototype chaining in JavaScript. Learn how prototypes work, how they are used to create inheritanc...
Differences between JavaScript Map and Object
Discover the key dissimilarities between JavaScript Map and Object. Learn how they store data, handle key collisions, and their performance trade-offs...