What is the benefit of storing an IIFE in a variable?

When it comes to using IIFE in JavaScript and AngularJS, I have come across two common structures:

Structure 1:

//IIFE Immediately Invoked Function Expression
(function () {


}());

However, there is another structure where the IIFE is assigned to a variable as seen below:

Structure 2:

//IIFE Immediately Invoked Function Expression assigned to doStuff variable
var doStuff = (function () {


}());

PLEASE NOTE: This inquiry is not about what an IIFE is, but rather focuses on why one would use a return variable within an IIFE and how it relates to Angular practices.

In Angular, Structure 1 works perfectly fine. However, in many native JavaScript examples, Structure 2 is preferred. The assumption is that anything encapsulated within doStuff will be accessible and callable through it. Yet, the exact reasoning behind this distinction between the two methods remains unclear. Any help in understanding when to use each method would be greatly appreciated.

Answer №1

The rationale behind Method #2 is that the IIFE contains code that returns something, typically an object or a function. This returned value is what gets assigned. For example:

//IIFE Immediately Invoked Function Expression assigned to doStuff variable
var doStuff = (function () {
    var privateInformationForDoStuff = 0;

    function doStuff() {
        console.log(++privateInformationForDoStuff);
    }

    return doStuff;
}());

In this scenario, the variable becomes a reference to a function that increments a number each time it's called. The IIFE ensures that the privateInformationForDoStuff remains immutable and exclusive to the doStuff function.

This approach, known as the "revealing module pattern", was commonly used to construct objects with encapsulated functions and private data within the module:

var MyApp = (function() {
    var privateModuleInformation;
    var morePrivateModuleInformation;
    // ...

    function doThis() {
        // ...
    }

    function doThat() {
        // ...
    }

    function doTheOther() {
        // ...
    }

    return {
        doThis: doThis,
        doThat: doThat,
        doTheOther: doTheOther
    };
})();

In contemporary settings, utilizing an actual module is preferred, although this wasn't always a feasible option in the past.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Calculating the function using data in a Vue component

Here is a Vue component along with some data: Vue.component('receipt', { template: '#receipt-template', data: function() { return { tip: 8.50 }; }, computed: { subtotal: function( ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Tips for managing variables to display or hide in various components using Angular

In this example, there are 3 main components: The first component is A.component.ts: This is the parent component where an HTTP call is made to retrieve a response. const res = this.http.post("https://api.com/abcde", { test: true, }); res.subscribe((r ...

Building a dynamic web application using JDBC Template, AngularJS, and RESTful APIs

Seeking guidance on populating an HTML table with data from an MS SQL Database. I have configured my app.properties for the sql server and initialized my jdbcTemplate in my .java file. As a newcomer to AngularJS and jdbcTemplate, any example code or pointe ...

Find and Scroll Dropdown Menu with Bootstrap Framework

Access the jsfiddle for more information. Have a look at these questions: In my dropdown menu, I have included a search box and multiple sub-menus. However, the search box only filters the first dropdown menu and does not work with the sub-menus. How ca ...

Utilizing AngularJS to locate duplicates during input validation using ng-repeat and placing ng-form within a nested form

In an attempt to identify duplicate values entered in a textbox, I am implementing a function that checks each input value on ng-change and displays the message "SOS number has a match" when a match is found. I have tried a solution but it still sorts the ...

Understanding how the context of an Angular2 component interacts within a jQuery timepicker method

Scenario: I am developing a time picker component for Angular 2. I need to pass values from Angular 2 Components to the jQuery timepicker in order to set parameters like minTime and maxTime. Below is the code snippet: export class TimePicker{ @Input() ...

Unlimited digest loop in Angular.js caused by nested ng-repeat and filter

In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices. angular.module('abc').filter('searchFor', function(){ return ...

Guide to utilizing the THREE.OBJExporter

I've come across this post, however, when I am utilizing var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); var mesh = new THREE.Mesh( totalGeom, material ); THREE.OBJExporter.parse( mesh ); Error message shown is: Uncaught Typ ...

Load Vue dynamically to implement reCAPTCHA script

I am looking for a way to dynamically load a script like recaptcha specifically within the Register.Vue / login.Vue component. <script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer> </s ...

What is the best way to incorporate two separate events in AngularJS for a DOM element based on whether the user is accessing the site

I am currently in the process of transitioning my application from relying on numerous jQuery Widgets to incorporating AngularJS. However, I am facing difficulties in finding an optimal solution for the following issue. There is an image that should displ ...

Encountering an issue while updating information following the migration to vue-chartjs 4

I recently upgraded from vue-chartjs version 3 to version 4. I successfully migrated my LineChart component by updating the template section and removing the draw method calls. This component is utilized for two separate charts. However, when I close the ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Changing variables from a different file in node.js: a guide

Currently utilizing the discord.js library for my project. Although I can refer to it as such, I am encountering issues when trying to access certain files. For example, let's consider a file named calc.js. In this scenario, I aim to retrieve a var ...

Is it possible for React Server Side rendering to be re-rendered on the client side?

In this demonstration of isomorphic rendering found at https://github.com/DavidWells/isomorphic-react-example, the author showcases Server Side Rendering by disabling Javascript. However, if JavaScript is enabled on the frontend, does it trigger a re-rende ...

When a div tag containing PHP is empty, it should either be hidden or show specific text based on your requirements

Among the plethora of unanswered queries regarding hiding empty divs, I find myself unable to make any of the suggested solutions work. Hence, I am putting forth my own question. On my webpage, there is a specific section dedicated to showcasing various it ...

Using Javascript to Swap the Content of an Element

Recently, I've been delving into the world of javascript and have hit a roadblock. I understand how to instruct javascript to set a specific value for an ID, but now I have a new challenge: I want to create javascript code that can retrieve informati ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...