Search code examples
javascriptfunctioniife

More IIFE clarification in JS for a more Java mind


I still a bit confused with those Immediate Invoked Function Expression. I got the scope closure (I've read Crockford's book), but then @plalx kindly wrote me this example for another doubt i had (jsfiddle linked at the end) using IIFE. And that made a bit confused again, here how I'm thinking.

In Java one would think:

type doSome(type input){
do_stuff
return same type
};

then later

doSome(data);

so in js I could do just the same, right?

function doSome(input){
do_stuff;
return someThing;
}

and latter:

doSome(data);

or with an IIFE much more used:

var doSome = (function(data){
do_stuff;
return something
})();

and latter:

doSome(data);

Am I correct so far?

So my question is: Why use IIFE instead of the other way in this case? both codes that raised this doubt are in jsfiddle:

http://jsfiddle.net/Victornpb/PT6Xc/7/

http://jsfiddle.net/PT6Xc/8/


Solution

  • The primary difference between those two example is how often the body of the function is evaluated.

    In this example: http://jsfiddle.net/Victornpb/PT6Xc/7/, with the IIFE, the code inside is only evaluated once and the function is returned. When you run the function via

    document.body.innerHTML = deaccentuate(s);
    

    It only executes the body of the function that was returned and not the statements that come prior to it.

    In the other example: http://jsfiddle.net/PT6Xc/8/

    The entire body of the function is evaluated every time you run the deaccentuate(s) function.

    document.body.innerHTML = deaccentuate(s);
    

    So, if you have some heavy operation that you just want to perform once at runtime, or like @RobG said for private members, use the IIFE in this case.

    You can verify this by adding console.log("whatever") to the top of both examples to verify.

    http://jsfiddle.net/PT6Xc/9/ -> goes with /7/

    and

    http://jsfiddle.net/PT6Xc/10/ -> goes with /8/