Borislav Hadzhiev
Sun Nov 14 2021·1 min read
Photo by Arnel Hasanovic
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
.