Count the Times a function has been Called in JavaScript


Borislav Hadzhiev

Last updated: Nov 14, 2021


Photo from Unsplash

Count the Times a function has been Called #

To count how many times a function has been called, declare a count variable outside of the function, setting it to 0. Inside of the body of the function reassign the variable incrementing it by 1. The count variable will store the number of function invocations.

let callCount = 0; function sum(a, b) { callCount += 1; return a + b; } sum(1, 2); console.log(callCount); // 👉️ 1 sum(1, 2); console.log(callCount); // 👉️ 2 sum(1, 2); console.log(callCount); // 👉️ 3

We declared a callCount variable using the let keyword. Had we used the const keyword, we would not be able to reassign the variable and increment its value.

We use the concept ot closures - declare the variable outside the function and access it inside the function.

This allows us to persist the state between function invocations.

Each time the function is called, we reassign the callCount variable incrementing its value by 1.

The variable is persisted in memory, so the call count is kept for as long your server stays up.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.