DEV Community

Cover image for ๐Ÿ’ก IIFE - Immediately Invoked Function Expressions in JavaScript

๐Ÿ’ก IIFE - Immediately Invoked Function Expressions in JavaScript

Benjamin Mock
I'm Ben, a Frontend Developer from Germany working at ebay
Originally published at ใƒป1 min read

You might have heard of IIFEs or you might already have seen some syntax like this:

(function() {
  // do some stuff

or as an arrow function like this

(() => {
  // do some stuff

These are immediately invoked function expressions. But what are they good for?

They're basically used to encapsulate code. Variables that are declared within an IIFE are isolated and neither the function itself nor the variables inside of it will pollute the global object, even if you use var which has function scope.

Let's have a closer look at the syntax.

// we basically create a function with brackets, which makes it an expression and call it immediately
(/* some function */)()

All the variable declarations are completely encapsulated. There's no way to access a variable from the outside. The following snippet will log the variable x, but x is not accessible from outside the IIFE.

(() => {
  const x = "dev"

console.log(x) // undefined

Want to get better at Web Development?
๐Ÿš€๐Ÿš€๐Ÿš€subscribe to the Tutorial Tuesday โœ‰๏ธnewsletter

Discussion (0)