Immediately Invoked Function Expressions (IIFE) | kirupa.com


#1

by kirupa | 6 February 2015

By now, you probably know enough about functions in JavaScript to be dangerously productive. Functions allow you to group statements together. If you give your function a name, you can re-use those grouped statements a whole bunch of times:


This is a companion discussion topic for the original entry at http://www.kirupa.com/html5/immediately_invoked_function_expressions_iife.htm

#2

This is true of the function itself, but there can be many traces (good and bad/accidental) that the function has run. The most accidental way is if you forget to declare a variable and use it. This will be detected as an error if you opt-in to ES5’s strict mode:

(function(){ 'use strict'; foo = 5 })() // Uncaught ReferenceError: foo is not defined

If you aren’t using strict mode, which is the default, you will have just set the global variable foo in your program.

Plus, you can still mess with any global program state, even in strict mode, as long as those objects aren’t frozen:

(function(){ 'use strict'; Math.PIE = 3 })()
Math.PIE // 3

So, as the tutorial mentions, IIFEs are great for protecting the IIFE code from the rest of your (or others’) programs, but they don’t stop your IIFE code from wreaking havoc on the code outside of your IIFE.


There are ways other than using wrapping parentheses to reach a valid point in the grammar so that your function is treated as an expression. Pretty much any unary operator will work, for example:

void function(e){ console.log(e) }('hi')
!function(e){ console.log(e) }('hi')
typeof function(e){ console.log(e) }('hi')

I forget if there’s any good reason why people have settled on the paren syntax, other than that it reminds people of Lisp, I guess. :stuck_out_tongue:


#3

That’s a great point about IIFEs having the ability to wreck things outside of their bubbles. I’ll modify the tutorial by adding a note summarizing what you mention.

Regarding the syntax, the paren version does look at lot like Lisp haha!


#4

Void… Cooool. Looks like the return type :stuck_out_tongue_winking_eye: