Curriculum / Fundamentals / Lesson 08

Scope & Hoisting

How JavaScript resolves variables and what hoisting really means.

8 of 30
beginner 📖 6 min read 🎯 4 questions

What is Scope?

Scope determines where variables are accessible in your code. It's like a visibility zone — a variable declared inside a zone is only visible inside that zone and any nested zones.

💡 Real-world analogy Think of scope like rooms in a house. A variable in the living room is accessible from the living room, but not from the bedroom unless you bring it there.

Global Scope

Variables declared outside any function are in the global scope and accessible everywhere.

let globalVar = "I'm global";

function showGlobal() {
  console.log(globalVar); // accessible here
}
showGlobal();

Function Scope

Variables declared inside a function are function-scoped and only accessible within that function.

function myFunction() {
  let localVar = "I'm local";
  console.log(localVar); // works here
}
// console.log(localVar); // ReferenceError

Block Scope with let and const

let and const are block-scoped — they're only accessible within the nearest { } block.

if (true) {
  let blockScoped = "I'm in a block";
  const alsoBlockScoped = "Me too";
}
// console.log(blockScoped); // ReferenceError

What is Hoisting?

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. This means you can use variables and functions before they're declared.

Function Hoisting

Function declarations are fully hoisted — you can call them before they're defined.

sayHello(); // Works!

function sayHello() {
  console.log("Hello!");
}

Variable Hoisting with var

var declarations are hoisted but initialized as undefined.

console.log(x); // undefined (not an error)
var x = 5;
console.log(x); // 5

Temporal Dead Zone (TDZ)

let and const are hoisted but not initialized. Accessing them before declaration throws a ReferenceError.

console.log(y); // ReferenceError
let y = 10;

Common Mistakes

Quick Quiz

1. What is the output?
console.log(x); var x = 5;

2. What is the output?
console.log(y); let y = 5;

3. Which keyword creates block-scoped variables?

Summary

Back to curriculum