In JavaScript, if you use the function
keyword inside another function, you are creating a closure.
The following code returns a reference to a function:
1 2 3 4 5 6 7 |
function sayHello2(name) { var text = 'Hello ' + name; // Local variable var say = function() { console.log(text); } return say; } var say2 = sayHello2('Rinoy'); say2(); // logs "Hello Rinoy" |
The above code has a closure because the anonymous function function() { console.log(text); }
is declared inside another function, sayHello2()
in this example.
In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.
In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function say2()
after we have returned from sayHello2()
. Notice that the code that we call references the variable text
, which was a local variable of the function sayHello2()
.
1 2 3 4 5 6 7 |
function sayAlice() { var say = function() { console.log(alice); } // Local variable that ends up within closure var alice = 'Hello Alice'; return say; } sayAlice()();// logs "Hello Alice" |