What is iffy?

Iffy, often stylized as IIFE, stands for Immediately Invoked Function Expression.

It's a JavaScript design pattern where a function is defined and executed immediately after its creation.

Key characteristics of an IIFE:

  • Function Expression: It starts with a function enclosed in parentheses (function() { ... }). The parentheses are crucial; they tell the JavaScript parser to treat the code as an expression rather than a function declaration. Using a Function Expression is important because function declarations need a name, which we avoid in IIFEs.
  • Invocation: Immediately after the function expression, another set of parentheses () invokes the function.
  • Privacy: IIFEs create a new scope. Variables declared inside the IIFE are not accessible from the outside, providing a form of data Privacy.
  • Avoid Global Scope Pollution: By creating a local scope, IIFEs prevent variables from accidentally leaking into the global scope and potentially causing conflicts.
  • Syntax: The basic syntax is:
(function() {
  // Code to be executed immediately
})();

// OR

(function() {
  // Code to be executed immediately
}());
(function(name) {
  console.log("Hello, " + name + "!");
})("World"); // Outputs "Hello, World!"

Benefits of using IIFEs:

  • Encapsulation of code.
  • Avoidance of naming conflicts.
  • Improved code organization.

They are still used in some legacy code, though modern JavaScript features like const and let (block scope variables) and modules have reduced their necessity in many cases.