end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

Do you speak JavaScript?

§ Immediately Invoked Function Expression

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;
})(); // 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() {
  return {
    publicMethod: function() {

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


Next: Monkey patching(03:52)

To the lesson →