DEV Community

Aaron Reisman
Aaron Reisman

Posted on • Updated on

Simplifying the mental model of Immediately-invoked Function Expressions in JavaScript

I'd like to breakdown how Immediately-invoked Function Expression (IIFE) works.

Let's start with some basics.

if I run this code what happens?

(undefined)
Enter fullscreen mode Exit fullscreen mode

the value that is returned from (undefined) is undefined.

what if we replaced that?

(1)
Enter fullscreen mode Exit fullscreen mode

(1) becomes 1

what we're doing is taking a (wrapped) value and returning it.

(x) === x

when passing a function as a value, we can call it.

(function add(x) { return x + x })
Enter fullscreen mode Exit fullscreen mode

becomes

function add(x) { return x + x }
Enter fullscreen mode Exit fullscreen mode

so, if we do

(function add(x) { return x + x })(2)
Enter fullscreen mode Exit fullscreen mode

Our value is a function, and we called that function with the arguments of 2 which the IIFE evaluated to 4.

if we didn't use the parentheses, we'd have to write our code like this:

function add(x) { return x + x }

add(2);
Enter fullscreen mode Exit fullscreen mode

the parentheses handle a step for us, we can define and call a function on 1 line, but if we don't, it results in a syntax error:

function add() { }() // Uncaught SyntaxError: Unexpected token ')'
Enter fullscreen mode Exit fullscreen mode

practical use cases I've seen for IIFE's are:

  1. kicking off the start of code.
  2. invoking a function to get a value to use later.

I'd love to hear your feedback on if this was helpful to you.

Have a good day!

Top comments (0)