2

this is a function that chooses items randomly from a given array until all are taken and only then repeating

i actually copied the code from a post because i couldn't understand how the variable copy's scope works .

PS : here's the post How to efficiently randomly select array item without repeats?

thanks in advance for the help .

function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length < 1) { copy = array.slice(0); }
    var index = Math.floor(Math.random() * copy.length);
    var item = copy[index];
    copy.splice(index, 1);
    return item;
  };
}

var chooser = randomNoRepeats(['Foo', 'Bar', 'Gah']);
chooser(); // => "Bar"
chooser(); // => "Foo"
chooser(); // => "Gah"
chooser(); // => "Foo" -- only repeats once all items are exhausted.
soufiane yakoubi
  • 861
  • 11
  • 31
  • What exactly is your question? How `chooser` is able to retain `copy`? –  Dec 01 '18 at 13:09
  • calling the `randomNoRepeats`, returns you a new function that can then be called, as long as that function is alive `array` & `copy` are alive in the closure. The most interesting that can happen (after all words have past once), that if the `array` sent in changes (as it is a reference), that the function will also adapt to those changes upon the next reset ^_^ – Icepickle Dec 01 '18 at 13:10
  • The inner function is [known as a `closure`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) and it "closes" around the outer lexical variables and takes them with it when it's returned. – Andy Dec 01 '18 at 13:10

1 Answers1

2

This is an example of [closures] in JavaScript.

According to MDN, functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

In your case, chooser is a reference to an instance of the function which is returned inside the function randomNoRepeats when the latter is called. The instance of this returned function maintains a reference to its lexical environment, within which the variable copy exists. For this reason, when chooser is invoked, the variable copy remains available for use.

Read more about closures from here.

Srishti Gupta
  • 1,155
  • 1
  • 13
  • 30