ES6 – From beginner to advanced (Part 3)

Tram Ho

To end the series on ES6, I would like to introduce to you two concepts that are used quite a lot in Js programming, which we rarely pay attention to.

content

  1. IIFE
  2. Closures

1. IIFE

IIFE stands for Immediately Invoked Function Expression. IIFE is a function of Javascript, this function runs as soon as it is defined

IIFE differs from normal functions in that we can call it more than once but IIFE does not. IIFE is only used once. That means the variables in there cannot be accessed so it is immutable

Another benefit of IIFE is to create local scope, if you have many js files that may have many similar variable names. IIFE avoids writing and protecting the scope of those variables.

Use IIFE. We wrap the function in () then we add () to the end of the function

(Our function) (Invoke)

(Our function) ()

In fact, we do not need to name the function because they only run once. So IIFE will often use the anonymous function

2. Closures

Closures are when a function remembers lexical scope even if a function is performed outside of lexical scope. So closure is when a function uses a variable defined in another function or another scope. It creates a link to this variable to update its variable

For example, we have 1 function printName with 1 variable. Then we have a function closure that calls the print function. Finally, we call this function in another scope

In other words, we execute the print function using a name variable. This variable is not declared in the scope function closure , but this variable is still in the scope function printName

By default, this logic is false. But in fact, this is a closure. So if we change or update our variable name, the Closure will update it

For another example, we can get or update the variable x in the inner function

This is another way to load the function closure first. Over here we have replaced an inner function that is an anonymous function that returns many values ​​in an array. Then we have implemented the outer function

Summary:

Hopefully the things I share above will help a lot for beginners to learn Javascript and ES6

References:

Share the news now

Source : Viblo