JavaScript for C# Developers: 6. Closures

Category: JavaScript
Last Modified: May 2 2017
Oct 30 2015

Closures are an important concept in JavaScript and give raise to some of the real power of the language. Later in this series I will discuss JavaScript module patterns – all of which rely on closures. In order to understand closures lets look at a specific example function.

function sayHello(name){     var text = 'Hello ' + name;     var sayAlert = function(){ alert(text); }     sayAlert(); } 

This function can be invoked by calling sayHello.

sayHello("John"); 

The first line in the function creates a local variable (remember variables are scoped at the function level) called text which prepends the word “Hello ” to the name parameter.  In the second line an anonymous function is created and assigned to the local variable sayAlert which calls alert with the value of the text variable.  Finally the function assigned to the sayAlert variable is invoked, the result being that invoking sayHello(“John”) will pop up the javascript alert with the text “Hello John”.

A Closure Example

While the above example is a closure its not really very useful as we will see later.  Let’s modify this function to return the sayAlert variable, to create a more useful closure.

function sayHello2(name){     var text = 'Hello ' + name;     var sayAlert = function(){ alert(text); }     return sayAlert; } 

Lets say we use the sayHello2 function in our program as follows.

var say2 = sayHello2("Jane"); say2(); 

Most programmers will understand that sayHello2 is returning a reference to the anonymous sayAlert function.  C programmers would understand that the variables sayAlert and say2 are each pointers to the same function.  However there is a critical difference between this function reference in JavaScript and a pointer,  You can think of the function reference as having a pointer to the function as well as an additional hidden pointer to the function’s closure. 

The above function has a closure because the anonymous function is declared inside it.

In C and most other languages, when you return from a function, all the local variables are no longer accessible as the stack-frame is destroyed.  In JavaScript, if you declare a function within another function, the local variables 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().

That’s it.  This concept is quite simple once you grok it, but it is a very powerful JavaScript concept as it helps us to use various module patterns to break up our code into manageable components.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Tags