Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Interesting Facts About JavaScript
Next article icon

Explain about IIFEs in JavaScript

Last Updated : 14 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Interesting Facts About JavaScript

H

hardikdhawan0108
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • Geeks-Premier-League-2022

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
  • 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
  • JavaScript Array Examples
    JavaScript array is used to store multiple elements in a single variable. [GFGTABS] JavaScript let a = ["HTML", "CSS", "JS"] console.log(a) [/GFGTABS]Output[ 'HTML', 'CSS', 'JS' ] Using New Keyword [GFGTABS] JavaScript // Declaring an array using Array Constructor let a
    3 min read
  • Interesting Facts About JavaScript Strings
    Let's see some interesting facts about JavaScript strings that can help you become an efficient programmer. Strings are ImmutableIn JavaScript, strings are immutable, which means once you create a string, you cannot change its characters individually. Any operation that appears to modify a string, l
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences