Skills101

AdvancedWeb Development · Lesson 13 of 13 · Updated ·

JavaScript Scope, Closures, Hoisting and this — Explained with Examples

Four ideas confuse more JavaScript learners than anything else: scope, closures, hoisting and this. They also appear in almost every frontend interview, usually as "what does this code print?". Once you understand the rules below, those questions become easy. Every example runs with node file.js.

1. Scope: where a variable can be used

Scope is the region of code where a variable is visible. JavaScript has three kinds:

ScopeCreated byWho uses it
Globalcode outside any function or blockeverything
Functionevery functionvar, let, const declared inside it
Blockany { } — if, for, whileonly let and const
const college = "NIT Jaipur";          // global

function showStudent() {
  const name = "Asha";                 // function scope
  if (true) {
    let marks = 91;                    // block scope
    var city = "Jaipur";               // var ignores the block!
    console.log(name, marks, college);
  }
  console.log(city);                   // works: var is function-scoped
  console.log(typeof marks);           // marks does not exist here
}
showStudent();
Asha 91 NIT Jaipur
Jaipur
undefined

typeof is used on the last line because reading marks directly outside its block would throw a ReferenceError.

The scope chain

When code uses a variable, JavaScript looks in the current scope first. If it is not there, it looks in the enclosing scope, then the next one out, until it reaches the global scope. If the name is still not found, you get a ReferenceError. This lookup path is the scope chain.

Three nested boxes: global scope holds college, function showStudent holds name, the if block holds marks; a lookup for college starts in the block and moves outward until it is found in the global scope

The lookup only goes outward, never inward: a function can read its parent's variables, but the parent cannot read the function's.

An inner variable with the same name shadows (hides) the outer one:

const level = "global";
function test() {
  const level = "function";
  console.log(level);
}
test();
console.log(level);
function
global

2. Closures: functions that remember

A closure is a function together with the variables from the scope where it was created. The function keeps those variables alive even after the outer function has finished.

function makeWallet(owner) {
  let balance = 0;                       // private: nothing outside can touch it directly
  return {
    add(amount) { balance += amount; return balance; },
    show() { return `${owner} has ₹${balance}`; },
  };
}

const asha = makeWallet("Asha");
const ravi = makeWallet("Ravi");
asha.add(500);
asha.add(250);
ravi.add(100);
console.log(asha.show());
console.log(ravi.show());
console.log(asha.balance);
Asha has ₹750
Ravi has ₹100
undefined

Two important points:

  • Each call to makeWallet creates a new balance. Asha's and Ravi's wallets do not share it.
  • balance is not a property of the returned object, so asha.balance is undefined. The only way to change it is through add. Closures give JavaScript private data.

Closures are everywhere: event handlers remember variables, React hooks rely on them, and functions like debounce and once are built with them.

function once(fn) {
  let done = false;
  return (...args) => {
    if (done) return "already paid";
    done = true;
    return fn(...args);
  };
}
const pay = once((amount) => `paid ₹${amount}`);
console.log(pay(999));
console.log(pay(999));
paid ₹999
already paid

A "Pay" button that uses once cannot charge a customer twice, even if they double-click.

3. Hoisting and the temporal dead zone

Before running a scope, JavaScript first registers every declaration in it. This is called hoisting. What you get if you use a name before its line depends on how it was declared:

DeclarationBefore its line you get
function f() {}the whole function — you can call it
var x = 5undefined (declared, not yet assigned)
let / constReferenceError (the temporal dead zone)
console.log(greet("Neha"));
function greet(name) { return `Hi ${name}`; }

console.log(score);
var score = 80;

try {
  console.log(total);
  let total = 100;
} catch (err) {
  console.log(err.name);
}
Hi Neha
undefined
ReferenceError

The temporal dead zone (TDZ) is the time between the start of the block and the line where a let or const is declared. The variable exists but cannot be touched. This is a feature: it turns a silent undefined bug into a clear error.

4. The classic interview question: var in a loop

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}
var: 3
var: 3
var: 3
let: 0
let: 1
let: 2

With var there is one shared i; the loop finishes and i becomes 3 before any timer runs, so all three callbacks print 3. With let each iteration gets its own j, so the callbacks print 0, 1 and 2

Why?

  • The timers run after the loop has finished (remember the event loop).
  • var i is one variable for the whole function. By the time the callbacks run, it is 3, and all three closures see that same i.
  • let j creates a new binding for each iteration. Each callback closes over its own j.

The fix is simply to use let. This one example tests scope, closures and the event loop together — which is why interviewers love it.

5. The this keyword

this is not decided by where a function is written. For normal functions it is decided by how the function is called:

How it is calledthis is
obj.method()obj (the object before the dot)
fn() on its ownundefined in strict mode (modules, classes); the global object otherwise
new Fn()the new object being created
fn.call(x) / fn.apply(x) / fn.bind(x)x
arrow functionno own this — it uses this from the surrounding code
"use strict";
const course = {
  title: "React",
  normal() { return this?.title; },
  arrowInside() {
    const inner = () => this.title;      // arrow takes this from arrowInside
    return inner();
  },
};

console.log(course.normal());
const detached = course.normal;
console.log(detached());
console.log(course.arrowInside());
const bound = course.normal.bind({ title: "Node" });
console.log(bound());
React
undefined
React
Node

detached() is called on its own, with no object before the dot, so this is undefined. The same function behaves differently depending on the call. This is the source of "this is undefined" bugs when you pass a method as a callback; fix it with an arrow function or bind.

Common mistakes

  • Using var and expecting block scope.
  • Expecting this inside a method that you passed as a callback to still be the object.
  • Using an arrow function as an object method and then expecting this to be the object.
  • Thinking closures copy values. They keep a reference to the variable, so they see later changes.

Quick recap

  • Scope = where a variable is visible: global, function, block (let/const only).
  • Lookup walks the scope chain outward; inner names shadow outer ones.
  • A closure is a function plus the variables of the place it was created; use it for private state.
  • Hoisting: functions are fully available, var is undefined, let/const are in the TDZ.
  • var in a loop shares one variable; let gives each iteration its own.
  • this depends on the call (obj.method(), new, bind); arrow functions borrow it.

Practice what you learned

📝 Quiz: Scope, Closures, Hoisting and this5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →