0

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
4

3 Answers 3

2

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.

0

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

0

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.

Your Answer

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