7619

How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?

I have seen the Scheme example given on Wikipedia, but unfortunately it did not help.

0

86 Answers 86

1 2
3
12

Closures are a somewhat advanced, and often misunderstood feature of the JavaScript language. Simply put, closures are objects that contain a function and a reference to the environment in which the function was created. However, in order to fully understand closures, there are two other features of the JavaScript language that must first be understood―first-class functions and inner functions.

First-Class Functions

In programming languages, functions are considered to be first-class citizens if they can be manipulated like any other data type. For example, first-class functions can be constructed at runtime and assigned to variables. They can also be passed to, and returned by other functions. In addition to meeting the previously mentioned criteria, JavaScript functions also have their own properties and methods. The following example shows some of the capabilities of first-class functions. In the example, two functions are created and assigned to the variables “foo” and “bar”. The function stored in “foo” displays a dialog box, while “bar” simply returns whatever argument is passed to it. The last line of the example does several things. First, the function stored in “bar” is called with “foo” as its argument. “bar” then returns the “foo” function reference. Finally, the returned “foo” reference is called, causing “Hello World!” to be displayed.

var foo = function() {
  alert("Hello World!");
};

var bar = function(arg) {
  return arg;
};

bar(foo)();

Inner Functions

Inner functions, also referred to as nested functions, are functions that are defined inside of another function (referred to as the outer function). Each time the outer function is called, an instance of the inner function is created. The following example shows how inner functions are used. In this case, add() is the outer function. Inside of add(), the doAdd() inner function is defined and called.

function add(value1, value2) {
  function doAdd(operand1, operand2) {
    return operand1 + operand2;
  }

  return doAdd(value1, value2);
}

var foo = add(1, 2);
// foo equals 3

One important characteristic of inner functions is that they have implicit access to the outer function’s scope. This means that the inner function can use the variables, arguments, etc. of the outer function. In the previous example, the “value1” and “value2” arguments of add() were passed to doAdd() as the “operand1” and “operand2” arguments. However, this is unnecessary because doAdd() has direct access to “value1” and “value2”. The previous example has been rewritten below to show how doAdd() can use “value1” and “value2”.

function add(value1, value2) {
  function doAdd() {
    return value1 + value2;
  }

  return doAdd();
}

var foo = add(1, 2);
// foo equals 3

Creating Closures

A closure is created when an inner function is made accessible from outside of the function that created it. This typically occurs when an outer function returns an inner function. When this happens, the inner function maintains a reference to the environment in which it was created. This means that it remembers all of the variables (and their values) that were in scope at the time. The following example shows how a closure is created and used.

function add(value1) {
  return function doAdd(value2) {
    return value1 + value2;
  };
}

var increment = add(1);
var foo = increment(2);
// foo equals 3

There are a number of things to note about this example.

The add() function returns its inner function doAdd(). By returning a reference to an inner function, a closure is created. “value1” is a local variable of add(), and a non-local variable of doAdd(). Non-local variables refer to variables that are neither in the local nor the global scope. “value2” is a local variable of doAdd(). When add(1) is called, a closure is created and stored in “increment”. In the closure’s referencing environment, “value1” is bound to the value one. Variables that are bound are also said to be closed over. This is where the name closure comes from. When increment(2) is called, the closure is entered. This means that doAdd() is called, with the “value1” variable holding the value one. The closure can essentially be thought of as creating the following function.

function increment(value2) {
  return 1 + value2;
}

When to Use Closures

Closures can be used to accomplish many things. They are very useful for things like configuring callback functions with parameters. This section covers two scenarios where closures can make your life as a developer much simpler.

Working With Timers

Closures are useful when used in conjunction with the setTimeout() and setInterval() functions. To be more specific, closures allow you to pass arguments to the callback functions of setTimeout() and setInterval(). For example, the following code prints the string “some message” once per second by calling showMessage().

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Closures</title>
  <meta charset="UTF-8" />
  <script>
    window.addEventListener("load", function() {
      window.setInterval(showMessage, 1000, "some message<br />");
    });

    function showMessage(message) {
      document.getElementById("message").innerHTML += message;
    }
  </script>
</head>
<body>
  <span id="message"></span>
</body>
</html>

