Scope determines the accessibility (visibility) of variables. In JavaScript, there are different types of scope:
let
and const
)Variables declared outside any function are in the global scope and accessible anywhere in the code.
let globalVar = "Hello";
function sayHello() {
console.log(globalVar); // Accessible here
}
Variables declared inside a function are only accessible within that function.
function testScope() {
let localVar = "I am local";
console.log(localVar); // Works
}
console.log(localVar); // โ Error: not defined
let
& const
)Variables declared with let
or const
inside { }
are limited to that block.
{
let blockVar = "Inside block";
console.log(blockVar); // โ
Works
}
console.log(blockVar); // โ Error
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!