DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

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

what if we replaced that?

(1)

(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 })

becomes

function add(x) { return x + x }

so, if we do

(function add(x) { return x + x })(2)

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);

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 ')'

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)

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post