How to use a Proxy Object In Javascript

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.

Example: The below code uses a proxy object to find out the number of times a function is called.

JavaScript
let counter = 0;
const myFunctionProxy = new Proxy(myFunction, {
    apply: function
        (target, thisArg, args) {
        counter++;
        return Reflect.apply
            (target, thisArg, args);
    }
});

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

myFunctionProxy();
myFunctionProxy();
myFunctionProxy();
myFunctionProxy();

Output
Function called: 1 times
Function called: 2 times
Function called: 3 times
Function called: 4 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....