JavaScript Functions
Functions in JavaScript are reusable blocks of code designed to perform a specific task.
1️⃣ Function Declaration
A named function that can be called before it's defined (due to hoisting).
Syntax
Example: Add two numbers
📌 Hoisting allows calling add()
before defining it.
2️⃣ Function Expression
A function stored in a variable. Not hoisted (cannot be called before declaration).
Example: Multiply numbers
3️⃣ Arrow Functions (ES6) 🚀
A shorter way to write functions.
Syntax
Example: Square a number
📌 If one parameter, parentheses are optional:
📌 If no parameters, use empty parentheses:
4️⃣ Default Parameters
Assign default values to function parameters.
5️⃣ Rest Parameters (...
)
Allows functions to accept any number of arguments.
6️⃣ Function Scope & Closures
Functions create local scope.
📌 Closures allow inner functions to access outer variables even after execution.
7️⃣ Higher-Order Functions
Functions that take another function as an argument or return a function.
8️⃣ Immediately Invoked Function Expressions (IIFE)
A function that runs immediately after definition.
📌 Useful for isolating variables and avoiding pollution of global scope.
🎯 Summary
✅ Function Declaration → function greet() {}
(hoisted)
✅ Function Expression → const greet = function() {}
(not hoisted)
✅ Arrow Function → const greet = () => {}
(shorter syntax)
✅ Default Parameters → function greet(name = "Guest") {}
✅ Rest Parameters → function sum(...numbers) {}
✅ Closures → Functions can remember outer variables
✅ Higher-Order Functions → Functions that take/return other functions
✅ IIFE → (function() { console.log("Runs immediately!"); })();
🚀 Now you’re ready to master JavaScript functions! Let me know if you need any help. 😊