JavaScript closures

Closures are functions that refer to variables from their parent environment. Using the closure pattern enables variables from the parent() function to remain bound to the closure. Let's take a look at the following example:

function parent() {
    var message = "Hello World";

    function child() {
        alert (message);
    }

    child();
}

parent();

In the preceding example, you can see how the child() function has access to a variable defined in the parent() function. But this is a simple example, so let's see a more interesting one:

function parent() {
   var message = 'Hello World';
    
  function child() {
    alert (message);
   }

   return child;
}

var childFN = parent()
childFN();

This time, the parent() function returned the child() function, and the child() ...

Get MEAN Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.