Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 660
Zach Lysobey Avatar asked Mar 20 '13 17:03

Zach Lysobey


People also ask

What is IIFE immediately invoked function expression in JS?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.

What is true regarding immediately invoked function expressions IIFE )?

An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

Which statement represents the starting code converted to an immediately invoked function expression IIFE )?

(function () { })(); This is called IIFE (Immediately Invoked Function Expression).

Why would you use an IIFE?

Immediately-Invoked Function Expressions (IIFE), pronounced "iffy", are a common JavaScript pattern that executes a function instantly after it's defined. Developers primarily use this pattern to ensure variables are only accessible within the scope of the defined function.


1 Answers

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.

like image 151
Stephen Avatar answered Oct 04 '22 03:10

Stephen