Functions 🔧
Functions package logic so you can reuse it everywhere.
1) Declarations vs Expressions 🧾
function add(a, b) {
return a + b;
}
const multiply = function (a, b) {
return a * b;
};- Declarations hoist (usable before definition).
- Expressions assign a function to a variable.
2) Arrow Functions ➡️
const greet = name => `Hello, ${name}!`;
const double = (n) => {
return n * 2;
};- Lexical
this: they capturethisfrom the surrounding scope. - No
argumentsobject; use rest params instead.
3) Closures 🧠
A closure remembers variables from its birth scope.
function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
counter(); // 1
counter(); // 24) Recursion 🔁
Functions calling themselves until a base case.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}- Ensure a base condition to prevent infinite loops.
5) Higher-Order Functions 🧮
Functions that take other functions or return them.
const numbers = [1, 2, 3];
const squares = numbers.map(n => n ** 2);map,filter,reduce,forEach,some,every.- Compose logic by passing callbacks.
Key Takeaways ✅
- Choose declarations for hoisting, expressions for inline definitions, and arrows for concise lexical
this. - Closures power private state and factory functions.
- Recursion and higher-order functions unlock elegant logic for trees, lists, and asynchronous flows.
Recap 🔄
Functions are JavaScript’s workhorses—master their shapes (declaration, expression, arrow), understand closure-powered memory, and embrace higher-order patterns to write expressive code.
Last updated on