Creating a JavaScript function that tracks its call count

I’m trying to make a function that knows how many times it’s been called. Here’s what I want it to do:

console.log(countCalls()()); // should show '2'
console.log(countCalls()()()); // should show '3'
console.log(countCalls()()()()); // should show '4'

How can I write countCalls() to do this? I tried something like this:

countCalls.count = 1;
function countCalls() {
  countCalls.count++;
  return function() {
    return countCalls.count;
  };
}

But it doesn’t work right when I do:

console.log(countCalls()()()());

Can someone help me figure out what I’m doing wrong? I’m pretty new to this and I’m not sure how to make it work correctly.

hey, i think u need a closure to avoid count reset. try:

function countCalls() {
let count = 1;
return () => ++count;
}

this way, repeated calls incr count correctly.

Your approach is close, but the issue lies in how the count is being incremented and returned. Here’s a solution that should work:

function countCalls() {
  let count = 1;
  return function() {
    return function() {
      return ++count;
    };
  };
}

This implementation uses nested closures to maintain the count across multiple calls. The outer function creates a closure over count, the middle function preserves this closure, and the innermost function increments and returns the count.

This structure allows for the chained calls you’re looking for while correctly tracking the number of invocations. It’s a bit more complex than a simple counter, but it provides the functionality you need for this specific use case.

Test it out and see if it meets your requirements. Let me know if you need any further explanation on how this works under the hood.

I faced a similar challenge when building a custom analytics tool. The key is to use closure, as mentioned, but with a slight tweak. Here’s what worked for me:

const countCalls = (() => {
  let count = 1;
  return () => () => count++;
})();

This creates an immediately invoked function expression (IIFE) that encapsulates the count variable. Each call to countCalls() returns a new function that, when invoked, increments and returns the count.

It’s a bit tricky at first, but once you grasp the concept, it becomes a powerful pattern for maintaining state across function calls. Just remember, the outer function creates the closure, the middle one preserves it, and the innermost one updates the count.

Give it a try and let me know if you need any clarification!