self-invoking function

What is a self-invoking function?

A self-invoking function is a function that automatically runs as soon as it is defined. It is also known as an Immediately Invoked Function Expression (IIFE). The function is wrapped in parentheses to make it an expression and then followed by another set of parentheses, which executes the function.

Example:


(function() {
   console.log("Hello, I am a self-invoking function");
})();

In the above example, the function is defined inside the parentheses and then immediately invoked by the second set of parentheses. This function will run as soon as it is defined and print the output on the console.

Advantages of using a self-invoking function:

  • It helps to prevent naming conflicts with other functions or variables in the global scope.
  • It helps to keep the code within a local scope, which increases security and reduces the risk of unexpected behavior.
  • It can be used to create private variables and functions that are inaccessible from outside the function.

Another way to create a self-invoking function:


!function() {
   console.log("Hello, I am a self-invoking function");
}();

In the above example, the function is defined with an exclamation mark before it. This is another way to make the JavaScript interpreter treat it as an expression and then immediately invoke it.

Overall, self-invoking functions are useful for encapsulating code within a local scope, which can help to prevent naming conflicts and increase security. They can also be used to create private variables and functions that are inaccessible from outside the function.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe