The scope in JavaScript is a region of your code where a variable can be accessed. JavaScript has two types of scope – global scope and local scope.
A variable declared outside a function becomes a global variable and it represents global scope. This variable can be accessed from any part of the code.
let globalVar = "I am a global variable";
function checkScope() {
console.log(globalVar); // "I am a global variable"
}
checkScope();
A variable that is declared inside a function becomes a local variable, and it represents local scope. This variable can only be accessed within the function it was declared.
function checkScope() {
let localVar = "I am a local variable";
console.log(localVar); // "I am a local variable"
}
checkScope();
console.log(localVar); // Error: localVar is not defined
With ES6, JavaScript got a new type of scope, called block scope. Variables declared with let and const are block scoped, which means they are only accessible within the block they were declared.
if(true){
let blockVar = "I am a block variable";
console.log(blockVar); // "I am a block variable"
}
console.log(blockVar); // Error: blockVar is not defined