33 Javascript Concepts — #8. IIFE and Module

DH KIM
3 min readFeb 4, 2021

First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.

#8. IIFE and Module

IIFE

If you want to make a variable that can not be accessed globally, you can declare a variable in the local scope. However, how do we make it so that our function also cannot be accessed? That’s where IIFE comes in!!

IIFE (Immediately Invoked Function Expression) refers to a function that is executed as soon as declared. IIFE is consist of two parts, first parenthesis that includes an anonymous function that doesn’t have function name and second parenthesis that invokes anonymous function immediately.

Basic syntax is like below.

// IIFE defined with regular function syntax(function () {
statements
})();
// IIFE defined with arrow function syntax(()=>{
statements
})();

Since the function is only invoked once, we don’t need to give the function a name anymore.

Module

If we don’t use module system, variables are shared globally. Let see what i mean by example below.

<script defer src=”app.js”></script>
<script defer src=”app2.js”></script>

First we import app.js and app2.js in html file.

// app.js
const age = 20;

In app.js, we declare age and assign 20

// app2.js
console.log(age);

In app2.js, write a single line of code that log age on the console.
What will be logged on the console???

Although age was declared from app.js file, it can be read inside of app2.js file since all global variables are shared in this case.

This is not a problem, if you are smart enough to remember all variables declared globally and have great naming skills so that every global variables have different name. But most of people, including me, don’t have this amazing skills. This is where ES6 module system comes in.

Module is just a chunk of code written in a file. The variables, functions in a module can not be used from another modules unless module files are exported.

<script type=’module’ defer src=”app.js”></script>
<script type=’module’ defer src=”app2.js”></script>

By writing type= “module” , we can simply use module system. And this will lead different result on the console.

To use variables declared in another module, we have to export them. But i will not write about it here. If you want to learn more click here

Conclusion

Honestly, i’ve never used IIFE in my projects. Thought that is just good to know concept. However module is what most of we are using to make big project without wasting time thinking about unique variable names.
I want this post was helpful for you guys. If this was helpful, left some responses of claps!!!

reference: medium

--

--