About

Labels

slider

Recent

Navigation

Javascript Closure and nested function

Each Javascript's functions codes which performs particular functions. They may have global or local variables, on each call local variable created and in the end they are destroyed. Where as global variables are updated to new values. This is not the only case, using Javascript's nested functions you will astound to see the strange behavior of variables under certain conditions.

Local & Global Variables

Lets take a function:
function add(a) {
    var number = a + 5;
    return number;
}
add(2)     //returns 7
add(5)     // returns 10
The variable number is a local one, it is create every time function add invokes and destroys every time it ends. This function is independent of any value since there is no global variable. Now lets take an other example:
var number = 0;
function add(a) {
    number += a;
}
console.log(number); // 0
add(5);
console.log(number); // 5
add(10);
add(10);
console.log(number); // 25
Now in above example, each time function is invoked, the value changes and each value depends on other due to global scope of variable.

Nested Function

The nested functions are obviously by name indicates the function inside a function. A child function have the scope of the variables above it. Nested functions are simply those functions that are under some function, they could be more than one. Each function have access to the variables of their parents and ancestors.

That's what we call Lexical Scope (also called Static scope), in which every inner function have access to outer variables.

Lets take this function:
function first() {
    var y = 8;

    function second() {
        var x = 5;

        function third() {
            console.log(x + y)
        }
        third();
    };
    second();
};
first();  // returns 13
The explanation of above example is quite simple, every new nested function shows lexical scoping, means, each inner function owns the variable of outer ones.

 

Closure Function

Closure functions are actually the factory that creates function. A function that returns a function when invoked, and for returned function a new argument is passed with different variable. Okay now let me take it easy, in nested function, each outer function calls is inner function in itself. But in closure they are not self-invoked.


Take this function:
function first(x) {
    return function (y) {
        return x + y
    };
};
var outer = first(10);
console.log(outer(20)); // returns 30
The above example shows strange behavior because when a function first() executed then its variable x was created and when it was finished then it should be destroyed, but x didn't destroyed because first() become closure.

The function inside closure remembers the environment outside it until execution.

Cannot be used in Loops

The closures inner function remembers their environment, each loop that is created shows different environment, due to which you never get the value that is required.
Take this example, if HTML is:
<button id='a'>For a</button>
<button id='b'>For b</button>
<button id='c'>For c</button>
<span id='letter'></span>
and Javascript:
function getAlphabet() {
    var buttondata = ['a', 'b', 'c'];
    var letterspace = document.getElementById('letter');
    for (var i = 0; i < buttondata.length; i++) {
        var button = document.getElementById(buttondata[i]);
        var letter = buttondata[i];
        button.onclick = function () {
            letterspace.innerHTML = letter;
        };
    }
}
getAlphabet();
The above code always shows 'c' on any button click because function inside a loop never works. The inner function that works onclick event remembers the environment of its outer function that is getAlphabet(), but loops create 3 different environment and that's what creates problem.

If the function inside a loop is transferred outside, and called inside the loop, then each time a loop is created the function will be called individually and every time function will face a new environment.
function doMyClick(x, y, z) {
    x.onclick = function () {
        y.innerHTML = z;
    };
}
function getAlphabet() {
    var buttondata = ['a', 'b', 'c'];
    var letterspace = document.getElementById('letter');
    for (var i = 0; i < buttondata.length; i++) {
        var button = document.getElementById(buttondata[i]);
        var letter = buttondata[i];
        doMyClick(button, letterspace, letter);
    }
}
getAlphabet();
Now the above function have the same work to do and this one works correctly, its  because every loop share different environment with function.

Memory Leaks and Closures

Memory leaks refers to a memory that was allocated for the function never relocated even the function was never used. Javascript is a garbage clearing language, once the function is executed the memory is been cleared.

When a closure (function) is executed then it is not cleared after execution because it refers to the inner objects, but when browser are unable to find this reference, the memory gets clear, function destroyed and system fails.

Closure commonly have memories need to be saved till the session ends but when the memory leaks, it is destroyed and your application fail to load stuff.

Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: