Saturday, February 27, 2016

Closure in JavaScript


 Here are some questions that I solved during one of the online courses. Hope they will help you to understand closure in JavaScript


//Write a function, `nonsense` that takes an input `string`.
//This function contains another function, `blab` which alerts `string`
//and is immediately called inside the function `nonsense`.
// `blab` should look like this inside of the `nonsense` function:



    var nonsense(string){
         var function blab(){
             alert(string);
         };

         blab();
    }



//In your function, `nonsense`,
//change the immediate call to a setTimeout so that the call to `blab` comes after 2 seconds.
//The `blab` function itself should stay the same as before.

    var nonsense(string){
         var function blab(){
             alert(string);
         };
        
         setTimeout(blab(),2000);
    }


//Now, instead of calling `blab` inside of `nonsense`, return `blab` (without invoking it).
//Call `nonsense` with some string and store the returned value (the `blab` function) in a variable called `blabLater`.
//Call `nonsense` again with a different string and store the returned value in a variable called `blabAgainLater`.


     var nonsense(string){
         var function blab(){
             alert(string);
         };
        
         return blab();
    }

    var blabLater=nonsense('My name is Saif');
    var blabAgainLater=nonsense('My name is Khan');


//Write a function with a closure. The first function should only take one argument,
//someone's first name, and the inner function should take one more argument, someone's last name.
//The inner function should console.log both the first name and the last name.

    
    var lastName= function(firstName){
       
        var innerFunction=function(lastName){
            console.log(firstName + ' ' + lastName);
        };

        return innerFunction;
    } 
      

//Create a `storyWriter` function that returns an object with two methods. One method,
//`addWords` adds a word to your story and returns the story while the other one, `erase`,
//resets the story back to an empty string. Here is an implementation:


    var storyWriter= function(){
        var story='';
        return{
            addWords: function(word) {
              story+=' '+ word;
              },
            erase:function(){
                story='';
            },
            logStory:function(){
                console.log(story);
            }
        };
    };


I ran into interesting example that was given by Kyle Simpson about misunderstanding in
 In the first snapshot, We expected the console to print 1, 2, 3 ,4 ,5 but it printed 6,6,6,6,6 instead of that. 
To solve that issue, Kyle suggested to use iffy so that each function will have its own 'i'. 

for (var i=1;i<=5;i++){
    setTimeout(function(){
    console.log("i: "+i);

    },i*1000);
}

for (var i=1;i<=5;i++){
    (function(i){
        setTimeout(function(){
        console.log("i: "+i);

        },i*1000);
    })(i);
}