Count the Times a function has been Called in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 14 20211 min read

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.

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee