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:
- kicking off the start of code.
- 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)