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.
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
- Assuming
letandconstare not hoisted (they are, but in the TDZ) - Accidentally creating global variables by omitting
let,const, orvar - Expecting
varto be block-scoped (it's function-scoped)
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
- Global scope: accessible everywhere
- Function scope: variables declared with
varare function-scoped - Block scope:
letandconstare block-scoped - Hoisting: declarations are moved to the top of their scope
- Function declarations are fully hoisted
varis hoisted but initialized asundefinedletandconstare in the Temporal Dead Zone until declared
