0

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Russ Urquhart
  • 327
  • 1
  • 4
  • 19
  • 1
    `tryGuess` will be the return value of `makePassword` which will be `guess`. So calling `tryGuess` will run that inner function, which has access to both `password` and `passwordGuess` due to the closure. – evolutionxbox Jan 07 '23 at 22:00
  • Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – evolutionxbox Jan 07 '23 at 22:00
  • if you call makePassword() just like that, password will be undefind, and it will compare any next chack you make with that – codingStarter Jan 07 '23 at 22:02
  • Ok, this makes sense now!! – Russ Urquhart Jan 07 '23 at 22:52

2 Answers2

2

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

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

Yatin Gupta
  • 653
  • 5
  • 12