Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › JavaScript

JavaScript Scope and Closures

Scope — where a variable can be used

Scope Created by Variables
Global the file / script declared outside everything
Function every function var, let, const inside it
Block { } of if/for/while only let and const (not var)
let a = 1;                 // global
function outer() {
  let b = 2;               // function scope
  if (true) {
    let c = 3;             // block scope
    var d = 4;             // var ignores blocks → function scope
  }
  console.log(d);          // 4
  // console.log(c);       // ReferenceError
}

Lexical scope and the scope chain

A function can use variables from where it was written (its outer scopes), not from where it is called. JavaScript looks for a variable in the current scope, then the outer one, and so on up to global — the scope chain.

Closures

A closure is a function together with the variables from its outer scope that it remembers — even after the outer function has finished.

function makeCounter() {
  let count = 0;                 // stays alive inside the closure
  return function () {
    count++;
    return count;
  };
}
const c1 = makeCounter();
c1(); // 1
c1(); // 2
const c2 = makeCounter();
c2(); // 1  — each call to makeCounter creates a new `count`

Where closures are used

1. Data privacy (module pattern)

function createAccount(initial) {
  let balance = initial;                       // private
  return {
    deposit: (x) => (balance += x),
    getBalance: () => balance,
  };
}
const acc = createAccount(100);
acc.deposit(50);
acc.getBalance();   // 150 — `balance` can't be changed directly

2. Function factories

const multiplier = (n) => (x) => x * n;
const double = multiplier(2);
double(5);  // 10

3. Memoisation

function memoize(fn) {
  const cache = {};
  return (n) => (n in cache ? cache[n] : (cache[n] = fn(n)));
}

4. Event handlers, setTimeout, debounce and once

function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);   // `timer` is remembered between calls
  };
}
const onSearch = debounce((q) => console.log("search", q), 300);

The classic interview question

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// prints 3, 3, 3

var is function-scoped: there is one i, and by the time the callbacks run the loop has finished (i === 3).

Fixes

for (let i = 0; i < 3; i++) {                  // let: a new i for every iteration
  setTimeout(() => console.log(i), 100);       // 0, 1, 2
}

for (var i = 0; i < 3; i++) {
  ((j) => setTimeout(() => console.log(j), 100))(i);   // IIFE captures each value
}

Closures and memory

A closure keeps its outer variables alive. Large objects captured by long-lived callbacks (event listeners, intervals) are not garbage-collected — remove listeners and clear intervals when done.

Interview one-liners

More JavaScript notes