⚡
Variable Scope and Hoisting
Beginner
80 XP
30 min
Lesson Content
Variable Scope and Hoisting
Scope determines where variables can be accessed in your code. Understanding scope is crucial for writing bug-free JavaScript.
Types of Scope
1. Global Scope
// Variables declared outside functions
let globalVar = 'I am global';
function myFunction() {
console.log(globalVar); // Can access
}
console.log(globalVar); // Can access everywhere2. Function Scope
function myFunction() {
let functionVar = 'I am in function scope';
console.log(functionVar); // Can access
}
// console.log(functionVar); // ERROR! Not accessible outside3. Block Scope (let, const)
if (true) {
let blockVar = 'I am in block scope';
const anotherVar = 'Me too';
console.log(blockVar); // Can access
}
// console.log(blockVar); // ERROR! Not accessible outside blocklet vs const vs var
- let - Block scoped, can be reassigned
- const - Block scoped, cannot be reassigned (but object properties can change)
- var - Function scoped, can be reassigned (avoid in modern JS)
Hoisting
JavaScript moves variable and function declarations to the top of their scope before execution.
// This works (function hoisting)
sayHello();
function sayHello() {
console.log('Hello!');
}
// This doesn't work (let/const not hoisted)
console.log(x); // ReferenceError
let x = 5;Best Practices
- Use
constby default - Use
letwhen you need to reassign - Avoid
var - Declare variables at the top of their scope
- Keep scope as narrow as possible
Example Code
Understand how scope affects variable access
// Global scope
const globalName = 'Global';
function outerFunction() {
// Function scope
const outerVar = 'Outer';
function innerFunction() {
// Inner function scope
const innerVar = 'Inner';
// Can access all outer scopes
console.log('Inner can see:', globalName, outerVar, innerVar);
}
innerFunction();
// Can access global and own scope
console.log('Outer can see:', globalName, outerVar);
// console.log(innerVar); // ERROR - not accessible
}
outerFunction();
// Block scope example
if (true) {
let blockVar = 'Block variable';
const blockConst = 'Block constant';
console.log('Inside block:', blockVar, blockConst);
}
// console.log(blockVar); // ERROR - not accessible outside blockExpected Output:
Inner can see: Global Outer Inner Outer can see: Global Outer Inside block: Block variable Block constant
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code