JavaScript - Scope

Immediately-Invoked Function Expression (IIFE), a.k.a. self-executing anonymous functions

Code language: JavaScript

(function () {
  // Safely declare your names inside this function.
  var variable1 = 1;
  let variable2 = 2;
  const constant = 3;
  function someFunction() {}
  class SomeClass {}

At the heart of this pattern, there is an anonymous function function () {…}. This is a function expression that simply creates a function and returns it as a value, in contrast to a function declaration that creates a function and inevitably binds it to a name.

The braces around the anonymous function, ( function() {…} ), allow the parser to recognize the function expression correctly. Finally, the braces at the end () call the function immediately. That is why it is called immediately-invoked function expression.

Quoted content is licensed under CC BY-SA.