1

I want to ask about the return type of variables/functions. I have some sample code like this:

var randomX = d3.randomNormal(mean, 80),      
    randomY = d3.randomNormal(mean, 80),     
    points = d3.range(1000).map(function() {return [randomX(), randomY()]; });

randomX and randomY were declared as variables, why in the return line they were randomX() and randomY() with the parentheses?

I'm new to Javascript, please help me out here. Thank you in advance!

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
Huyen
  • 443
  • 4
  • 17

2 Answers2

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>
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
2

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?

Stephen
  • 5,362
  • 1
  • 22
  • 33