₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,043 members, 8,420,028 topics. Date: Thursday, 04 June 2026 at 09:51 AM

Toggle theme

Javascript Self-executing Functions - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingJavascript Self-executing Functions (245 Views)

1 Reply

Javascript Self-executing Functions by kemi72(op): 1:08am On Oct 10, 2023
What are Self-Executing Functions?
A self-executing function, also known as Immediately-invoked Function Expression (IIFE), is a JavaScript function that is defined and executed immediately after its creation. Unlike regular functions that require a call to execute their code, IIFE runs automatically. This feature is particularly handy when you want to encapsulate code and create a private scope for your variables, preventing them from polluting the global scope and is a good software development practice.

The basic syntax for an IIFE looks like this:

(function () {
// Your code here
})();
Here’s a breakdown of how this works:

Enclose the function definition within parentheses (function () { ... }).
Immediately following the closing parentheses, add another pair of parentheses ( ... ) to invoke the function.
In this software development training in Abuja, Nigeria, you will learn how to build software solutions that solve real time problems.

Inside the first set of parentheses, you can pass parameters to the IIFE just like you would with any regular function. For example:

(function (x, y) {
console.log(x + y);
})(5, 10); // Outputs: 15
Benefits of Self-Executing Functions
Self-executing functions offer several advantages that make them a valuable tool for software developers who use JavaScript:

1. Encapsulation and Scope Isolation
One of the primary benefits of IIFE is that they create a private scope for your code. Any variables declared inside an IIFE are not accessible from the outside, preventing them from conflicting with variables in the global scope or other parts of your code. This helps improve code maintainability and reduces the risk of naming collisions.

(function () {
var privateVar = 'This is private';
console.log(privateVar); // Outputs: 'This is private'
})();
console.log(typeof privateVar); // Outputs: 'undefined'

Read more
https://codeflarelimited.com/blog/javascript-self-executing-functions/

1 Reply

Inline Functions In C++Mobile Technology: Lets Build A Mobile App With JavascriptFree HTML5, CSS3 And Basic Javascript (jquery) Training234

Are You An App Devloper? Hop InReplace Your Text OnlineConnection Across Different Time Zones Without An Internet