Unfortunately, Internet Explorer does not support passing callback arguments via setInterval(). Instead of displaying “some message”, Internet Explorer displays “undefined” (since no value is actually passed to showMessage()). To work around this issue, a closure can be created which binds the “message” argument to the desired value. The closure can then be used as the callback function for setInterval(). To illustrate this concept, the JavaScript code from the previous example has been rewritten below to use a closure.

window.addEventListener("load", function() {
  var showMessage = getClosure("some message<br />");

  window.setInterval(showMessage, 1000);
});

function getClosure(message) {
  function showMessage() {
    document.getElementById("message").innerHTML += message;
  }

  return showMessage;
}

Emulating Private Data

Many object-oriented languages support the concept of private member data. However, JavaScript is not a pure object-oriented language and does not support private data. But, it is possible to emulate private data using closures. Recall that a closure contains a reference to the environment in which it was originally created―which is now out of scope. Since the variables in the referencing environment are only accessible from the closure function, they are essentially private data.

The following example shows a constructor for a simple Person class. When each Person is created, it is given a name via the “name” argument. Internally, the Person stores its name in the “_name” variable. Following good object-oriented programming practices, the method getName() is also provided for retrieving the name.

function Person(name) {
  this._name = name;

  this.getName = function() {
    return this._name;
  };
}

There is still one major problem with the Person class. Because JavaScript does not support private data, there is nothing stopping somebody else from coming along and changing the name. For example, the following code creates a Person named Colin, and then changes its name to Tom.

var person = new Person("Colin");

person._name = "Tom";
// person.getName() now returns "Tom"

Personally, I wouldn’t like it if just anyone could come along and legally change my name. In order to stop this from happening, a closure can be used to make the “_name” variable private. The Person constructor has been rewritten below using a closure. Note that “_name” is now a local variable of the Person constructor instead of an object property. A closure is formed because the outer function, Person() exposes an inner function by creating the public getName() method.

function Person(name) {
  var _name = name;

  this.getName = function() {
    return _name;
  };
}

Now, when getName() is called, it is guaranteed to return the value that was originally passed to the constructor. It is still possible for someone to add a new “_name” property to the object, but the internal workings of the object will not be affected as long as they refer to the variable bound by the closure. The following code shows that the “_name” variable is, indeed, private.

var person = new Person("Colin");

person._name = "Tom";
// person._name is "Tom" but person.getName() returns "Colin"

When Not to Use Closures

It is important to understand how closures work and when to use them. It is equally important to understand when they are not the right tool for the job at hand. Overusing closures can cause scripts to execute slowly and consume unnecessary memory. And because closures are so simple to create, it is possible to misuse them without even knowing it. This section covers several scenarios where closures should be used with caution.

In Loops

Creating closures within loops can have misleading results. An example of this is shown below. In this example, three buttons are created. When “button1” is clicked, an alert should be displayed that says “Clicked button 1”. Similar messages should be shown for “button2” and “button3”. However, when this code is run, all of the buttons show “Clicked button 4”. This is because, by the time one of the buttons is clicked, the loop has finished executing, and the loop variable has reached its final value of four.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Closures</title>
  <meta charset="UTF-8" />
  <script>
    window.addEventListener("load", function() {
      for (var i = 1; i < 4; i++) {
        var button = document.getElementById("button" + i);

        button.addEventListener("click", function() {
          alert("Clicked button " + i);
        });
      }
    });
  </script>
</head>
<body>
  <input type="button" id="button1" value="One" />
  <input type="button" id="button2" value="Two" />
  <input type="button" id="button3" value="Three" />
</body>
</html>

To solve this problem, the closure must be decoupled from the actual loop variable. This can be done by calling a new function, which in turn creates a new referencing environment. The following example shows how this is done. The loop variable is passed to the getHandler() function. getHandler() then returns a closure that is independent of the original “for” loop.

function getHandler(i) {
  return function handler() {
    alert("Clicked button " + i);
  };
}
window.addEventListener("load", function() {
  for (var i = 1; i < 4; i++) {
    var button = document.getElementById("button" + i);
    button.addEventListener("click", getHandler(i));
  }
});

Unnecessary Use in Constructors

Constructor functions are another common source of closure misuse. We’ve seen how closures can be used to emulate private data. However, it is overkill to implement methods as closures if they don’t actually access the private data. The following example revisits the Person class, but this time adds a sayHello() method which doesn’t use the private data.

