I see many developers found in a situation where they mess up variable name conflict especially in JavaScript, as var
is a global scope.
In order to avoid variable name conflict, we should write code in a way so that we can get out of it.
For that, we use IIFE statements where we can minimize any variable name conflicts.
In a situation where we want to create a program, we start writing codes on a blank page where we may have variable name conflicts when the code starts growing.
Then, what if we wrap a block of code inside a function and call it, where it does its job. Like this:
function functionName() {
var text = "Hello World";
console.log(text);
}
functionName();
console.log(text); // text is undefined
But that is awful to call a function when it does not need to call it again.
Here comes a solution
IIFE ( Immediately Invoked Function Expression, pronounced “iffy” ) is a JavaScript function expression which calls the function after it defined.
Here is the above code wrapped inside of IIFE which is as simple as this:
(function() {
var text = "Hello World";
console.log(text);
// your codes here
})();
console.log(text); // text is undefined
In this example, first, we create a function inside a parenthesis then call the function after it defined. There are several ways to write an IIFE statement.
(function() {
// your codes here
})();
(function() {
// your codes here
}());
(() => { /* ... */ })(); // The parentheses in arrow functions of ES6 is only allowes on outside
I personally prefer the first one because it is easy to use and easy to understand. But you can use whatever you want just remember the syntax.
So Let’s start coding