Home > Back-end >  Passing arguments to function expressions with embedded function
Passing arguments to function expressions with embedded function

Time:01-08

I'm trying to understand the argument passing mechanism for function expressions that have functions within them, requiring argument passing. I think I know what is happening, but not sure.

I have the following code fragment:

makePassword(password) {
   return function guess(passwordGuess) {
      return (passwordGuess === password);
   }
}

var tryGuess = makePassword("secret");
console.log("Guessing 'nope': "   tryGuess("nope"));
console.log("Guessing 'secret': "   tryGuess("secret"));

tryGuess gets the function reference of makePassword("secret"). I understand that. I'm trying to wrap my head around why tryGuess("nope") passes nope to the inner function guess and not to makePassword? I'm think that, in this example, password is set before the function reference is passed to tryGuess?

If that is so, how would I pass the parameters to password and passwordGuess in tryGuess if I had assigned tryGuess like this:

var tryGuess = makePassword();

There is an assumption about nested functions and parameter passing that I must be missing.

CodePudding user response:

makePassword takes the password argument and returns a function that uses that value. makePassword('secret') returns a function that effectively is:

function guess(passwordGuess) {
    return (passwordGuess === 'secret');
}

And calling var tryGuess = makePassword("secret"); assigns it to tryGuess.

From this point onwards, it's a function like any other function. Calling tryGuess('nope') will return false (because 'nope' === 'secret' is false), while calling tryGuess('secret') will return true.

CodePudding user response:

var tryGuess = makePassword("secret");

is not returning a reference to the function makePassword but it calls the function and assigns tryGuess the return value of the function makePassword which in this case is the reference to guess function. The value of password is fixed when you ran makePassword("secret") as secret

  • Related