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.
(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
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.
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.
(function () { })(); This is called IIFE (Immediately Invoked Function Expression).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With