Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 3

Functions, Scope and Closures

Define functions with parameters that adapt, pass them around like any other value, and use closures to keep private state between calls.

Contentsand lesson path

What you will learn

  • Define and compose functions (arrow functions, default and rest parameters, higher-order functions, closures) and explain lexical scope and how this is bound.

01. Why it matters

Functions are the unit you build with. They turn a block of behaviour into a name you can read, test and reuse, and they are the currency of every framework you will meet: a React component is a function, an event handler is a function, a test case is a function. Getting fluent in three ideas — parameters that adapt, functions passed as values, and scope — pays for itself immediately.

The third idea, the closure, is the one that separates people who copy JavaScript patterns from people who understand them. A closure lets a function remember the variables that existed where it was created, even after that creation has finished. It is how you keep private state without a class, why callbacks can read "their" configuration, and the answer to a whole genre of interview puzzles. It is also the subject of one of the quiz questions ahead, so make sure the limiter example below genuinely makes sense to you.

02. Functions and their parameters

A function declaration starts with function; an arrow function is a shorter expression form, (a, b) => ..., that suits small callbacks. Both take parameters. Two refinements make parameters flexible: a default parameter fills in a value the caller left out, and a rest parameter, written ...name, gathers all remaining arguments into a real array.

Every function returns a value: whatever follows return, or undefined if it never reaches one. A default can even be computed from earlier parameters, which reads like a small rule rather than a fallback:

JavaScript · params.js
function toCelsius(fahrenheit, precision = 1) {
  const celsius = ((fahrenheit - 32) * 5) / 9;
  return Number(celsius.toFixed(precision));
}

const roundAll = (...values) => values.map((v) => Math.round(v));

console.log(toCelsius(100));
console.log(toCelsius(100, 3));
console.log(roundAll(1.2, 2.7, 3.5));
Expected output
37.8
37.778
[ 1, 3, 4 ]

03. Functions as values

In JavaScript a function is a value like a number or a string. You can store it in a variable, put it in an array, pass it to another function and return it. A function that takes or returns one is called a higher-order function, and it is the mechanism behind map, filter and every setTimeout you will ever write: you hand over what to do, and the other code decides when to do it.

This is also where a famous bug lives. Array methods such as map call your function with more than one argument: the element, then its index, then the whole array. parseInt accepts a second argument, the numeric base to parse in. Pass parseInt straight to map and the index becomes the base:

JavaScript · higher-order.js
const applyTwice = (fn, value) => fn(fn(value));
const discount = (price) => Math.max(price * 0.9, 5); // 10% off, floor of 5

console.log(applyTwice(discount, 10));
console.log(applyTwice(discount, 4));

console.log(['1', '7', '11'].map(parseInt));
console.log(['1', '7', '11'].map((s) => parseInt(s, 10)));
Expected output
8.1
5
[ 1, NaN, 3 ]
[ 1, 7, 11 ]

The three strings were parsed in bases 0, 1 and 2: base 0 counts as "no base given", so parseInt falls back to its default (10, or 16 for strings that start with 0x), base 1 accepts nothing and base 2 reads 11 as binary three. The fix is the arrow on the last line: your own one-parameter function stands between the method and parseInt, so the index never arrives. When a callback gets extra arguments you did not expect, wrap it instead of passing it bare.

04. Scope is lexical

Scope answers the question "which names can this code see?". A variable declared with const or let exists in the block, the { ... }, where it was written, and in every block inside it. An inner block may declare a name that also exists outside; the inner one then shadows the outer one until its block ends.

The word lexical is the important part: scope is decided by where code is written, not by where it is run from. A function can see the variables of the place it was defined, no matter who calls it or when. Predict before running: which rate does convert use?

JavaScript · scope.js
const rate = 1.2; // module scope

const convert = (amount) => amount * rate; // reads "rate" where it was written

function outer() {
  const rate = 1.1; // shadows the outer "rate" inside this function only
  console.log(convert(100));
}

outer();
Expected output
120

The answer is 120: convert was written next to the rate of 1.2, so that is the rate it sees, even though outer has its own shadowing rate of 1.1 while the call happens. Lexical scope makes code readable — you can find the meaning of a name by looking at the source, not by tracing every caller.

Older code adds two more rules. The keyword var, used before let and const arrived in 2015, ignores blocks: a var belongs to the whole function around it, or to the whole script outside any function. Its declaration is also hoisted: it is processed before the function body runs, so the name exists from the first line, holding undefined until the assignment is reached.

let and const give no such early access. From the start of their block until their declaration runs, the name is in the temporal dead zone (TDZ), and reading it throws a ReferenceError. The error points at the bug instead of handing you a silent undefined. The attempt helper below prints either the value or the error, so each line shows what happens:

JavaScript · hoisting.js
const attempt = (read) => {
  try {
    console.log(read());
  } catch (error) {
    console.log(`${error.name}: ${error.message}`);
  }
};

function demo() {
  attempt(() => early); // var: the name exists from the top, holding undefined
  var early = 'set';
  attempt(() => early);

  if (true) {
    var leaked = 'var ignores the block';
    let kept = 'let stays in the block';
  }
  attempt(() => leaked);
  attempt(() => kept);

  attempt(() => late); // let: in the temporal dead zone until its line runs
  let late = 'set';
  attempt(() => late);
}

