Function that can be called only once in JavaScript
Last Updated :
24 Apr, 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 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.
OutputFunction 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.
OutputSquare 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.
Similar Reads
All about Functions and Scopes in JavaScript In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to - understand different types of function declarations.make better use of functions.understand how different scopes and scope chain works in JS.learn about closures and
10 min read
Call multiple JavaScript functions in onclick event Calling multiple JavaScript functions in an onclick event means executing several functions sequentially when a user clicks an element, like a button. This approach allows you to trigger multiple actions or behaviors with a single click, enhancing interactivity and functionality in web applications.
2 min read
JavaScript - What is the Purpose of Self Executing Function? The self-executing anonymous function is a special function which is invoked right after it is defined. There is no need to call this function anywhere in the script. This type of function has no name and hence it is called an anonymous function. The function has a trailing set of parentheses. The p
2 min read
How to find out how many Times a Function is Called with JavaScript ? In JavaScript, a function can be called multiple times wherever you need the same kind of functionality. You can also keep track of the function calls to find out how many times it is called in the whole code using the below approaches. Table of Content Using a Counter VariableUsing a Wrapper Functi
2 min read
What is the first class function in JavaScript ? First-Class FunctionA programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. JavaScript treats function as a fir
2 min read
How to write a function in JavaScript ? JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read