Declaring a Function
function greet(name) {
return "Hello, " + name + "!";
}
const message = greet("Alice");
console.log(message); // "Hello, Alice!"Parameters and Return
function add(a, b) {
return a + b;
}
add(2, 3); // 5
add(10, 20); // 30
// Default parameter values
function greet(name = "World") {
return `Hello, ${name}!`;
}
greet(); // "Hello, World!"
greet("Alice"); // "Hello, Alice!"Arrow Functions
// Traditional
function square(x) { return x * x; }
// Arrow function
const square = (x) => x * x;
// Single parameter — parens optional
const double = x => x * 2;
// Multi-line — needs braces + return
const add = (a, b) => {
const sum = a + b;
return sum;
};Function Expressions
// Stored in a variable
const multiply = function(a, b) {
return a * b;
};
// Immediately Invoked Function Expression (IIFE)
(function() {
console.log("Runs immediately!");
})();Higher-Order Functions
// A function that takes a function as argument
function repeat(n, action) {
for (let i = 0; i < n; i++) action(i);
}
repeat(3, i => console.log("Step", i));
// Step 0
// Step 1
// Step 2Arrow functions don't have their own
this — they inherit it from the surrounding scope. Use them for callbacks and short expressions. Use regular functions when you need this (class methods, event handlers on DOM elements).