Using Named Immediately-Invoked Function Expression (IIFE) instead of comments

What are the pros and cons of utilizing Named IIFEs within JS code to describe and group related code?

I've been using this "pattern" to lend structure to my more procedural code that gets executed only in one place.


Example

(function hideStuffOnInstantiaton(){
    $('oneThing').hide().removeClass();
    $('#somethign_else').slideUp();
    $('.foo').fadeOut();
}());

I find this preferable to both:

// hide Stuff on Instantiaton
$('oneThing').hide().removeClass();
$('#somethign_else').slideUp();
$('.foo').fadeOut();

since over time the comment may get separated from the code and its not immediately obvious what line(s) the comment applies to

and to:

function hideStuffOnInstantiaton(){
    $('oneThing').hide().removeClass();
    $('#somethign_else').slideUp();
    $('.foo').fadeOut();
};

hideStuffOnInstantiaton();

becuase why separate the function and its execution if its only executed in one place?


Are there any performance, maintainability, testability, or cross-browser considerations when using this pattern? I don't believe I've seen many people use this in the wild butI feel as though it could be very useful

Answers:

Answer

why separate the function and its execution if its only executed in one place?

In that case, there's no reason to use a function (with its overhead) at all - just inline the code. And don't hide comments in function names, I'd call that a bad practise. If someone separates the comment from the code, it's his fault not yours - actually he could pack completely unrelated stuff in your IENFE as well.

While this pattern could be useful if you'd reuse the function (recursively) or need it to build a closure around something, and the named function makes stacktraces easier to debug, there are various bugs in IE. So avoid it if you don't really need it - and you do not.

If you want to express that your comment applies to a block of code, you can explicitly use a block statement for that and put your comment at its head:

{ // hide Stuff on Instantiaton
    $('oneThing').hide().removeClass();
    $('#somethign_else').slideUp();
    $('.foo').fadeOut();
}

…although that'll likely confuse your readers as much as a superfluous IEFE.

Answer

I always thought labels were cool:

hideStuffOnInstantiaton: {
  $('oneThing').hide().removeClass();
  $('#somethign_else').slideUp();
  $('.foo').fadeOut();
}

In reality, it's usually silly to do this. Instead, grouped functionality generally belongs in its own function.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.