Advertisement
A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.
1. Own scope where variables defined between its curly brackets
2. Outer function's variables
3. Global variables
Let's take an example of closure concept,
1function Welcome(name) {
2
3var greetingInfo = function (message) {
4 console.log(message + " " + name);
5};
6
7return greetingInfo;
8}
9
10var myFunction = Welcome("John");
11
12myFunction("Welcome "); //Output: Welcome John
13
14myFunction("Hello Mr."); //output: Hello Mr. JohnAs per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.
Advertisement
JavaScript Coding Exercise 30
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement