Open In App

Function that can be called only once in JavaScript

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 that returns a once function
function createOnceFunction() {
    let hasBeenCalled = false;
 
    return function () {
        if (!hasBeenCalled) {
            console.log('Function called!');
            hasBeenCalled = true;
        } else {
            console.log('Function can only be called once.');
        }
    };
}
 
// Create the once function
const callOnce = createOnceFunction();
 
// Call the function the first time
callOnce(); // Output: Function called!
 
// Call the function again
callOnce(); // Output: Function can only be called once.


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 that returns a once function
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.');
        }
    };
}
 
// Create the once function for calculating the square
const calculateSquareOnce = createOnceFunction();
 
// Call the function with input 5 (first call)
calculateSquareOnce(5); // Output: Square of 5: 25
 
// Call the function again (subsequent calls)
calculateSquareOnce(8); // Output: Function can only be called once.


Output

Square of 5: 25
Function can only be called once.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads