Suggest an editImprove this articleRefine the answer for “IIFE”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A **self-invoking function** (**IIFE - Immediately Invoked Function Expression**) is a function that **is created and invoked right away**, without a separate call by name. **Key point:** IIFEs are used to isolate scope, perform one-time initialization, and run async code immediately.Shown above the full answer for quick recall.Answer (EN)ImageA self-invoking function (**IIFE - Immediately Invoked Function Expression**) is a function that **is created and invoked right away**, without a separate call by name. --- ## Syntax: ```javascript (function () { console.log('I ran right after being declared!'); })(); ``` Notice the **two pairs of parentheses**: 1. The first `(function() { ... })` - turns the function into a **function expression**. 2. The second `()` - **immediately invokes** that function. --- ## Example with parameters: ```javascript (function (name) { console.log(`Hello, ${name}!`); })('Tim'); ``` Prints: ```javascript Hello, Tim! ``` --- ## What IIFE is used for ### 1. **Creating an isolated scope** IIFE is often used to **avoid variable conflicts** - for example, when writing code that should not "pollute" the global scope (`window` or `global`). ```javascript (function() { const secret = 'Secret inside the function'; console.log(secret); })(); console.log(secret); // ReferenceError: secret is not defined ``` The `secret` variable is only accessible inside the IIFE. --- ### 2. **One-time code initialization** You can use an IIFE to run something **once, on load**: ```javascript const config = (() => { const apiKey = '12345'; const baseUrl = 'https://api.example.com'; return { apiKey, baseUrl }; })(); console.log(config.apiKey); // 12345 ``` We return an object, but the variables inside stay **encapsulated**. --- ### 3. **Use with async / await** An IIFE can be made **asynchronous** to use `await` at the top level: ```javascript (async () => { const data = await fetch('/api/data').then(res => res.json()); console.log(data); })(); ``` --- ## Historically Before ES6 modules appeared (where every `import/export` file unit now has its own scope), IIFEs were actively used in JavaScript for **encapsulation** and **code structuring**. They are used less often now, but are still useful for: - one-time initialization, - isolating temporary variables, - immediately running async code. --- **In short:** | Trait | Description | |---|---| | Name | IIFE - Immediately Invoked Function Expression | | Essence | The function is created and invoked right away | | Why | Isolation, initialization, temporary variables | | Traits | Does not pollute the global scope, can be async |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.