0

I know this question has a quick one line answer, but I can't wrap my head around how to make this arrow function self contained, using properties properly. It is just a function that counts how many times it has been called. Some help would be appreciated.

const countTimes = () => {
    countTimes.count = countTimes.count + 1;
    return countTimes.count;
};
countTimes.count = 0;
  • What do you mean by "self contained"? – Pointy Feb 28 '19 at 14:03
  • by self contained, I mean that the function shouldn't rely on anything outside of its body – Gregory Siot Feb 28 '19 at 14:04
  • Does it need to be an arrow function? Because those inherit the surrounding context rather than creating their own. – Heretic Monkey Feb 28 '19 at 14:06
  • @HereticMonkey — If it had a different context and stored the data on that, then it would still be storing data outside the function body, so that wouldn't help. – Quentin Feb 28 '19 at 14:07
  • @Quentin Yeah I just noticed hence why I removed my comment – Adrian Feb 28 '19 at 14:07
  • Possible duplicate of [How do I find out how many times a function is called with javascript/jquery?](https://stackoverflow.com/questions/8517562/how-do-i-find-out-how-many-times-a-function-is-called-with-javascript-jquery) – Mehrad Feb 28 '19 at 14:07
  • @Quentin Depends on the OP's definition of "function body", as your comment on Andy's answer demonstrates. – Heretic Monkey Feb 28 '19 at 14:11

2 Answers2

3

The function body exists only during execution and starts from fresh each time the function is called. If you want to persist data between invocations of the function then you must store that data outside the function body (be it as a property on an object, a closed-over variable, a global or whatever).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Maybe use a closure:

function countTimes() {
  let count = 0;
  return function() {
    return ++count;
  }
};

const count = countTimes();

console.log(count());
console.log(count());
console.log(count());
Andy
  • 61,948
  • 13
  • 68
  • 95
  • The `count` variable is still stored outside the body of the function (well, the function that actually gets called when you call `count`). – Quentin Feb 28 '19 at 14:07
  • I suppose it depends which function shouldn't violate the "function shouldn't rely on anything outside of its body" rule. – Andy Feb 28 '19 at 14:15