Scope
A variable is not always available everywhere in your program. Some variables can be used anywhere, while others can only be used inside a function or a block.This is called Scope.
Types of Scope in JavaScript
Global Scope - A variable declared outside any function or block is called a Global Variable.It can be accessed from anywhere in the program.
Eg:
let name = "Pranay";
function greet() {
console.log(name);
}
console.log(name);
greet(); // Output:
Pranay
Pranay
Function Scope - Variables declared inside a function can only be used inside that function.
Eg:
function student() {
let age = 20;
console.log(age);
}
student(); // Output: 20
// If you try to access age outside the function
function student() {
let age = 20;
}
console.log(age); // Output: ReferenceError: age is not defined
// This happens because age exists only inside the function.
Block Scope - A block is anything inside curly braces { }.Variables declared using let and const inside a block can only be accessed within that block.
Eg:
if (true) {
let city = "Chennai";
console.log(city);
} // Output: Chennai
// Trying to access it outside the block
if (true) {
let city = "Chennai";
}
console.log(city); // Output: ReferenceError: city is not defined
- var - Function-scoped and not block-scoped.
- let and const - Block-scoped
Variable Hoisting
Hoisting means JavaScript processes declarations first, before running the program.
Hoisting - var and function
Non-Hoisting - let and const
Top comments (0)