user10467090
user10467090

Reputation:

how does functions that return function work?

I expect that every time I call the function it will pass 1 as the value of seed parameter and so that value = 1 * 16807 in returned function so the result of every call will be 16807 I don't understand how this function work

 function pseudoRandom(seed) {
  let value = seed;

  return function() {
    value = value * 16807;
    return value;
  }
}

let generator = pseudoRandom(1);
alert(generator()); // 16807
alert(generator()); // 282475249
alert(generator()); // 1622650073

Upvotes: 0

Views: 95

Answers (3)

jirassimok
jirassimok

Reputation: 4253

When you set value = value * 16807, it changes the the variable in generator's closure, so each call to generator sees the value set by the last call.


Here's a simplified version of how closures work:

When you run pseudoRandom(1), you create a closure. Basically, the closure is the combination of the function returned by pseudoRandom and pseudoRandom's local variables. When you call that closure, it updates value in the closure's local variables, so future calls see a different value.

And remember that each time you call pseudoRandom, you create a new closure, with its own local variables, which lets the seeding work correctly.

I recommend reading at least the first 3 or so sections of Mozilla's page on the topic to build a better understanding of how closures work and why they are useful.

Upvotes: 2

fiveobjects
fiveobjects

Reputation: 4269

If you do not assign back to value, every time result will be the same 16807.

function pseudoRandom(seed) {
  let value = seed;

  return function() {
    // value = value * 16807;
    return value * 16807;
  }
}

Since you are modifying the value after multiplying with 16807, everytime you call generator() it will be 1 * 16807, 1 * 16807 * 16807, 1 * 16807 * 16807 * 16807 and so on.

Upvotes: 0

user11162572
user11162572

Reputation:

This is a scope issue. Change the code to return

return function() {
    return value * 16807;
}

or rename the variable in the return function from value to var myValue (for example). In your existing code you are updating value in the outer method. See closures:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Closure

Upvotes: 0

Related Questions