1

It is a simple question, why are var1 and var2 undefined .

I was trying to learn closures in javascript and added a parameter but not sure why it is undefined.

    var closureFunction = function(var1,var2){  
        var privateVar = var1+var2;     

        console.log("Sum of "+ var1 +" and "+ var2+"");     
        return function(){return privateVar;} 
    }();


    console.log(closureFunction(2,3));
3
  • You pass none in. Commented Oct 17, 2016 at 11:40
  • How can I pass parameters ? Commented Oct 17, 2016 at 11:43
  • Don't immediately invoke it. Commented Oct 17, 2016 at 11:45

2 Answers 2

4

When you use brackets () after a function, it gets executed immediately. And in this case you have not passed any parameter there.

It can go two ways.

   var closureFunction = function(var1,var2){  
        var privateVar = var1+var2;     

        console.log("Sum of "+ var1 +" and "+ var2+"");     
        return function(){return privateVar;} 
    }(2,3);  //prints 'Sum of 2 and 3'

    console.log(closureFunction()); //prints '5'

Or you can pass parameters in steps

var closureFunction = function(var1){  

    return function(var2 ){
         console.log("Sum of "+ var1 +" and "+ var2+"");
         return var1 + var2;
     } 
}(2);  //just return a 'closure' function

console.log(closureFunction(3)); //prints 'Sum of 2 and 3 5'

or you can execute it later.

var closureFunction = function(var1){  

    return function(var2 ){
         console.log("Sum of "+ var1 +" and "+ var2+"");
         return var1 + var2;
     } 
};  

var x = closureFunction(2);  //return a 'closure' function
console.log(x(3)); //prints 'Sum of 2 and 3 5'
Sign up to request clarification or add additional context in comments.

Comments

1

You have to call the closure once its available.

var closureFunction = function(var1, var2) {
  var privateVar = var1 + var2;

  console.log("Sum of " + var1 + " and " + var2 + "");
  return function() {
    return privateVar;
  }
};


console.log(closureFunction(2, 3)());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.