Search code examples
javascriptanonymous-functioniifefunction-expression

JavaScript anonymous function expression vs IIFE


Encountered some code that's using IIFEs in an expression rather than just a normal function.

var custom_type = (function() {
    return $('#myDiv').attr('custom_type');
})();

Normally I would write this as something like:

var custom_type = function() {
    return $('#myDiv').attr('custom_type');
};

What's the reason for the IIFE? The only thing I can think of is that the IIFE might assign the custom_type variable only once at the beginning whereas the second might continue to check for the updated type every time the variable is referenced.


Solution

  • In this example, you can dispense with the function altogether and just do:

    var custom_type = $('#myDiv').attr('custom_type');
    

    However in general you can use an IIFE for more complex "just-in-time" computation of variable assignments - I like to use them if I need to iterate over something, so I can have i without polluting the current scope.

    In your second example, though, the result is completely different - you will need to call the function custom_type() to get the current value, whereas the first piece of code will get its value once, and the variable will hold that value.