Functions
Prerequisites:
Functions are reusable blocks of code that perform specific tasks.
Function Declaration
Section titled “Function Declaration”function greet(name) { return `Hello, ${name}!`;}
greet("Alice"); // "Hello, Alice!"Function Expression
Section titled “Function Expression”const greet = function(name) { return `Hello, ${name}!`;};Arrow Functions (ES6)
Section titled “Arrow Functions (ES6)”// Full syntaxconst greet = (name) => { return `Hello, ${name}!`;};
// Concise syntax (implicit return)const greet = (name) => `Hello, ${name}!`;
// Single parameter (no parentheses needed)const double = n => n * 2;
// No parametersconst sayHi = () => "Hi!";Parameters & Arguments
Section titled “Parameters & Arguments”Default Parameters
Section titled “Default Parameters”function greet(name = "Guest") { return `Hello, ${name}!`;}
greet(); // "Hello, Guest!"greet("Alice"); // "Hello, Alice!"Rest Parameters
Section titled “Rest Parameters”function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0);}
sum(1, 2, 3, 4); // 10Destructuring Parameters
Section titled “Destructuring Parameters”function createUser({ name, age, role = "user" }) { return { name, age, role };}
createUser({ name: "Alice", age: 30 });Return Values
Section titled “Return Values”// Single valuefunction add(a, b) { return a + b;}
// Multiple values (via object)function getStats(numbers) { return { min: Math.min(...numbers), max: Math.max(...numbers), avg: numbers.reduce((a, b) => a + b) / numbers.length };}
const { min, max, avg } = getStats([1, 2, 3, 4, 5]);Higher-Order Functions
Section titled “Higher-Order Functions”Functions that take or return other functions:
// Function as parameterfunction repeat(fn, times) { for (let i = 0; i < times; i++) { fn(i); }}
repeat(i => console.log(`Iteration ${i}`), 3);
// Function as return valuefunction multiplier(factor) { return (number) => number * factor;}
const double = multiplier(2);double(5); // 10Closures
Section titled “Closures”Functions remember their lexical scope:
function counter() { let count = 0; return { increment: () => ++count, decrement: () => --count, getCount: () => count };}
const myCounter = counter();myCounter.increment(); // 1myCounter.increment(); // 2myCounter.getCount(); // 2