function Person(name) {
  var _name = name;

  this.getName = function() {
    return _name;
  };

  this.sayHello = function() {
    alert("Hello!");
  };
}

Each time a Person is instantiated, time is spent creating the sayHello() method. If many Person objects are created, this becomes a waste of time. A better approach would be to add sayHello() to the Person prototype. By adding to the prototype, all Person objects can share the same method. This saves time in the constructor by not having to create a closure for each instance. The previous example is rewritten below with the extraneous closure moved into the prototype.

function Person(name) {
  var _name = name;

  this.getName = function() {
    return _name;
  };
}

Person.prototype.sayHello = function() {
  alert("Hello!");
};

Things to Remember

  • Closures contain a function and a reference to the environment in which the function was created.
  • A closure is formed when an outer function exposes an inner function. Closures can be used to easily pass parameters to callback functions.
  • Private data can be emulated by using closures. This is common in object-oriented programming and namespace design.
  • Closures should be not overused in constructors. Adding to the prototype is a better idea.

Link

11

A closure is created when the inner function is somehow made available to any scope outside the outer function.

Example:

var outer = function(params){ //Outer function defines a variable called params
    var inner = function(){ // Inner function has access to the params variable of the outer function
        return params;
    }
    return inner; //Return inner function exposing it to outer scope
},
myFunc = outer("myParams");
myFunc(); //Returns "myParams"
0
11

A closure is a block of code which meets three criteria:

  • It can be passed around as a value and

  • executed on demand by anyone who has that value, at which time

  • it can refer to variables from the context in which it was created (that is, it is closed with respect to variable access, in the mathematical sense of the word "closed").

(The word "closure" actually has an imprecise meaning, and some people don't think that criterion #1 is part of the definition. I think it is.)

Closures are a mainstay of functional languages, but they are present in many other languages as well (for example, Java's anonymous inner classes). You can do cool stuff with them: they allow deferred execution and some elegant tricks of style.

By: Paul Cantrell, @ http://innig.net/software/ruby/closures-in-ruby

11

Closures are simple

You probably shouldn't tell a six-year old about closures, but if you do, you might say that closure gives an ability to gain access to a variable declared in some other function scope.

enter image description here

function getA() {
  var a = [];

  // this action happens later,
  // after the function returned
  // the `a` value
  setTimeout(function() {
    a.splice(0, 0, 1, 2, 3, 4, 5);
  });

  return a;
}

var a = getA();
out('What is `a` length?');
out('`a` length is ' + a.length);

setTimeout(function() {
  out('No wait...');
  out('`a` length is ' + a.length);
  out('OK :|')
});
<pre id="output"></pre>

<script>
  function out(k) {
    document.getElementById('output').innerHTML += '> ' + k + '\n';
  }
</script>

0
10

Functions containing no free variables are called pure functions.

Functions containing one or more free variables are called closures.

var pure = function pure(x){
  return x 
  // only own environment is used
}

var foo = "bar"

var closure = function closure(){
  return foo
  // foo is free variable from the outer environment
}

src: https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure

0
10

Considering the question is about explaining it simply as if to a 6-year-old, my answer would be:

"When you declare a function in JavaScript it has forever access to all the variables and functions that were available in the line before that function declaration. The function and all the outer variables and functions that it has access to is what we call a closure."

0
9

I like Kyle Simpson's definition of a closure:

Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Lexical scope is when an inner scope can access its outer scope.

Here is a modified example he provides in his book series 'You Don't Know JS: Scopes & Closures'.

function foo() {
  var a = 2;

  function bar() {
    console.log( a );
  }
  return bar;
}

function test() {
  var bz = foo();
  bz();
}

// prints 2. Here function bar referred by var bz is outside 
// its lexical scope but it can still access it
test(); 
9

MDN explains it best I think:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

A closure always has an outer function and an inner function. The inner function is where all the work happens, and the outer function is just the environment that preserves the scope where the inner function was created. In this way, the inner function of a closure 'remembers' the environment/scope in which it was created. The most classic example is a counter function:

var closure = function() {
  var count = 0;
  return function() {
    count++;
    console.log(count);
  };
};

var counter = closure();

counter() // returns 1
counter() // returns 2
counter() // returns 3

In the above code, count is preserved by the outer function (environment function), so that every time you call counter(), the inner function (work function) can increment it.

8

Closure is when a function is closed in a way that it was defined in a namespace which is immutable by the time the function is called.

In JavaScript, it happens when you:

  • Define one function inside the other function
  • The inner function is called after the outer function returned
// 'name' is resolved in the namespace created for one invocation of bindMessage
// the processor cannot enter this namespace by the time displayMessage is called
function bindMessage(name, div) {

    function displayMessage() {
        alert('This is ' + name);
    }

    $(div).click(displayMessage);
}
8

This is how a beginner wrapped one's head around Closures like a function is wrapped inside of a functions body also known as Closures.

Definition from the book Speaking JavaScript "A closure is a function plus the connection to the scope in which the function was created" -Dr.Axel Rauschmayer

So what could that look like? Here is an example

function newCounter() {
  var counter = 0;
   return function increment() {
    counter += 1;
   }
}

var counter1 = newCounter();
var counter2 = newCounter();

counter1(); // Number of events: 1
counter1(); // Number of events: 2
counter2(); // Number of events: 1
counter1(); // Number of events: 3

newCounter closes over increment, counter can be referenced to and accessed by increment.

counter1 and counter2 will keep track of their own value.

Simple but hopefully a clear perspective of what a closure is around all these great and advanced answers.

8

For a six-year-old ...

Do you know what objects are?

Objects are things that have properties and do stuff.

One of the most important things about closures is that they let you make objects in JavaScript. Objects in JavaScript are just functions and closures that lets JavaScript store the value of the property for the object once it has been created.

Objects are very useful and keep everything nice and organised. Different objects can do different jobs and working together objects can do complicated things.

It's lucky that JavaScript has closures for making objects, otherwise everything would become a messy nightmare.

8

Closure are not difficult to understand. It depends only from the point of view.

I personally like to use them in cases of daily life.

function createCar()
{
    var rawMaterial = [/* lots of object */];
    function transformation(rawMaterials)
    {
       /* lots of changement here */
       return transformedMaterial;
    }
    var transformedMaterial = transformation(rawMaterial);
    function assemblage(transformedMaterial)
    {
        /*Assemblage of parts*/
        return car;
    }
    return assemblage(transformedMaterial);
}

We only need to go through certain steps in particular cases. As for the transformation of materials is only useful when you have the parts.

8

Let's start from here, As defined on MDN: Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.

Lexical scoping
Consider the following:

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function    
  }
  displayName();    
}
init();

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function. The displayName() function has no local variables of its own. However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

