1

The following code returns a function that is stateful. Just try running the output of the factory multiple times. Then re-manufacture the output and then run it again. You'll see that the output is the same, which means it's keeping track of state between runs.

But I'm not quite sure how this is possible... can somebody explain?

function mulberry32(a) {
    return function() {
      var t = a += 0x6D2B79F5;
      t = Math.imul(t ^ t >>> 15, t | 1);
      t ^= t + Math.imul(t ^ t >>> 7, t | 61);
      return ((t ^ t >>> 14) >>> 0) / 4294967296;
    }
}
user1543574
  • 873
  • 1
  • 7
  • 12
  • 1
    It's created a closure with `a` – kelsny Oct 29 '22 at 01:31
  • 2
    The return value of the function is another function, and it has a closure. It stores a reference to the passed parameter `a` to the outer function `mulberry32`, and it can be used in the inner function as if it had an inner variable. You can find more details [here](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Rodrigo Rodrigues Oct 29 '22 at 01:32
  • So are all non-object values passed into a closure also implicitly redeclared as variables inside the closure? – user1543574 Oct 29 '22 at 01:55
  • Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – kelsny Oct 29 '22 at 03:21
  • All *parameters* of the "parent" function are in the closure. – kelsny Oct 29 '22 at 03:21

0 Answers0