1

I've come across a very interesting - yet confusing - code snippet and had hard time to understand what exactly does it return it.

// Create a data point generator.
var getDataPoint = (function() {
  var _x = -1;
  var _max = _data.length;

  return function() {
    _x = (_x + 1) % _max;
    return {
      x: Date.now(),
      y: _data[_x]
    };
  };
})();

var heartRate = 60; // bpm
var interval = 60 * 1000 / (_data.length * heartRate);

// Generate a new data point based on the heart rate.
setInterval(function() {
  $('.jke-ecgChart').ecgChart('addDataPoint', getDataPoint());
}, interval);

Now I have a very basic understanding of closures and how they work, for example, they're scope within outer functions.

But what confused me more is this specific line:

$('.jke-ecgChart').ecgChart('addDataPoint', getDataPoint());

What will getDataPoint() return? A function or {x, y}?

What if I wanted to return {x, y} instead of the function?

Thanks

3
  • 1
    It returns a function Commented Feb 4, 2018 at 18:40
  • 1
    Why do you think return function() {...}; wouldn't return a function? If you want to return a value, just return the value. Commented Feb 4, 2018 at 18:41
  • I still do believe it should return function, but in the console for some reason, it returns an array of scopes. @SLaks Commented Feb 4, 2018 at 18:42

1 Answer 1

2

Here getDataPoint is resolved to be a value returned by an immediately invoked function in the first line. hence getDataPoint stores reference to a function returned at line 4. hence, when you call it at $('.jke-ecgChart').ecgChart('addDataPoint', getDataPoint()), the function at line 4 will be called, which will return {x, y}, not a function. You can see the similar example in the code below, I have used some constants in it, just to be able to log the output.

// Create a data point generator.
var getDataPoint = (function() {
  var _x = -1;
  var _max = 6;

  return function() {
    _x = (_x + 1) % _max;
    return {
      x: Date.now(),
      y: _x
    };
  };
})();

var heartRate = 60; // bpm
var interval = 1000;

// Generate a new data point based on the heart rate.
setInterval(function() {
  console.log(getDataPoint());
}, interval);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that makes more sense. Appreciate it :)

Your Answer

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