Search code examples
javascriptangularjshottowel

HotTowel Angular and Immediately-Invoked Function Expression (IIFE)


Starting to look at HotTowel templates for AngularJS and all those "why" questions pops into my mind. I have cleared some of them, but couldn't clear this. I.e. the use of "Immediately-Invoked Function Expression (IIFE)" for controllers. Below is the code from "shell.js"

    (function () { 
        'use strict';

        var controllerId = 'shell';
        angular.module('app').controller(controllerId,
            ['$rootScope', 'common', 'config', shell]);

        function shell($rootScope, common, config) {
            var vm = this;
      //rest of the code omitted 

I can't figure out why IIFE is used here. One reason could be if we don't use IIFE, then

var controllerId = "shell"

will have global scope (is that correct?). I have tried to remove the IIFE style and obviously it is working with out any issue. I went through AngularJS Style Guide but couldn't find an explanation there. Can someone please explain what benefits we get by following this approach?

P.S. If you think this is not the correct place for this question please point me to the correct place.


Solution

  • As you said it's to prevent adding to global scope. In you above code controllerId and the shell function will be added to global scope if an IIFE is not used.

    There is an explanation in John Papa's style guide:

    Why?: An IIFE removes variables from the global scope. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions.

    Why?: When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE protects you against both of these by providing variable scope for each file.