function init() {
    var name = "Mozilla"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

Closure
Now consider the following example:

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

Running this code has exactly the same effect as the previous example of the init() function above: this time, the string "Mozilla" will be displayed in a JavaScript alert box. What's different — and interesting — is that the displayName() inner function is returned from the outer function before being executed.

At first glance, it may seem unintuitive that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.

The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a reference to the instance of the function displayName created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use and "Mozilla" is passed to alert.

Here's a slightly more interesting example — a makeAdder function:

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In this example, we have defined a function makeAdder(x), which takes a single argument, x, and returns a new function. The function it returns takes a single argument, y, and returns the sum of x and y.

In essence, makeAdder is a function factory — it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.

add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.

Practical closures

Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:

body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}

h1 {
  font-size: 1.5em;
}

h2 {
  font-size: 1.2em;
}

Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units. Here's the JavaScript:

function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>


function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

for reading more about closures, visit the link on MDN

7

There once was a caveman

function caveman {

who had a very special rock,

var rock = "diamond";

You could not get the rock yourself because it was in the caveman's private cave. Only the caveman knew how to find and get the rock.

return {
    getRock: function() {
        return rock;
    }
};
}

Luckily, he was a friendly caveman, and if you were willing to wait for his return, he would gladly get it for you.

var friend = caveman();
var rock = friend.getRock();

Pretty smart caveman.

7

My perspective of Closures:

Closures can be compared to a book, with a bookmark, on a bookshelf.

Suppose you have read a book, and you like some page in the book. You put in a bookmark at that page to track it.

Now once you finish reading the book, you do not need the book anymore, except, you want to have access to that page. You could have just cut out the page, but then you would loose the context on the story. So you put the book back in your bookshelf with the bookmark.

This is similar to a closure. The book is the outer function, and the page is your inner function, which gets returned, from the outer function. The bookmark is the reference to your page, and the context of the story is the lexical scope, which you need to retain. The bookshelf is the function stack, which cannot be cleaned up of the old books, till you hold onto the page.

