JavaScript Function Expressions
A function expression is a function that is assigned to a variable. Unlike function declarations, function expressions are not hoisted and must be defined before use.
1️⃣ Syntax
2️⃣ Example: Function Expression
š Key Difference from Function Declarations:
- Function declarations are hoisted, meaning they can be used before they are defined.
- Function expressions are not hoisted, meaning they must be defined before use.
3️⃣ Anonymous Function Expression
A function without a name, assigned to a variable.
š The function has no name but is stored in the sum
variable.
4️⃣ Named Function Expression
A function with a name, assigned to a variable.
š Here, fact(n)
is a function name only available inside the function.
5️⃣ Function Expressions as Arguments
Function expressions can be passed as arguments to other functions.
6️⃣ Arrow Functions (ES6) as Function Expressions
A shorter syntax for function expressions.
7️⃣ Immediately Invoked Function Expression (IIFE)
A function that runs immediately after being defined.
š Useful for:
✅ Avoiding pollution of global scope
✅ Isolating variables in their own scope
šÆ Summary
✅ Function Expression → const sum = function(a, b) { return a + b; };
✅ Anonymous Function Expression → No function name
✅ Named Function Expression → Can reference itself
✅ Used as Arguments → Pass functions into other functions
✅ Arrow Functions → const square = n => n * n;
✅ IIFE → (function() { console.log("Runs immediately!"); })();
š Now you understand function expressions! Let me know if you need help. š