How to use a Wrapper Function In Javascript

We can wrap the original function inside another function that increments a counter before calling the original function. Thus finding out how many times a function is called within JavaScript program.

Example: The below code uses a wrapper function to wrap the original function to count the number of times the function has been called.

JavaScript
let counter = 0;
function myFunctionWrapper() {
    counter++;
    myFunction(counter);
}

function myFunction(count) {
    console.log("Function called:", 
        count, "times");
}

myFunctionWrapper();
myFunctionWrapper();
myFunctionWrapper();

Output
Function called: 1 times
Function called: 2 times
Function called: 3 times

How to find out how many Times a Function is Called with JavaScript ?

In JavaScript, a function can be called multiple times wherever you need the same kind of functionality. You can also keep track of the function calls to find out how many times it is called in the whole code using the below approaches.

Table of Content

  • Using a Counter Variable
  • Using a Wrapper Function
  • Using a Proxy Object

Similar Reads

Using a Counter Variable

In this approach, a counter variable is used inside the function which will be incremented by one every time the function is called and the final value of the counter variable will be equal to the function calls....

Using a Wrapper Function

We can wrap the original function inside another function that increments a counter before calling the original function. Thus finding out how many times a function is called within JavaScript program....

Using a Proxy Object

We use Proxy object to intercept calls to the original function and each time the function is called through the proxy, it logs the number of times the function has been called and thus counting the number of times the function has been called....