What is IIFEs (Immediately Invoked Function Expressions)?
What is IIFEs (Immediately Invoked Function Expressions)?
An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern which is used to execute a function immediately as soon as it is defined. The primary purpose of an IIFE is to create a new scope by declaring a function and running it immediately without saving a reference to it. This helps in avoiding pollution of the global namespace and provides a way to encapsulate variables and functions.
The syntax of an IIFE involves wrapping the function declaration in parentheses, followed by another set of parentheses that invokes the function immediately. Here is a basic example of an IIFE:
(function() {
// Code goes here
})();
This pattern can also be written with arrow functions in ES6 (ECMAScript 2015) as follows:
(() => {
// Code goes here
})();
One of the key benefits of using an IIFE is data privacy. Variables declared within the IIFE cannot be accessed by the outside world, which is particularly useful for protecting the scope of variables and preventing conflicts with other code that may be using the same variable names.
IIFEs can also be used to pass arguments into the self-executing function, allowing for initialization code that runs once and does not interfere with other parts of the application. For example:
(function(message) {
console.log(message);
})('Hello, World!');
In this example, the string 'Hello, World!' is passed as an argument to the IIFE and logged to the console immediately.
Before the introduction of block-scoped variables (let
and const
) with ES6, IIFEs were commonly used to simulate block sc...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào