AdvancedLesson 21 of 305 min read

Scope, hoisting and closures

Understand where variables live, how JavaScript looks them up, and how closures give functions a private memory.

In this lesson you will

  • Describe global, function and block scope
  • Explain the scope chain and shadowing
  • Understand hoisting
  • Use closures for private state

About 20 minutes

Where does a variable live, and how long?

In the functions lesson you learned that a variable made inside a function stays inside it. That idea has a name, scope, and it is one of the most important concepts in JavaScript. Understanding it is the difference between code that works by luck and code you can reason about. And scope leads directly to closures, a feature that sounds mysterious but is really just a function that remembers where it was born.

The three kinds of scope

const site = "Skills in Minutes";       // global scope

function show() {
  const topic = "Closures";              // function scope
  if (true) {
    const detail = "Block scope";        // block scope: only inside { }
    let counter = 1;
  }
  console.log(site, topic);              // both visible here
  // console.log(detail);                // ReferenceError: not defined
}
show();
  • Global scope: declared outside everything. Visible everywhere. Use sparingly.
  • Function scope: visible only inside the function.
  • Block scope: let and const inside any pair of curly braces (an if, a for) stay inside those braces.

Think of scope as a set of rooms. Code can look out of its own room into the rooms around it, but never into a room next door.

The scope chain

const a = "outer";

function one() {
  const b = "middle";
  function two() {
    const c = "inner";
    console.log(a, b, c);    // looks outward: c, then b, then a
  }
  two();
}
one();

When JavaScript meets a name, it looks in the current scope first, then the scope around it, then the one around that, until it reaches the global scope. This outward search is called the scope chain. An inner variable with the same name hides an outer one; this is called shadowing.

Predict what each line prints before pressing Run. Which x does each console.log see?

const x = 'global';
function test() {
  const x = 'function';
  if (true) {
    const x = 'block';
    console.log(x);
  }
  console.log(x);
}
test();
console.log(x);

Each x lives in its own room. The innermost one wins inside its room.

const x = 'global';
function test() {
  const x = 'function';
  if (true) {
    const x = 'block';
    console.log(x);   // block
  }
  console.log(x);     // function
}
test();
console.log(x);       // global

var versus let and const

for (var i = 0; i < 3; i++) {}
console.log(i);        // 3: var leaks out of the block

for (let j = 0; j < 3; j++) {}
// console.log(j);     // ReferenceError: let stays inside

var ignores block scope and is visible throughout the whole function, which causes surprising bugs. That is one more reason to use let and const.

Hoisting

console.log(greet());      // works: "Hello"
function greet() { return "Hello"; }

// console.log(age);       // ReferenceError (Temporal Dead Zone)
let age = 30;

console.log(old);          // undefined, not an error!
var old = 5;

Before running, JavaScript scans the code and registers declarations. Function declarations are fully available early. Variables made with let and const are registered but locked until their line runs (the “temporal dead zone”), so using them early is an error, which is helpful. var variables start as undefined. The practical rule is simple: declare things before you use them.

Closures: a function that remembers

Here is the surprising part. When a function is created inside another function, it keeps access to the variables around it, even after the outer function has finished. That remembered environment is a closure.

function makeCounter() {
  let count = 0;                 // private to makeCounter
  return function () {
    count++;
    return count;
  };
}

const counterA = makeCounter();
const counterB = makeCounter();

console.log(counterA());   // 1
console.log(counterA());   // 2
console.log(counterB());   // 1  (its own separate count)

When makeCounter finished, you might expect count to vanish. It does not, because the returned function still uses it. Nothing outside can touch count directly. That makes closures the standard way to create private data in JavaScript.

Write makeGreeter(greeting) that returns a function taking a name and returning the greeting plus the name. Create two greeters and use them.

function makeGreeter(greeting) {
  // return a function that remembers greeting
}
const hello = makeGreeter('Hello');
const salaam = makeGreeter('Salaam');
console.log(hello('Sara'));
console.log(salaam('Ali'));

return function (name) { return greeting + ‘, ‘ + name + ‘!’; };

function makeGreeter(greeting) {
  return function (name) {
    return greeting + ', ' + name + '!';
  };
}
const hello = makeGreeter('Hello');
const salaam = makeGreeter('Salaam');
console.log(hello('Sara'));
console.log(salaam('Ali'));

What closures are used for

  • Private state: counters, caches and settings no outside code can break.
  • Function factories: build customised functions, like the greeter above.
  • Event handlers and timers: callbacks remember the variables around them.
  • Debounce and once: helpers that need memory between calls.
function once(fn) {
  let done = false, result;
  return function (...args) {
    if (!done) { result = fn(...args); done = true; }
    return result;
  };
}
const init = once(() => { console.log("Setting up..."); return 42; });
console.log(init());   // runs: Setting up... 42
console.log(init());   // 42, without running again

The classic loop puzzle

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// prints 4 4 4 : one shared i, already 4 when the timers fire

for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log(j), 100);
}
// prints 1 2 3 : each round gets its own j

Run both loops. Then fix the var version without changing var to let, by wrapping the timer in a function that receives i as a parameter.

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log('var', i), 100);
}
for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log('let', j), 200);
}

Use an immediately-invoked function: (function (n) { setTimeout(() => console.log(n), 100); })(i);

for (var i = 1; i <= 3; i++) {
  (function (n) {
    setTimeout(() => console.log('fixed', n), 100);
  })(i);
}
for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log('let', j), 200);
}
Common mistake

Creating accidental globals by forgetting the keyword: total = 5 instead of let total = 5. In sloppy mode this silently makes a global that any code can overwrite. Add "use strict"; at the top of a file (modules are strict automatically) so JavaScript reports it as an error.

Keep scope small

Declare each variable in the smallest room that needs it. Fewer places can touch it, so fewer places can break it. That one habit prevents a surprising number of bugs.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Where is a const declared inside an if { } block visible?

  1. Anywhere in the file
  2. Only inside that block
  3. Only in functions
  4. Nowhere

let and const are block-scoped.

What is a closure?

  1. A way to close the browser
  2. A loop
  3. A kind of array
  4. A function that remembers the variables from where it was created

It keeps access to its surrounding scope.

What does console.log(x); var x = 5; print?

  1. undefined
  2. 5
  3. ReferenceError
  4. null

var is hoisted and starts as undefined.

Why do three makeCounter() counters not interfere?

  1. They share one count
  2. JavaScript resets them
  3. Each call creates its own count variable
  4. They use globals

Every call makes a fresh environment.

What is variable shadowing?

  1. Deleting a variable
  2. A CSS effect
  3. A global variable
  4. An inner variable hiding an outer one with the same name

The inner name wins in its scope.

Summary

  • let and const are block-scoped; var is not.
  • Lookups travel outward along the scope chain.
  • Declare before you use.
  • A closure is a function plus the variables it remembers.

Next lesson

Next: this, and how to control it with call, apply and bind.

Questions

Are closures bad for memory?

Not normally. A closure only keeps what it uses. Problems appear only if you hold huge data in a closure that lives for a long time.

Should I ever use var?

In new code, no. let and const are clearer and safer.

What is an IIFE?

An immediately invoked function expression, written (function(){ ... })(). It creates a private scope and runs at once. Modules have mostly replaced it.

Progress is saved in this browser.