IIFE or Immmediately Invoked Function Expression is a function which is executed as soon as the function is created.

(function () {
    /.../
})();

Using arrow functions:

(() => {
    /.../
})();

The function contained within the brackets () is an anonymous function. It is anonymous due to the function not having a name. If we were to write an anonymous function outside the containing brackets (), we would get an error.

function () {
    console.log("Hello");
}
    
//Result:
//Uncaught SyntaxError: function statement requires a name

The enclosing brackets () allow the function to be anonymized and also protects the function along with any variables from being accessed from outside the IIFE scope and prevents the global object from being polluted.

(function () {
   let a = 1;
})();

console.log(a); //Uncaught ReferenceError: a is not defined

The brackets outside the IIFE scope (); allow the function expression to be invoked immediately.

Functions can be either anonymous as above or named.

(function add () {
    let x = 2;
    let y = 2;

    console.log(x + y);
})();

Using arrow functions:

(add = () => {
    let x = 2;
    let y = 2;

    console.log(x + y);
})();

We can save the return value of a function in an IIFE by assigning it to a variable.

let answer = (function () {
    let x = 2;
    let y = 2;
    
    return x + y;
})();

NOTE: This will only save the return value and not the function’s definition.