Javascript

Learning Javascript Closure with Examples

Closures are one of the most important topic in JavaScript which you must need to understand if you really want to excel Javascript and its basic concept. And that is what we are trying to do in this article i.e trying to explain closures in a much easier way and with some examples.

This is a relatively short article on Javascript Closure but if you want to read more closure, you can check our detailed article on closure i.e – what is closure in javascript.

Javascript closure with example

What is closure in Javascript?

In a very simple term, Closure contains a function and all the variables that were in scope when the function got declared. The closure has three scope chains:

  1. It has access to its own scope (variables defined between its curly brackets).
  2. It has access to the outer function’s variables.
  3. It has access to the global variables.

Also Read: What is Closure in Javascript?

Javscript Closure Examples

Example 1:

function say667() {
    // Local variable that ends up within closure
    var num = 666;
    var sayAlert = function() { alert(num); }
    num++;
    return sayAlert;
}

The above stated example shows that the local variables are not copied infact they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!

Example 2: In the below written code we have hree global functions all having a common reference to the same closure because they are all declared within a single call to setupSomeGlobals().

function setupSomeGlobals() {
     // Local variable that ends up within closure
     var num = 666;
     // Store some references to functions as global variables
     gAlertNumber = function() { alert(num); }
     gIncreaseNumber = function() { num++; }
     gSetNumber = function(x) { num = x; }
 }

That conclude the basic of Javascript closure with some examples. Feel free share and comment if you have any feedback.

Leave a Comment