Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 838
diplosaurus Avatar asked Apr 09 '14 22:04

diplosaurus


3 Answers

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.

like image 132
Niet the Dark Absol Avatar answered Oct 08 '22 10:10

Niet the Dark Absol


The IIFE will actually run (immediately-invoked function expression), so the variable will be set to its response.

Here's a JSFiddle to demonstrate this, watch your JS console for the output: http://jsfiddle.net/Y4JmT/1/

Code Here:

var custom_type = (function() {
    return 'foo';
})();

var custom_type2 = function() {
    return 'bar';
};

console.log('iife = ' + custom_type);
console.log('non-iife = ' + custom_type2);

In your JS console you'll see something similar to:

iife = foo 

and

non-iife = function () {
    return 'bar';
} 
like image 27
Jasper Avatar answered Oct 08 '22 09:10

Jasper


The first one of yours (IIFE) executes the function and store its result, the seconds stores function as definition.

(function(x) {
    return x * 2;
})(5);

You are making a call like to normal funciton: func(arg1, arg2), but instead of function name you pass whole function definition, so the above would return 10 like:

function multiply(x) {
    return x * 2;
}

multiply(5);

They mean the same thing, you are making calls. Unlikely the first, second is definition plus a call.

like image 2
Rolice Avatar answered Oct 08 '22 10:10

Rolice