0

I have been recently learning JavaScript and came across this piece of code.

function sayIntro(name,age){

var address = "TX";

return function(name,age,address){
console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};

}

sayIntro("john",27)();

As per my understanding, the results are undefined because within the scope of returning function previous variables are not available. Still how do I get the output as bellow?

I am john
I am 27
from TX 
2
  • You're simply shadowing the variable names. Rename them to something else in the inner function and it works fine. Commented Oct 13, 2017 at 10:44
  • Variables from sayIntro are still in scope within the anonymous function – that’s not the problem. The problem is that there’s a whole new set of parameters with the same names that aren’t being passed values, and because they have the same names they hide the other variables. return function () { to fix. Commented Oct 13, 2017 at 10:48

1 Answer 1

1

The parameters from the inner function shadows the outer function parameters and the variable. You can just access the variables inside the inner function, because when it tries to find a variable, it goes from its scope, if not found goes to the outer scope, in this case the outer function's scope and finds them.

But if you declare parameters in the inner function, they are founded and because you does not pass a value for them, their values are undefined. So you get undefined.

Or remove them from the inner function

return function() {
   console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};

or just remove the address and call the inner function and pass to it the parameters.

return function(name, age) {
   console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};

...

sayIntro()("john",27);

Example

function sayIntro(name,age){

   var address = "TX";

   return function(){
      console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
   };

}

sayIntro("john",27)();

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the detailed explanation, I understand what was happening, so according to the second way you mentioned, when invoking the first pair of brackets passes no parameters to the outer function and second pair of brackets passes name and age to the inner function right?
First call returns the inner and second call passes params to it
Yes, closure - the combinatoin of the function and the environment where that function was declared

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.