Self Invoking Function ($()) That Can Be Reused

Self Invoking Function ($()) That Can Be Reused

If you are a JavaScript developer, you might have heard about self-invoking functions. Self-invoking functions are functions that are called automatically when they are defined. They are also known as Immediately Invoked Function Expressions (IIFE).

One of the most common use cases of self-invoking functions is to create a private scope for your code. When you define a variable inside a self-invoking function, it is not accessible outside of that function. This helps to prevent naming conflicts with other scripts.

The Syntax of Self Invoking Function

The syntax of self-invoking function is simple. You just need to define a function and invoke it immediately using the parentheses operator.

$(() => {
  // Your code here
})();

The above code defines a self-invoking function that runs when the document is ready. You can replace the $() with any selector to run the function on specific DOM elements.

Reusing Self Invoking Functions

The beauty of self-invoking functions is that they can be reused multiple times. You can define a function once and call it wherever you need it. This helps to reduce code duplication and makes your code more modular.

(function myFunction() {
  // Your code here
})();

(function anotherFunction() {
  // Your code here
})();

The above code defines two self-invoking functions that can be called anywhere on the page. You just need to call them using their function names.

Conclusion

Self-invoking functions are a powerful tool for JavaScript developers. They help to create private scopes, reduce code duplication, and make your code more modular. With a little bit of practice, you can start using self-invoking functions in your projects and see the benefits for yourself.

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