Functions
Arrow functions and scope
Goal: Write arrow functions and understand block scope and closures · 9 min
Arrow functions are a short syntax: const square = x => x * x; With one expression, the value is returned implicitly. Several parameters need parentheses: (a, b) => a + b; a body with several statements needs braces and an explicit return.
Scope: let and const are visible only inside the block { } where they are declared. Inner functions can read variables of outer functions — even after the outer function has finished. This is called a closure:
function counter() { let n = 0; return () => ++n; }
const next = counter(); next(); next(); // 2Worked example: Closure keeps state
- makeAdder(10) returns a function that remembers 10.
- add10(5) → 15.
- Each call of makeAdder creates a new, independent closure.
const makeAdder = n => x => x + n;
const add10 = makeAdder(10);
console.log(add10(5), makeAdder(1)(1));Output:
15 2