Explain about IIFEs in JavaScript
Last Updated :
14 Mar, 2022
In this article, you will learn about JavaScript immediately invoked function expressions (IIFE). A JavaScript immediately Invoked Function Expression is a function defined as an expression and executed immediately after creation. The following shows the syntax of defining an immediately invoked function expression.
Syntax:
(function(){
// Function Body goes here
})();
IIFEs can also be used with arrow functions as shown below.
(() => {
// Function Body goes here
})()
Now that we understand what exactly is an IIFE let us try and understand some of the situations where we might need to use IIFE or Self executing functions.
Common Use Cases of IIFEs
1. Avoiding the pollution of global execution context:
An immediately invoked anonymous function may be used for the initialization code. There are variables needed to set up the environment which afterwards is no longer used and should not clutter the namespace. If you know about execution contexts in javascript then you must be aware of the concept of global scope. Any variable or function that is present in the global scope is accessible anywhere in the whole program. But sometimes we need to make sure that those variables are not accessible only to the specific parts of the program.
For Example: Consider that you are writing a library and for the functional part you are going to use variable names that are easy to understand and match with the context you need to use them for. But in a library, you would not want to force any other developer to use some different name just because you are using some variable name in the library code. You want to ensure that any existing (or new) code doesn’t accidentally interfere with other variables or override functions and methods. The way to ensure that such accidents don’t happen is to wrap all of your code inside an IIFE. This is why a lot of libraries write their source code in IIFE style.
Example:
HTML
< script >
let firstVariable = "Hello";
(() => {
// Some initiation code
let secondVariable = "Geeks";
})();
// The secondVariable will
// be discarded after the function is executed
console.log("First Variable:", firstVariable)
console.log("Second Variable:", secondVariable)
</ script >
|
Output:
First Variable: Hello
Uncaught ReferenceError: secondVariable is not defined
2. To make variables private:
IIFEs are also useful for establishing private methods for accessible functions while still exposing some properties for later use.
Example:
HTML
const User = (() => {
let userName = "Geek";
let userSecret = "Likes using IIFE";
return {
getName: () => userName,
getSecret: () => userSecret
}
})();
console.log(User.getName()); // returns "Geek"
console.log(User.getSecret()); // returns "Likes using IIFE"
console.log(User.userName); // returns undefined
|
Output: In the above example, we can easily access get methods that are returned from the functions to us but we can not access any properties that are defined inside the function. Many javascript libraries follow a similar pattern.
Geek
Likes using IIFE
undefined
Conclusion: An IIFE may not see being used a lot in regular coding projects but it is one of those things that exist and has practical use cases in the real world. You might find yourself creating projects which might be used by other developers and concepts like IIFE will definitely come in handy. You might also find a few open-source projects that extensively use concepts like closures, IIFE, function currying, composition, and many more. These concepts are the heart of functional programming and javascript so knowing such topics will definitely help you in your journey of learning JavaScript.
Similar Reads
Interesting Facts About JavaScript
JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Here are some inter
5 min read
Abstraction in JavaScript
In JavaScript, Abstraction can be defined as the concept of hiding the inner complex workings of an object and exposing only the essential features to the user. Hiding Complexity: Implementation is hidden, it shows only the necessary details.Modularity: Code is organized in a reusable form, which im
4 min read
Interesting Facts about JavaScript Functions
Let us talk about some interesting facts about JavaScript Functions that can make you an efficient programmer. Functions Are First-Class CitizensJavaScript treats functions as first-class citizens, meaning they can be: Stored in variablesPassed as arguments to other functionsReturned from other func
4 min read
Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs. [GFGTABS] JavaScript function sum(x, y) { return x + y; } console.log(sum(6, 9)); [/GFGTABS]Output1
5 min read
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
Interesting Facts about Object in JavaScript
Let's see some interesting facts about JavaScript Objects that can help you become an efficient programmer. JavaSctipt Objects internally uses Hashing that makes time complexities of operations like search, insert and delete constant or O(1) on average. It is useful for operations like counting freq
4 min read
Explain invoking function in JavaScript
In this article, we will learn about invoking the function in Javascript, along with understanding its implementation through examples. Function Invoking is a process to execute the code inside the function when some argument is passed to invoke it. You can invoke a function multiple times by declar
2 min read
Encapsulation in JavaScript
Encapsulation is a fundamental concept in object-oriented programming that refers to the practice of hiding the internal details of an object and exposing only the necessary information to the outside world. Encapsulation can be achieved using two techniques: Table of Content Using ClosuresUsing Cla
3 min read
JavaScript Function Examples
A function in JavaScript is a set of statements that perform a specific task. It takes inputs, and performs computation, and produces output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different
3 min read
Interesting Facts about JavaScript Arrays
Let us talk about some interesting facts about JavaScript Arrays that can make you an efficient programmer. Arrays are ObjectsJavaScript arrays are actually specialized objects, with indexed keys and special properties. They have a length property and are technically instances of the Array construct
3 min read