Javascript Closures
Elango Sundar

Elango Sundar @10secondsofcode

About: Fullstack developer in ReactJs, Symfony4, NodeJs, Javascript, html5, css3, php and AWS.

Location:
India
Joined:
Oct 26, 2018

Javascript Closures

Publish Date: Dec 24 '18
7 2

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains:
- it has access to its own scope (variables defined between its curly brackets).
- it has access to the outer function’s variables.
- it has access to the global variables.

Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.

Inner function can access variables and parameters of an outer function.
It is useful in hiding implementation detail in JavaScript.

function showName (firstName, lastName) {
    var nameIntro = "Your name is ";
    // this inner function has access to the outer function's variables, including             the parameter
    function makeFullName () {       
        return nameIntro + firstName + " " + lastName;   
    }

    return makeFullName ();
}

showName ("Michael", "Jackson"); // Your name is Michael Jackson
function OuterFunction() {

    var outerVariable = 100;

    function InnerFunction() {
        alert(outerVariable);
    }

    return InnerFunction;
}
var innerFunc = OuterFunction();

innerFunc(); // 100


function Counter() {
    var counter = 0;

    function IncreaseCounter() {
        return counter += 1;
    };

    return IncreaseCounter;
}

var counter = Counter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
alert(counter()); // 4

In the above example, return InnerFunction; returns InnerFunction from OuterFunction when you call OuterFunction(). A variable innerFunc reference the InnerFunction() only, not the OuterFunction(). So now, when you call innerFunc(), it can still access outerVariable which is declared in OuterFunction(). This is called Closure.

Repo: https://github.com/10secondsofcode/10secondsofcode

javascript, #10secondsofcode, #closures

Comments 2 total

Add comment