Skip to content
the poor coder

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

Poor Man
Published
Reading time
1 min read
On this page

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.

Text
$(() => {
  // 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.

Text
(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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC