I am tasked with creating an arrow function called countTimesCalled that takes no parameters. It has to return the number of times it has been called each time it is invoked. The function should be entirely self-contained.
This is what I have so far, I'd like it to be something along these lines but I can't figure out how to initialize the counter. Any help would be greatly appreciated!
countTimesCalled = () => {
counter = 0;
if (counter == undefined){
counter = 1;
return(this.counter)
} else {
return(this.counter++)
}
You could attach a property to the function itself that keeps track of the count:
const countTimesCalled = () => {
if (!countTimesCalled.count) {
countTimesCalled.count = 0;
}
return ++countTimesCalled.count;
};
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());