Code Example:

function book() {
   var pages = [....]; //array of pages in your book
   var bookMarkedPage = 20; //bookmarked page number
   function getPage(){
       return pages[bookMarkedPage];
   }
   return getPage;
}

var myBook = book(),
    myPage = myBook.getPage();

When you run the book() function, you are allocating memory in the stack for the function to run in. But since it returns a function, the memory cannot be released, as the inner function has access to the variables from the context outside it, in this case 'pages' and 'bookMarkedPage'.

So effectively calling book() returns a reference to a closure, i.e not only a function, but a reference to the book and it's context, i.e. a reference to the function getPage, state of pages and bookMarkedPage variables.

Some points to consider:

Point 1: The bookshelf, just like the function stack has limited space, so use it wisely.

Point 2: Think about the fact, whether you need to hold onto the entire book when you just want to track a single page. You can release part of the memory, by not storing all the pages in the book when the closure is returned.

This is my perspective of Closures. Hope it helps, and if anyone thinks that this is not correct, please do let me know, as I am very interested to understand even more about scopes and closures!

0
7

Closures in JavaScript are associated with concept of scopes.

Prior to es6, there is no block level scope, there is only function level scope in JS.

That means whenever there is a need for block level scope, we need to wrap it inside a function.

Check this simple and interesting example, how closure solves this issue in ES5

// let say we can only use a traditional for loop, not the forEach

for (var i = 0; i < 10; i++) {
    
    setTimeout(function() {
        console.log('without closure the visited index - '+ i)
    })
}

// this will print 10 times 'visited index - 10', which is not correct

/**
Expected output is 

visited index - 0
visited index - 1
.
.
.
visited index - 9

**/

// we can solve it by using closure concept 
   //by using an IIFE (Immediately Invoked Function Expression)


// --- updated code ---

for (var i = 0; i < 10; i++) {
    (function (i) {
      setTimeout(function() {
        console.log('with closure the visited index - '+ i)
      })
    })(i);
}

NB: this can easily be solved by using es6 let instead of var, as let creates lexical scope.


In simple word, Closure in JS is nothing but accessing function scope.

6

I have read all of these before in the past, and they are all very informative. Some come very close to getting the simple explanation and then get complex or remain abstract, defeating the purpose and failing to show a very simple real world use.

Though combing through all the examples and explanations you get a good idea of what closures are and aren't via comments and code, I was still unsatisfied with a very simple illustration that helped me get a closures usefulness without getting so complex. My wife wants to learn coding and I figured I needed to be able to show here not only what, but why, and and how.

I am not sure a six year old will get this, but I think it might be a little closer to demonstrating a simple case in a real world way that might acually be useful and that is easily understandable.

One of the best (or closest to simplest) is the retelling of Morris' Closures for Dummies example.

Taking the "SayHi2Bob" concept just one step further demonstrates the two basic things you can glean from reading all the answers:

  1. Closures have access to the containing function's variables.
  2. Closures persist in their own memory space (and thus are useful for all kinds of oop-y instantiation stuff)

Proving and demonstrating this to myself, I made a little fiddle:

http://jsfiddle.net/9ZMyr/2/

function sayHello(name) {
  var text = 'Hello ' + name; // Local variable
  console.log(text);
  var sayAlert = function () {
      alert(text);
  }
  return sayAlert;
}

sayHello(); 
/* This will write 'Hello undefined' to the console (in Chrome anyway), 
but will not alert though since it returns a function handle to nothing). 
Since no handle or reference is created, I imagine a good js engine would 
destroy/dispose of the internal sayAlert function once it completes. */

// Create a handle/reference/instance of sayHello() using the name 'Bob'
sayHelloBob = sayHello('Bob');
sayHelloBob();

// Create another handle or reference to sayHello with a different name
sayHelloGerry = sayHello('Gerry');
sayHelloGerry();

/* Now calling them again demonstrates that each handle or reference contains its own 
unique local variable memory space. They remain in memory 'forever' 
(or until your computer/browser explode) */
sayHelloBob();
sayHelloGerry();

This demonstrates both of the basic concepts you should get about closures.

In simple terms to explain the why this is useful, I have a base function to which I can make references or handles that contain unique data which persists within that memory reference. I don't have to rewrite the function for each time I want to say someone's name. I have encapsulated that routine and made it reusable.

