TutreNews Learn

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(); // 2

Worked example: Closure keeps state

  1. makeAdder(10) returns a function that remembers 10.
  2. add10(5) → 15.
  3. 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