Computer Science

Javascript Immediately Invoked Function Expressions

Javascript Immediately Invoked Function Expressions (IIFE) are functions that are executed as soon as they are defined. They are used to create a private scope for variables and functions, preventing them from being accessed outside of the function. IIFE's are commonly used in Javascript libraries and frameworks to avoid naming conflicts with other code.

Written by Perlego with AI-assistance

5 Key excerpts on "Javascript Immediately Invoked Function Expressions"

  • Book cover image for: JavaScript for Sound Artists
    eBook - ePub

    JavaScript for Sound Artists

    Learn to Code with the Web Audio API

    • William Turner, Steve Leonard(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    immediately invoked function expression or IIFE (pronounced “iffy”). This method is useful if you want to briefly encapsulate and run a block of code only once. The syntax looks like this:
    //______________________BEGIN IIFE (function run() { return "data"; }()); //______________________END IIFE
    To view the output, you can wrap it in console.log() .
    console.log( //______________________BEGIN IIFE (function run() { return "data"; }()) //______________________END IIFE );
    The first thing to notice is that the function is wrapped in parentheses. This is optional, but is considered best practice because it helps differentiate the construct syntactically from non-IIFE functions.
    (function run() { return "data"; }());
    The next thing to notice is the parentheses toward the end of the function before the closing, encapsulating parenthesis. This syntax is what invokes the function.
    (function run() { return "data"; }());
    To add parameters and arguments, you put parameters in the first set of parentheses and arguments in the second set of parentheses. (function add(a, b) { //_____ parameters return a + b; }(2, 3)); //___________________arguments

    Closures

    One of the most difficult aspects of the JavaScript language for new programmers to grasp is closures. Understanding closures will ultimately allow you to write cleaner code while giving you a powerful tool to solve a host of problems you will inevitably run into. Understanding the concept of closure can be a bit difficult at first. But in the long term, the benefits are worth the time investment.

    What Is a Closure?

    A closure is an inner function that has access to the scope of its outer environment even after that outer environment has returned. To understand what this means, you must first solidify your understanding of scope. The following example demonstrates how a function has access to its local scope, the global scope, and its local arguments.
  • Book cover image for: Mastering JavaScript
    No longer available |Learn more
    () after the function expression to execute it immediately. So the complete pattern looks as follows:
    (function foo(){ /* code */ })();
    This pattern is so common that it has a name: IIFE , which stands for Immediately Invoked Function Expression . Several programmers omit the function name when they use IIFE. As the primary use of IIFE is to introduce function-level scope, naming the function is not really required. We can write the earlier example as follows:
    var a = 1; (function() { var a = 2; console.log( a ); // 2 })(); console.log( a ); // 1
    Here we are creating an anonymous function as IIFE. While this is identical to the earlier named IIFE, there are a few drawbacks of using anonymous IIFEs:
    • As you can't see the function name in the stack traces, debugging such code is very difficult
    • You cannot use recursion on anonymous functions (as we discussed earlier)
    • Overusing anonymous IIFEs sometimes results in unreadable code
    Douglas Crockford and a few other experts recommend a slight variation of IIFE: (function(){ /* code */ }()); Both these IIFE forms are popular and you will see a lot of code using both these variations. You can pass parameters to IIFEs. The following example shows you how to pass parameters to IIFEs:
  • Book cover image for: JavaScript: Novice to Ninja
    • Darren Jones(Author)
    • 2017(Publication Date)
    • SitePoint
      (Publisher)
    These are two powerful methods, as they allow generalized functions to be written that are not tied to specific objects by being methods of that object. This gives flexibility over how the functions can be used.

    Custom Properties

    There is nothing to stop you adding your own properties to functions in the same way that you can add properties to any object in JavaScript. For example, you could add a description property to a function that describes what it does:
    square.description = 'Squares a number that is provided as an argument' << 'Squares a number that is provided as an argument'
    Memoization
    A useful feature of this is that it provides result caching, or memoization .
    If a function takes some time to compute a return value, we can save the result in a cache property. Then if the same argument is used again later, we can return the value from the cache, rather than having to compute the result again. For example, say squaring a number was an expensive computational operation that took a long time. We could rewrite the square() function so it saved each result in a cache object that is a property of the function:
    function square(x){ square.cache = square.cache || {}; if (!square.cache[x]) { square.cache[x] = x*x; } return square.cache[x] }
    If we try calling the function a few times, we can see that the cache object stores the results:
    square(3); << 9 square(-11); << 121 square.cache; << {"3": 9, "-11": 121}

    Immediately Invoked Function Expressions

    An Immediately Invoked Function Expression – or IIFE – (pronounced 'iffy') is an anonymous function that, as the name suggests, is invoked as soon as it’s defined. This is easily achieved by placing parentheses at the end of the function definition (remember we use parentheses to invoke a function). The function also has to be made into an expression, which is done by placing the whole declaration inside parentheses, as in this example:
    (function(){ const temp = 'World'; console.log(`Hello ${temp}`); })(); << 'Hello World' IIFEs are a useful way of performing a task while keeping any variables wrapped up within the scope of the function. This means the global namespace is not polluted with lots of variable names.
  • Book cover image for: JavaScript for Sound Artists
    eBook - PDF

    JavaScript for Sound Artists

    Learn to Code with the Web Audio API

    • William Turner, Steve Leonard(Authors)
    • 2017(Publication Date)
    • Routledge
      (Publisher)
    5. Functions 48 in the code In this case, the function is run before the initialization that defines the function occurs The lesson here is that when you use function expressions, you must declare functions before you invoke them This is good practice with all your functions as it makes your code less confusing and more readable multFreq(200, 2); //___ error! “multFreq is not a function”. var multFreq = function(input, val) { return input * val } Anonymous Functions Anonymous functions are functions that do not have a name Technically, the function in the following code is an anonymous function because the variable it is assigned to is not the function name It is the container name for an anony- mous function var multFreq = function(input, val) { return input * val; } To give this function a name, you do it like this: var multFreq = function nameGoesHere(input, val) { return input * val; } Note, however, that to invoke the function, you use the variable name that it is assigned to multFreq(100,2); // 200 In JavaScript, it is possible to create a function that is invoked immediately after it is declared This type of function is called an immediately invoked func- tion expression or IIFE (pronounced “iffy”) This method is useful if you want to briefly encapsulate and run a block of code only once The syntax looks like this: //______________________BEGIN IIFE (function run() { return "data"; }()); //______________________END IIFE To view the output, you can wrap it in console.log()  console.log( //______________________BEGIN IIFE (function run() { return "data"; }()); //______________________END IIFE );
  • Book cover image for: TypeScript: Modern JavaScript Development
    • Remo H. Jansen, Vilic Vane, Ivo Gabe de Wolff(Authors)
    • 2016(Publication Date)
    • Packt Publishing
      (Publisher)
    _i , we will not get any errors because TypeScript will not generate runtime private properties for us. Sometimes we will need to write our functions in such a way that some properties are private at runtime, for example, if we release a library that will be used by JavaScript developers. We can use IIFE to simultaneously allow public access to methods while retaining privacy for variables defined within the function:
    var Counter = (function () { var _i : number = 0; function Counter() { } Counter.prototype.get = function () { return _i; }; Counter.prototype.set = function (val : number) { _i = val; }; Counter.prototype.increment = function () { _i++; }; return Counter; })();
    In the preceding example, everything is almost identical to TypeScript's generated JavaScript, except that the variable _i before was an attribute of the Counter class, and now it is an object in the Counter closure.

    Note

    Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure remembers the environment (variables in the scope) in which it was created. We will discover more about closures in Chapter 5 , Runtime .
    If we run the generated output in a browser and try to invoke the _i property directly, we will notice that the property is now private at runtime:
    var counter = new Counter(); console.log(counter.get()); // 0 counter.set(2); console.log(counter.get()); // 2 counter.increment(); console.log(counter.get()); // 3 console.log(counter._i); // undefined

    Note

    In some cases, we will need to have really precise control over scope and closures, and our code will end up looking much more like JavaScript. Just remember that, as long as we write our application components (classes, modules, and so on) to be consumed by other TypeScript components, we will rarely have to worry about implementing runtime private properties. We will look in depth at the TypeScript runtime in Chapter 5 , Runtime
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.