Immediately-Invoked Function Expression (2010)

benalman.com

16 points by motorest 4 days ago


domlebo70 - 19 hours ago

Reminds me of this post https://maxgreenwald.me/blog/do-more-with-run

I now reach for this a lot to allow me to write expression oriented programs in JS

motorest - 4 days ago

This blog post is referenced by Mozilla's page on IIFE.

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

jelder - 20 hours ago

I frequently reach for IIFE when I use switch/case. It's a very convenient (if maybe a bit weird looking) way of turning a statement into an expression. In other words, `return 1` instead of `foo = 1; break` for a trivial example.

insin - 16 hours ago

Missing my favourite when you don't care about a return value, which I personally find less fussy to type and look at (good for confusing Java developers who don't share the fullness of the stack, too):

    void function() {
      …
    }()
Escpecially when I can't be bothered to stop and extract an async function out when there's a sudden need to wait in a non-async context, handy when in the middle of adding features to browser extensions for apps:

    let $el = document.querySelector(…) // oops, not available yet

    void async function() {
      let $el = await waitForElement(…)
    }()
Edit: documented on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
zahlman - 18 hours ago

One of the things I hated most about using JavaScript in that era was the proliferation of long chains of }); or whatever the order was. IIFEs were a major contributor to that.

It's okay to name your functions. Flat is better than nested.

apothegm - 4 days ago

Those infuriate me so much when I need a slight modification to the behavior of a third party library. Leaves no option but forking. There are such better ways to achieve encapsulation in modern JS.