Open In App

Function that can be called only once in JavaScript

Last Updated : 24 Apr, 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.

Explanation:

  • We define a function called once which is immediately invoked. This function returns the another function.
  • Inside the immediately invoked function we declare a variable executed and set its initial value to the false. This variable will keep track of whether the function has been executed before.
  • The function returned from the immediately invoked function is a closure. It has access to executed variable in its outer scope.
  • When the returned function is called, it checks if executed is false. If it is it sets executed to the true and executes the desired operation. Otherwise, it logs a message indicating that the function has already been executed and cannot be called again.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads