Void of Function Expression

Why can’t I declare a function and immediately execute it?

function foo() { .. }();

See the () on the end? So simple, right? But nope, that’s not legal syntax in JS.

Let’s try this instead:

function bob() { .. }

That works, but… now bob has escaped into the surrounding scope, which we might not have wanted.

Function Without The bob()

How do we declare and execute the function without the bob() in the mix?

If you want to declare and execute a function all in one go, you’ll have to make it a function expression instead of a declaration — declarations have the word function in the very first position, expressions don’t.

How do we do that? Let’s first try this:

function bob() { .. }
( bob )();

Here, I’ve wrapped ( ) around the name bob in the function call expression. What I’m illustrating here is that a call expression can actually be thought of as two separate expressions: (1) the lexical name look-up bob to get the function value reference; (2) the invocation operator () against the function value reference.

Well, what if we just do this:

( function bob() { .. } )();

We just inlined the function value, eliminating the need to declare and then look-up bob. So the expression ( function bob() { .. } ) is still going to produce the same function value reference, and thus the next () will invoke it all the same.

But now we’ve accomplished our goal of “declaring” (actually expressing) a function value and then immediately executing it. How? Because function is no longer in the first position in the statement, so now it’s able to immediately execute!

This is what’s called the IIFE (Immediately Invoked Function Expression) pattern. We’re a terribly creative bunch with our naming, aren’t we!?

BTW, you may have seen an alternate form of the IIFE parenthesis wrapping before, advocated by Crockford and others. We can observe:

function bob() { .. }
( bob() );

And then:

( function bob() { .. }() );

Note: This works for precisely the same reason as the previous variation: the outer ( .. ) serves no other purpose but to move function out of the first position of the statement, thereby making it an expression instead of a declaration. That makes the () after the function legal syntax.


The primary purpose of an IIFE is to create a function-block of scope in the middle of some other scope of our program. This could for example be to create variable(s) that will only exist for the life of that IIFE and not pollute the enclosing scope.

var a = 2;

