Question:
We've the following function greet
, we need to find out how many times this function has been called.
function greet(){
console.log("Hello World!");
}
Approach-1
Using a global variable to maintain a count of the number of times this function can be called.
let count = 0;
function greet(){
count++;
console.log("Hello World");
}
greet();
greet();
greet();
console.log(count); // 3
Problem:
This approach works fine, but there's an issue that, any other part in the codebase can manipulate the count
variable.
Approach-2
Using Function Closure
function getGreetings(){
let _count = 0;
function greet(){
_count++;
console.log("Hello, my name is Shivaansh");
}
function getGreetCount(){
console.log(_count);
}
return {
greet,
getGreetCount
}
}
let {greet, getGreetCount} = getGreetings();
getGreetCount();
greet();
greet();
greet();
getGreetCount();
greet();
greet();
getGreetCount();
O/P
Approach-3
Using IIFE
const {greet, getCount} = (function(){
let count = 0;
function getCount(){
return getCount;
}
function greet(){
count++;
console.log("Hello World");
}
return {
greet,
getCount
};
})();
greet();
greet();
greet();
console.log(getCount); // 3
With this approach, we can ensure that no other piece of code can change the count variable. Here the greet function will have a closure with the count variable so with the use of concepts like IIFE and Closures, we would be able to achieve the requirement.
Approach-4
Using Classes
class Greet {
#msg = "Hello World";
#count = 0;
printMessage() {
this.#count += 1;
console.log("Hello World");
}
getCount() {
console.log(this.#count);
}
}
const greet = new Greet();
greet.printMessage();
greet.printMessage();
greet.printMessage();
greet.getCount();
greet.printMessage();
greet.getCount();
O/P.
Here we've created a class User and 2 private properties (Private Properties in a class in Javascript are those with a # prefix attached to them).
In this way, we encapsulate the count
from the outer scope and hence achieve our target of tracking the function called time.