To me this leads to at least the basic concepts of constructors, oop practices, singletons vs instantiated instances with their own data, etc. etc.

If you start a neophyte with this, then you can move on to more complex object property/member based calls, and hopefully the concepts carry.

6

I think it is valuable to take a step back, and examine a more general notion of a "closure" -- the so-called "join operator".

In mathematics, a "join" operator is a function on a partially ordered set which returns the smallest object greater than or equal to its arguments. In symbols, join [a,b] = d such that d >= a and d >= b, but there does not exist an e such that d > e >= a or d > e >= b.

So the join gives you the smallest thing "bigger" than the parts.

Now, note that JavaScript scopes are a partially ordered structure. So that there is a sensible notion of a join. In particular, a join of scopes is the smallest scope bigger than the original scopes. That scope is called the closure.

So a closure for the variables a, b, c is the smallest scope (in the lattice of scopes for your program!) that brings a, b, and c into scope.

6

A closure is basically creating two things : - a function - a private scope that only that function can access

It is like putting some coating around a function.

So to a 6-years-old, it could be explained by giving an analogy. Let's say I build a robot. That robot can do many things. Among those things, I programmed it to count the number of birds he sees in the sky. Each time he has seen 25 birds, he should tell me how many birds he has seen since the beginning.

I don't know how many birds he has seen unless he has told me. Only he knows. That's the private scope. That's basically the robot's memory. Let's say I gave him 4 GB.

Telling me how many birds he has seen is the returned function. I also created that.

That analogy is a bit sucky, but someone could improve it I guess.

6

The word closure simply refers to being able to access objects (six-year-old: things) that are closed (six-year-old: private) within a function (six-year-old: box). Even if the function (six-year-old: box) is out of scope (six-year-old: sent far away).

6

The easiest use case I can think of to explain JavaScript closures is the Module Pattern. In the Module Pattern you define a function and call it immediately afterwards in what is called an Immediately Invoked Function Expression (IIFE). Everything that you write inside that function has private scope because it's defined inside the closure, thus allowing you to "simulate" privacy in JavaScript. Like so:

 var Closure = (function () {
    // This is a closure
    // Any methods, variables and properties you define here are "private"
    // and can't be accessed from outside the function.

    //This is a private variable
    var foo = "";

    //This is a private method
    var method = function(){

    }
})();

If, on the other hand, you'd like to make one or multiple variables or methods visible outside the closure, you can return them inside an object literal. Like so:

var Closure = (function () {
  // This is a closure
  // Any methods, variables and properties you define here are "private"
  // and can't be accessed from outside the function.

  //This is a private variable
  var foo = "";

  //This is a private method
  var method = function(){

  }

  //The method will be accessible from outside the closure
  return {
    method: method
  }

})();

Closure.method();

Hope it helps. Regards,

0
6

The best way is to explain these concepts incrementally:

Variables

console.log(x);
// undefined

Here, undefined is JavaScript's way of saying "I have no idea what x means."

Variables are like tags.

You can say, tag x points to value 42:

var x = 42;
console.log(x);
// 42

Now JavaScript knows what x means.

You can also re-assign a variable.

Make tag x point to a different value:

x = 43;
console.log(x);
// 43

Now x means something else.

Scope

When you make a function, the function has its own "box" for variables.

function A() {
  var x = 42;
}

console.log(x);

// undefined

From outside the box, you cannot see what's inside the box.

But from inside the box, you can see what's outside that box:

var x = 42;

function A() {
  console.log(x);
}

// 42

Inside function A, you have "scope access" to x.

Now if you have two boxes side-by-side:

function A() {
  var x = 42;
}

function B() {
  console.log(x);
}

// undefined

Inside function B, you have no access to variables inside function A.

But if you put define function B inside function A:

function A() {

  var x = 42;

  function B() {
    console.log(x);
  }

}

// 42

You now have "scope access".

Functions

In JavaScript, you run a function by calling it:

function A() {
  console.log(42);
}

Like this:

A();

// 42

Functions as Values

In JavaScript, you can point a tag to a function, just like pointing to a number:

var a = function() {
  console.log(42);
};

Variable a now means a function, you can run it.

a();
// 42

You can also pass this variable around:

setTimeout(a, 1000);

In a second (1000 milliseconds), the function a points to is called:

// 42

