score:2

Accepted answer

I'm sure this has been answered elsewhere, but take a look at this example:

function fn1(inputNumber) {
    return function () {
        return Math.round(Math.random() * inputNumber)
    }
}

var bigRand = fn1(10000);
console.log(bigRand());
console.log(bigRand());

This is sorta like what the d3.randomNormal is doing. You're creating a new function via closure, mostly in this case so you don't have to repeat the same input over and over. This is effectively the same as doing the following:

function fn2(inputNumber) {
    return Math.round(Math.random() * inputNumber)
}

console.log(fn2(10000));
console.log(fn2(10000));

See How do JavaScript closures work?

score:3

Just to add the specific D3 information to the comments and to the accepted answer (which covers the question very well): d3.randomNormal() returns a function.

The API is clear:

Returns a function for generating random numbers with a normal (Gaussian) distribution. (emphasis mine)

You can also see this if you inspect the source code:

export default (function sourceRandomNormal(source) {
  function randomNormal(mu, sigma) {
      //bunch of code here...
  };
  return randomNormal;//returns the function here!
});

So, if you want to get the actual numbers, you have to call it (with parentheses):

d3.randomNormal([mu][, sigma])()
//parentheses here------------^

Let's prove it.

First, without parentheses:

var random = d3.randomNormal(10, 1);
console.log(random);
<script src="https://d3js.org/d3.v4.js"></script>

Now with the parentheses:

var random = d3.randomNormal(10, 1)();
console.log(random);
<script src="https://d3js.org/d3.v4.js"></script>


Related Query

More Query from same tag