Function that can be called only once in JavaScript
Last Updated :
08 Jan, 2024
In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer boundary and is created automatically whenever a function is created.
Lexical Scoping:
A function scope’s ability to access variables from the parent scope is known as lexical scope. We refer to the parent function’s lexical binding of the child function as “lexically binding.”
Example 1: In this example, the createOnceFunction
function returns a closure. The closure contains a hasBeenCalled
variable, ensuring that the enclosed function logic is executed only once. When callOnce
is invoked for the first time, it logs “Function called!”. On subsequent calls, it logs “Function can only be called once.” This pattern allows you to control the execution of certain operations to ensure they happen only once in the application’s lifecycle.
Javascript
function createOnceFunction() {
let hasBeenCalled = false ;
return function () {
if (!hasBeenCalled) {
console.log( 'Function called!' );
hasBeenCalled = true ;
} else {
console.log( 'Function can only be called once.' );
}
};
}
const callOnce = createOnceFunction();
callOnce();
callOnce();
|
Output
Function called!
Function can only be called once.
Example 2: In this example, the createOnceFunction
returns a closure that calculates the square of a number on its first invocation. The calculateSquareOnce
function is then used to calculate the square of 5. On subsequent calls, it logs a message indicating that the function can only be called once. This pattern ensures that the expensive square calculation is performed only when necessary.
Javascript
function createOnceFunction() {
let hasBeenCalled = false ;
return function (input) {
if (!hasBeenCalled) {
const result = input * input;
console.log(`Square of ${input}: ${result}`);
hasBeenCalled = true ;
} else {
console.log( 'Function can only be called once.' );
}
};
}
const calculateSquareOnce = createOnceFunction();
calculateSquareOnce(5);
calculateSquareOnce(8);
|
Output
Square of 5: 25
Function can only be called once.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...