demo();
Expected output
undefined
set
var ignores the block
ReferenceError: kept is not defined
ReferenceError: Cannot access 'late' before initialization
set

Compare the two errors. Outside the if block, kept is not defined at all, while leaked escaped the block. Inside demo, late is a known name that cannot be accessed before initialization: that is the TDZ. Prefer const, use let when a value must change, and treat var as something to read, not to write.

05. Closures: state that outlives the call

Put the two ideas together and you get the closure. When a function is created, it keeps a reference to the scope around it. If that function escapes — being returned, stored, handed to a listener — its scope escapes with it: the variables it needs stay alive as long as the function does, private to it. That pairing of a function with the variables it captured is the closure.

Here is the pattern in a useful shape: a rate limiter that remembers how many permits have been taken. used is not a property anyone can read or reset from outside; the two returned methods are the only doors.

JavaScript · closure.js
function makeLimiter(max) {
  let used = 0; // private to makeLimiter, alive as long as the methods need it

  return {
    take() {
      if (used >= max) return false;
      used += 1;
      return true;
    },
    left: () => max - used,
  };
}

const tokens = makeLimiter(2);
console.log(tokens.take(), tokens.take(), tokens.take());
console.log(tokens.left());

const other = makeLimiter(2);
console.log(tokens.left(), other.left()); // each limiter has its own "used"
Expected output
true true false
0
0 2

Three calls to take, two successes, and used survives between them — it is not reset, because makeLimiter finished long ago; only its captured scope carries on. The last line is the detail that makes closures click: each call to makeLimiter runs the body again and creates a fresh used, so tokens and other count independently. The same mechanism powers a once() wrapper, a memoisation cache, and the counters and subscriptions inside event-driven code. Classes, coming later in this skill, are one answer to shared state; closures are the lighter one for a single private value.

Closures and var meet in a classic trap: functions created inside a loop. A for (let ...) loop gives each pass its own fresh copy of the loop variable, so a function created in the first pass keeps that pass's 0. A var loop variable is one variable for the whole function, so every function made in the loop closes over the same one and sees whatever value it holds when the function finally runs:

JavaScript · loop-closures.js
const withVar = [];
for (var i = 0; i < 3; i++) {
  withVar.push(() => i); // every arrow reads the one shared "i"
}

const withLet = [];
for (let j = 0; j < 3; j++) {
  withLet.push(() => j); // each pass of the loop has its own "j"
}

console.log(withVar.map((read) => read()));
console.log(withLet.map((read) => read()));
console.log(i); // var leaked out of the loop, with its final value
Expected output
[ 3, 3, 3 ]
[ 0, 1, 2 ]
3

The var arrows run after the loop has ended, when the shared i is 3, the value that made i < 3 false. The let arrows each captured a different j. The same happens with any callback that runs later, and timers are the everyday case: setTimeout(fn) does not call fn now, it schedules it. Even with no delay, the callback runs only after the code that is already running has finished, here the whole file:

JavaScript · timer.js
setTimeout(() => console.log('timer callback'));
console.log('first line done');
console.log('second line done');
Expected output
first line done
second line done
timer callback

So a timer started inside a loop fires after the loop is over, and reads the loop variable as it is at that moment. The async JavaScript skill explains the event loop behind this order.

06. Check your understanding

Practice check · 3 questions

Parameters, scope, captured state

Predict the output, or pick the explanation that matches the mechanism.

Q1. What does this log? function f(a, b = a * 2) { return a + b; } console.log(f(3), f(3, 1));
Q2. What does this log? const once = (fn) => { let done = false; return (...args) => { if (done) return 'already run'; done = true; return fn(...args); }; }; const start = once(() => 'started'); console.log(start(), start());
Q3. What does this log? const label = 'outer'; function pick() { return label; } function run() { const label = 'inner'; return pick(); } console.log(run());
Practice only: not graded, not saved, not evidence.

07. Apply it

The orders module this skill builds towards is a set of pure functions over a JSON array — functions in, value out. Prepare for it now:

  1. Write subtotal(items, { discount = 0, roundTo = 2 } = {}): the sum of qty * price with the discount subtracted and the result rounded to roundTo decimals. The braces unpack the options object into two variables, each with its own default (the next lesson covers this destructuring in full). The trailing = {} is a default for the whole options object: without it, calling subtotal(items) throws a TypeError, because there is no object to unpack. Call it three ways: no options, a discount only, and both.
  2. Write callTimes(n, fn) that returns a new function which calls fn and returns an array of the n results. It is a higher-order function; test it with Math.random.
  3. Write makeUuidPrefixer(prefix) that returns a function handing out prefix-1, prefix-2, ... with the counter in a closure. Create two prefixers and show that they count independently.

When you wire behaviour to clicks and keyboard events in the DOM and events skill, every listener you register will be a closure over the values it needs.

08. Review prompt

Without looking back: explain the difference between a parameter and an argument, and what ...values does in a parameter list. Then define "higher-order function" and give the reason map(parseInt) misbehaves. State what lexical scope promises, and describe in your own words what a closure captures and why two limiters made from the same makeLimiter never share state. Finally, say what hoisting does to a var, what the temporal dead zone is, and why arrows created in a var loop all return the same number.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check