(function IIFE(){
   var a = 10;
   var b = 20;
   console.log( a * b );  // 200

console.log(a);  // 2

Of course, we can do that now in ES6 with block scoping and let:

var a = 2;

   let a = 10;
   let b = 20;
   console.log( a * b );  // 200

console.log(a);  // 2

Once you have the { let .. }-form available, why would you use an IIFE form ever again? It’s heavier and uglier, right?

Changed this / return / etc

A function changes the meaning of this, return, etc. If that’s not what you want, the { let .. }-form is helpful. But, what if that’s exactly what you want!?

For example, you may want a “block” in the middle of some code where the this is set differently. Or you may want to use return to exit a block early on some condition?

function foo(o) {
   console.log(this.id);  // 1

   (function IIFE(){
      if (this.id > 4) return;


var o1 = { id: 1 }, o2 = { id: 5 };

o1.id;  // 2
o2.id;  // 5

Note: You can early-exit a block by labeling the block (like bob: { .. } and using continue bob;. However, that style of coding is far less common than early-exit with return from a function.

Repeating IIFE

Another case may be repeating a “block” under some circumstances, such as:

(function IIFE(){
   var el;

   // is `abc` present in the DOM yet?
   if (!(el = document.getElementById("abc"))) {
      // try again in a little while

   // .. use `el` now that it's present

Note: I know, I know, using timeouts like that is far less preferable to listening for events to know when something is ready. The point is, there are cases when a block needs to be repeated, and having that block as a named-function (expression) is a simple way of achieving that.

IIFE return

Function expressions are also useful if you want to specifically return a value from a block. Consider:

var id = (function IIFE(){
   var v;
   do {
      v = getNewID();
   } while (!validateID(v));
   return v;

Of course, in the case where the IIFE is returning a value, you don’t need the ( .. ) around it to make it an expression — it’s already one because function isn’t in the first position. So this works the same:

var id = function IIFE(){
   var v;
   do {
      v = getNewID();
   } while (!validateID(v));
   return v;

However, most people still put the ( .. ) around the function, because it’s a helpful visual signal to know that the assignment isn’t just of the function value itself, but that the () at the end will execute the function, and thus the assignment will be of any return value received.

I don’t personally use IIFEs in assignments very often. I prefer to avoid that here possible. There are a few exceptions, but it’s definitely a lesser-common pattern in my own code.


There’s a proposal being considered for the ES2016/2017 timeframe called “do-expressions”. A do-expression is a do-block kind of like the do..while, but where the while is left off, so it’s not a repeating loop.

Instead, the do-expression can have a result value (aka “completion value”) — specifically, the result of the final expression inside the block — that can be captured/assigned:

var id = do {
   let v;
   do {
      v = getNewID();
   } while (!validateID(v));
   v; // final expression becomes "completion value"

This is a proposal and not guaranteed. But it’s interesting to consider what additional coding patterns it might enable in the future.

So it’s clear that sometimes a function expression (IIFE) is more what you want than just a lightweight block scope.

( .. ) alternatives

As we explored earlier, the only concrete reason for the wrapping ( .. ) in an IIFE is for syntax disambiguation. But that’s not the only way we can accomplish the goal.

There are several unary operators (operators which take only one operand) in JS that can do the same thing. For example, some readers may have seen this (usually in minified code):

!function IIFE() { .. }();

The ! (negation) operator moves function out of the first position, so the () on the end becomes valid.

Other unary operators which can do the same thing: +, -, ~, etc.

Operating on Function or Return?

You may not have ever wondered/considered before, but ! for example negates a value. So how does !function...(); not negate the function to false before the ending () tries to invoke it (which would fail)?

Operator precedence. The () invocation operator binds more tightly than most other operators, which means it happens first. So the ! negation, or the + numeric coercion, or the ~ bitwise negation, or … those all happen after the invocation.

In other words, all these other operator variations of the IIFE are fine (and shorter by 1 character) than the ( .. ) wrapping form, but only when there’s no need to get a return value from the IIFE. Consider:

var x = !function IIFE(){ return 42; }();
console.log(x);  // false

The IIFE function runs right away, and then the ! is applied to any return value, which prevents us from getting the return value into x as we intend. The wrapping ( .. ) don’t mess with the value, so that’s the more preferred form if the return value of your IIFE is relevant.

Standalone IIFE

But with standalone IIFE’s, the return value is irrelevant, so those unary operator forms are all perfectly fine.

// no relevant return value here, so ~ is fine
~function IIFE() { .. }();

Which do you prefer? Do you still use ( .. ) even though it’s one character longer? Most do, it seems. Perhaps that’s just our normal habits at play.

I have taken to preferring a different operator for the job, which most JS devs have never heard much about: void.

The void operator is a unary operator that discards whatever value its given and returns undefined. Consider:

var x = void 42;
console.log(x);  // undefined

So, if I have a standalone IIFE that won’t have any relevant return value, I kinda prefer this form:

void function IIFE() { .. }();

What!? Yeah… no seriously, I do. But why?

Because the word void is a nice visual clue that stands out — it’s five characters (“void “) instead of 1 or 2 — and has a convenient semantic benefit that none of the other operator forms do.

void says, “hey, you! there’s no relevant return value here. The result is void of value.”

Update: As David mentions in the comments, void is also useful for voiding out the automatic return value from an => arrow function’s body expression.


At this point, most of you probably think I’m nuts for preferring void.

Just hear me out.

My primary goal is not shorter code. My primary goal is more understandable code. Code is communication with other humans.

So when someone is reading code, especially for the first time, with an IIFE in it, if the form is ( .. )-wrapped, or using ! or whatever, those operators have absolutely no meaning or obvious purpose.

There’s zero semantic reason for them to be included. They have to accept at face value that there’s some weird grammatic nuance that makes them required. Those sorts of things are not only not helpful in learning, but they actively overload the learner’s brain making it harder to understand other things.

I think void, on the other hand, offers a slight improvement in that there’s some meaningful, semantic reason for it to exist. We can explain that it’s there to signal no return value. It’s secondary (and irrelevant to the learner!) benefit is that it accomplishes that disambiguation for grammar purposes.

Given the choice between something that is nothing but visual clutter and serves no obvious purpose, which you just have to accept blindly, and something that has at least some degree of semantic explanation, I think the latter creates more understandable code than the former.

Ironically, it’s the ( .. ) / ! / + / etc forms that are void of any value in our code. void gives our IIFE’s meaning. And understandability.

Posted in: JavaScript by getify 3 Comments