Super Computer.

JavaScript Closures

Closures in JavaScript

What are JavaScript closures?

A closure is a kind of object that combines two things:

  1. a function
  2. that function’s environment

The function’s environment consists of any local variables that were in-scope at the time that the closure was created.

How do you create a closure in JavaScript?

Simply, in JavaScript, if you use the function keyword inside another function, you are creating a closure.

As such, local variables remain accessible after returning from the function you called; the inner function still has access to the outer function’s variables even after the outer function has returned.

Here’s an example of a simple closure in JavaScript:

<script>

var sayHello = function alertGreeting(name){
    var greeting = "Hello";
    function displayName() {
        alert(greeting + " " + name);
    };
    displayName();
};

sayHello("Chris");

</script>

Sample the code on JS Fiddle

There’s a lot, lot more on closures but I just wanted to get the basic definition down. If you want to go deeper, here are a few resources to get you started.