Translation: The rolling curtain is still

The original address: javascript. Plainenglish. IO / 4 – practical…

withIIFEWrite more secure code

You’ve probably heard of the concept of IIFE.

IIFE full name is Immediately Invoked Function Express- The Immediately Invoked Function, as the name implies, is a Function executed Immediately after definition.

IIFE is primarily known for protecting variable ranges. But what does this mean in practice, and what are IIFE’s practical applications?

You’ll find answers to these questions in this article.

closure

Variables defined inside IIFE are not accessible to the outside world. In other words, variables declared with let or const are only accessible inside the block. (Note: block is the scope defined by {})

However, it is inevitable that at some point you will need to modify these variables.

How to modify:

Closures, as you all know, provide the ability to access the scope of an external function from within a function. Creating a closure is nothing more than defining a function inside another function and exposing that function externally.

Closures have two advantages when combined with IIFE:

  1. The range of variables is safely limited to avoid being modified by unexpected behavior;
  2. You can modify variables inside a function outside of it. That sounds like it undermines the first advantage, but it doesn’t. Because variables cannot be modified directly, they can only be modified through internally exposed functions. This approach is safe.
const user = (function() {
  let name = 'anonymous';  
  return {
    getName: _= > name,
    setName: newName= >name = newName }; }) ();console.log(user.getName()) // anonymous
user.setName('Amy');
console.log(user.getName()); // Amy
Copy the code

Name is a private variable that can only be changed within the immediate user function. But because we are using closures here, we can modify the variable externally by exposing the setName() method.

Alias of a global variable

Using a large number of JavaScript libraries can cause conflicts because the objects exposed by these libraries may have the same name.

Than if you are using jQuery. We all know that it exposes $as the primary object. As long as any library in your project dependencies also uses the $sign to export variables, conflicts will occur.

Fortunately, you can solve this problem by executing the function immediately to set the alias:

(function ($) {
// You’re safe to use jQuery here
})(jQuery);
Copy the code

By wrapping the code in IIFE and passing jQuery as an argument, you guarantee that the $symbol will only reference jQuery and not other libraries.

Safe range of variables

ES6 introduced lets and const to define variables in a more secure way. Using VAR can lead to unexpected behavior because the scope of VAR can be easily broken.

But what if your production environment doesn’t support ES6? Or in some cases you can’t use let and const?

Don’t worry. You also have IIFE, the Immediately Invoked Function Expression- executing the Function Immediately achieves the same goal.

(function () {
  varThe greeting = 'Good morning! How are you today? ";console.log(greeting); // Good morning! How are you today?}) ();console.log(greeting); // error: Uncaught ReferenceError: greeting is not defined
Copy the code

As you saw in the demo above, execution within immediate functions is only valid within IIFE. You cannot externally access variables defined inside IIFE.

Loop index

Executing loops within asynchronous tasks can lead to unexpected results.

Take setTimeout() as an example:

for (var i = 0; i < 3; i++) {
    setTimeout(_= > console.log(` We 're at${i}`), 100);
}
Copy the code

We expect to get:

We’re at 0
We’re at 1
We’re at 2
Copy the code

But it turns out that

We’re at 3
We’re at 3
We’re at 3
Copy the code

Why do you do that? Because the console.log() statement in this example is set to be executed after 100ms. The loop is done before that, which means I is already at 3. As a result, all console.log() prints the final result: I = 3

We can solve this problem by putting setTimeout into IIFE:

for (var i = 0; i < 3; i++) {
    (function(index) {
        setTimeout(_= > console.log(` We 're at${index}`), 100);
    })(i);
}
Copy the code

The results were as expected:

We’re at 0
We’re at 1
We’re at 2
Copy the code

Also, this is the era of ES6, and we can simplify code with lets:

for (let i = 0; i < 3; I++) {setTimeout (_ = > console. The log (` We 're at ${I} `), 100); }Copy the code

conclusion

IIFE is a great way to ensure scope security. You can use IIFE to prevent problems with global variable definitions, alias variables, protect private variables, and avoid conflicts when different libraries export the same object name.

Although IIFE can be replaced with ES6 features, you should still learn IIFE to get a clearer understanding of how scopes work in JavaScript. Also, you can’t make ES6 immediately available to older projects. So IIFE is still important.

Did you learn? I hope you like this article