A function packages code under a name so you can run it whenever, wherever, as many times as you like — the fundamental unit of reuse in JavaScript.
Three ways to declare one
// 1. Declaration — hoisted, callable before it appears in the file
function greet(name) {
return `Hello, ${name}!`;
}
// 2. Expression — a function stored in a variable
const greet2 = function (name) {
return `Hello, ${name}!`;
};
// 3. Arrow function — concise, and the modern default for callbacks
const greet3 = (name) => `Hello, ${name}!`;
const shout = (text) => text.toUpperCase() + "!"; // implicit returnArrow functions with a single expression return it automatically; with { }
you need an explicit return.
Parameters
// Defaults kick in for missing OR undefined arguments
function makeTea(type = "milk", sugar = 1) {
return `${type} tea, ${sugar} sugar${sugar === 1 ? "" : "s"}`;
}
makeTea(); // "milk tea, 1 sugar"
makeTea("lemon"); // "lemon tea, 1 sugar"
// Rest parameters gather extras into a real array
function total(...prices) {
return prices.reduce((sum, p) => sum + p, 0);
}
total(120, 40, 250); // 410Functions are values
Functions can live in variables, arrays, objects — and be handed to other functions. One that takes or returns a function is called higher-order:
const ops = {
add: (a, b) => a + b,
mul: (a, b) => a * b,
};
ops.mul(6, 7); // 42
[1, 2, 3].map((n) => n * 10); // map receives YOUR functionmap, filter and reduce deserve special attention — you'll use them
constantly. They're covered hands-on in the next chapter.
Closures — functions with memory
A function defined inside another keeps access to the outer variables even after the outer call has finished. That combination (function + captured variables) is a closure, and it's how JavaScript does private state:
Closures power module patterns, memoization, event handlers that remember their setup data, and hooks in frameworks like React.
Callbacks
A callback is simply a function passed to be called back later — the seed of all asynchronous JavaScript (chapter 6):
button.addEventListener("click", () => {
console.log("clicked"); // this arrow runs LATER, on click
});
setTimeout(() => console.log("3 seconds passed"), 3000);Knowledge Check
4 questions — test your understanding
How do arrow functions treat this?
function greet(name = "World") {} - what does greet(undefined) return?
function counter() { let n = 0; return () => ++n; } - why does this work as a private counter?
With rest parameters, function f(...args) receives args as...
Next: Arrays & Objects