Understanding scope and hoisting is essential for writing predictable and bug-free JavaScript code. Scope determines where variables are accessible, and hoisting explains how variable and function declarations are processed.
This blog will cover all types of scope and explain hoisting with examples.
⭐ 1. What Is Scope in JavaScript?
Scope defines the accessibility of variables and functions in different parts of your code.
There are three types:
✔ Global Scope
Variables declared outside functions are global and accessible everywhere.
✔ Local (Function) Scope
Variables declared inside a function are accessible only inside that function.
✔ Block Scope (ES6)
Variables declared with let or const inside {} are accessible only inside that block.
⭐ 2. Examples of Scope
Global Scope
let name = "Sagar";
function greet() {
console.log(name); // Accessible
}
greet();
console.log(name); // Accessible
Function Scope
function myFunction() {
let age = 22;
console.log(age); // Accessible
}
myFunction();
console.log(age); // Error: age is not defined
Block Scope
if (true) {
let city = "Ludhiana";
const country = "India";
var state = "Punjab"; // var is function-scoped, not block-scoped
}
console.log(city); // Error
console.log(country); // Error
console.log(state); // Accessible
⭐ 3. What Is Hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top of the scope during compilation.
- Variables declared with
varare hoisted and initialized withundefined. - Variables declared with
letorconstare hoisted but not initialized (temporal dead zone). - Function declarations are fully hoisted.
⭐ 4. Examples of Hoisting
Variable Hoisting
console.log(a); // undefined
var a = 5;
let/const Hoisting
console.log(b); // Error: Cannot access 'b' before initialization
let b = 10;
Function Hoisting
greet(); // Hello from hoisted function
function greet() {
console.log("Hello from hoisted function");
}
⭐ 5. Why Scope & Hoisting Matter
- Prevent accidental global variables
- Avoid bugs with undefined values
- Ensure proper variable access
- Write cleaner, predictable code
⭐ Conclusion
Scope and hoisting are fundamental concepts in JavaScript. Knowing them helps you manage variable accessibility, avoid unexpected behavior, and debug errors efficiently.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/