Closure Scope

Now when you define functions, those functions have access to their outer scopes.

When you pass functions around as values, it would be troublesome if that access is lost.

In JavaScript, functions keep their access to outer scope variables. Even when they are passed around to be run somewhere else.

var a = function() {

  var text = 'Hello!'

  var b = function() {
    console.log(text);
    // inside function `b`, you have access to `text`
  };

  // but you want to run `b` later, rather than right away
  setTimeout(b, 1000);

}

What happens now?

// 'Hello!'

Or consider this:

var c;

var a = function() {

  var text = 'Hello!'

  var b = function() {
    console.log(text);
    // inside function `b`, you have access to `text`
  };

  c = b;

}

// now we are out side of function `a`
// call `a` so the code inside `a` runs
a(); 

// now `c` has a value that is a function
// because what happened when `a` ran

// when you run `c`
c();

// 'Hello!'

You can still access variables in the closure scope.

Even though a has finished running, and now you are running c outside of a.

What just happened here is called 'closure' in JavaScript.

4

Also... Perhaps we should cut your 27-year-old friend a little slack, because the entire concept of "closures" really is(!) ... voodoo!

By that I mean: (a) you do not, intuitively, expect it ...AND... (b) when someone takes the time to explain it to you, you certainly do not expect it to work!

Intuition tells you that "this must be nonsense... surely it must result in some kind of syntax-error or something!" How on earth(!) could you, in effect, "pull a function from 'the middle of' wherever-it's-at," such that you could [still!] actually have read/write access to the context of "wherever-it-was-at?!"

When you finally realize that such a thing is possible, then ... sure ... anyone's after-the-fact reaction would be: "whoa-a-a-a(!)... kew-el-l-l-l...(!!!)"

But there will be a "big counter-intuitive hurdle" to overcome, first. Intuition gives you plenty of utterly-plausible expectations that such a thing would be "of course, absolutely nonsensical and therefore quite impossible."

Like I said: "it's voodoo."

0
4

The simplest, shortest, most-easy-to-understand answer:

A closure is a block of code where each line can reference the same set of variables with the same variable names.

If "this" means something different than it does somewhere else, then you know it is two different closures.

0
4

A closure is simply when a function have access to its outside scope even after the scope's function has finished executing. Example:

function multiplier(n) {
    function multiply(x) {
          return n*x;
    }
    return mutliply;
}

var 10xmultiplier = multiplier(10);
var x = 10xmultiplier(5); // x= 50

we can see that even after multiplier has finished executing, the inner function multiply gets still access to the value of x which is 10 in this example.

A very common use of closures is currying (the same example above) where we spice our function progressively with parameters instead of supplying all of the arguments at once.

We can achieve this because Javascript (in addition to the prototypal OOP) allows as to program in a functional fashion where higher order functions can take other functions as arguments (fisrt class functions). functional programming in wikipedia

I highly recommend you to read this book by Kyle Simpson: 2 one part of the book series is dedicated to closures and it is called scope and closures. you don't know js: free reading on github

2

A closure is a function that has access to information from the environment it was defined in.

For some, the information is the value in the environment at the time of creation. For others, the information is the variables in the environment at the time of creation.

If the lexical environment that the closure refers to belongs to a function that has exited, then (in the case of a closure referring to the variables in the environment) those lexical variables will continue to exist for reference by the closure.

A closure can be thought of a special case of global variables -- with a private copy created just for the function.

Or it can be thought of as a method where the environment is a specific instance of an object whose properties are the variables in the environment.

The former (closure as environment) similar to the latter where the environment copy is a context variable passed to each function in the former, and the instance variables form a context variable in the latter.

So a closure is a way to call a function without having to specify the context explicitly as a parameter or as the object in a method invocation.

var closure = createclosure(varForClosure);
closure(param1);  // closure has access to whatever createclosure gave it access to,
                  // including the parameter storing varForClosure.

vs

var contextvar = varForClosure; // use a struct for storing more than one..
contextclosure(contextvar, param1);

vs

var contextobj = new contextclass(varForClosure);
contextobj->objclosure(param1);

For maintainable code, I recommend the object oriented way. However for a quick and easy set of tasks (for example creating a callback), a closure can become natural and more clear, especially in the context of lamda or anonymous functions.

1 2
3

Not the answer you're looking for? Browse other questions tagged or ask your own question.