This lesson is only accessible in the paid version of the course.
Get access to all lessons 💫 price: 34.99$
Do you speak JavaScript?
In this video, we will be discussing Immediately Invoked Function Expression (IIFE) in JavaScript and how to use it to create a private scope for your variables.
An Immediately Invoked Function Expression (IIFE) is a function that is immediately executed after it is defined. It can be used to create a local scope and hide variables and functions from the global scope. They are also known as Self-Executing Anonymous Functions.
Here is an example of an IIFE in JavaScript:
(function () {
var x = 10;
console.log(x);
})(); // Output: 10
console.log(x); // ReferenceError: x is not defined
In this example, the function ()
is immediately invoked after it is defined, and it creates a local scope for the variable x
, which is only accessible within the function. Attempting to access x
from the global scope will result in a ReferenceError
.
IIFEs are also useful for creating modules, this is a pattern that's often used in JavaScript libraries and frameworks. Here is an example:
const myModule = (function () {
let privateVariable = "I am private";
function privateMethod() {
console.log(privateVariable);
}
return {
publicMethod: function() {
privateMethod();
}
};
})();
myModule.publicMethod(); // Output: "I am private"
console.log(myModule.privateVariable); // undefined
In this example, the IIFE returns an object that has a public method that can access the private variable and methods. This way the private variable and methods are hidden from the outside world and can only be accessed by the public methods.
Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.
Materials related to the lesson:
→ Files associated with the lesson
→ Ben Almen's article about IIFE