Skip to content
the poor coder

es6 IIFE

Poor Man
Published
Reading time
1 min read
On this page

What is ES6 IIFE?#

ES6 IIFE stands for Immediately Invoked Function Expression, which is a way of declaring and calling a function at the same time. It is commonly used in JavaScript to create a local scope and prevent variables from polluting the global scope.

How to use ES6 IIFE?#

To use ES6 IIFE, you can declare a function expression and immediately invoke it using parenthesis. Here is an example:

Text

(() => {
  // code here
})();

In this example, we declared an arrow function expression, wrapped it in parenthesis, and called it immediately using another set of parenthesis. This creates a local scope where variables declared inside the function are not accessible outside of it.

You can also pass arguments to the IIFE by placing them inside the first set of parenthesis. Here is an example:

Text

((x, y) => {
  console.log(x + y);
})(2, 3);

In this example, we passed two arguments to the IIFE and logged the sum of them to the console.

Alternative ways to use IIFE#

There are other ways to declare and call an IIFE in JavaScript. Here are some examples:

  • Using a function expression instead of an arrow function
  • Using the "function" keyword instead of an arrow function
  • Using the "void" operator to prevent the IIFE from returning a value

Regardless of the syntax used, ES6 IIFE is a powerful tool in JavaScript that allows you to create local scopes and prevent variable collisions in the global scope.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC