Câu hỏi phỏng vấn Javascript
Câu hỏi

What is IIFEs (Immediately Invoked Function Expressions)?

Câu trả lời

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:

javascript Copy
(function() {
    // Code goes here
})();

This pattern can also be written with arrow functions in ES6 (ECMAScript 2015) as follows:

javascript Copy
(() => {
    // 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:

javascript Copy
(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

middle

Gợi ý câu hỏi phỏng vấn

middle

What are the advantages and disadvantages of using use strict ?

expert

In JavaScript, why is the this operator inconsistent?

senior

When should you NOT use arrow functions in ES6? Name three or more cases

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào