Anonymous Functions & IIFEs Exploring anonymous functions and Immediately Invoked Function Expressions (IIFEs) and their importance in modern JavaScript. by Irfan Khatib
Anonymous Functions Definition An Anonymous Function is a function without a name. It’s like a contractor hired for a specific job—you don’t need to remember their name, just the job they’re doing. In JavaScript, you normally use the function keyword followed by a name to declare a function.However, in an anonymous function, the name is omitted . let numbers = [1, 2, 3, 4]; numbers.forEach(function(number) { console.log(number * 2); }); // Output: 2 4 6 8
IIFE( Immediately Invoked Function Expressions ) Immediately Invoked Function Expressions (IIFE) are JavaScript functions that are executed immediately after they are defined. They are typically used to create a local scope for variables to prevent them from polluting the global scope. Example 1: Basic IIFE (function() { console.log('This runs immediately!'); })(); // Output: This runs immediately!
Why Use IIFEs? Private Scope Variables are inaccessible from outside. Naming Conflicts Prevents naming collisions. Accidental Modifications Avoids unwanted changes.