// Function declaration — hoisted (can be called before it's defined)
function add(a, b) {
return a + b;
}
// Function expression — not hoisted
const multiply = function(a, b) {
return a * b;
};
// Arrow function — modern, concise
const subtract = (a, b) => a - b; // implicit return
const square = x => x * x; // single param, no parens needed
const greet = () => "Hello!"; // no params
// Multi-line arrow function needs explicit return
const divide = (a, b) => {
if (b === 0) throw new Error("Division by zero");
return a / b;
};
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
console.log(square(7)); // 49
// Default parameters
function greetUser(name = "World") {
return `Hello, ${name}!`;
}
console.log(greetUser()); // Hello, World!
console.log(greetUser("Alice")); // Hello, Alice!
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15