Javascript scope and closure

Today let me try to explain some of the strange behavior of Javascript (compared to Python).

Variable scope

Different than in Python, in Javascript variables are accessable from lower structure from where it’s declared.

Consider:

function foo(){
    var a = 1;
    function bar(){
        var b = 2;
        console.log(a);
    }
    bar(); //returns a=1
    console.log(b); //b is not defined. Because b is not available to upper scope
}

Closure

According to “You don’t know JS” series, Closure is:

You can think of closure as a way to "remember" and continue to access a
function's scope (its variables) even once the function has finished running.

Consider:

function makeAdder(x){

    //add(y) is a function, what it does is to add x (recieved from caller) to 
    //its argument 'y'
    function add(y){
        return y+x;
    };

    //makeAdder(x) returns a FUNCTION, namely, add(y).
    //Add what? It's determined by the argument x when makeAdder is called.
    //See below
    return add;
}

// To make a function, add 1 to its argument.
var plusOne = makeAdder(1);

console.log( plusOne(8) ); //returns 9

It’s more or less about functional programming, and the example does make sense: It provide a way to “produce” function. For example if next time I want to “produce” a function, whose function is to add 5 to its argument, I can call:

var plusFive = makeAdder(5);

Keep learning! And that’s it for today!

Written on June 2, 2016