In JavaScript, scope controls where variables are accessible in your code. It helps avoid naming conflicts and bugs by defining which parts of the code can use a given variable.
{ }) when using let or const.A variable’s scope is determined by where it is declared:
let / const inside blocks (like if, for) → block scope.var is not block-scoped, only function-scoped.A variable is in global scope if it is declared outside any function or block. It can be accessed and modified from anywhere in the script.
let globalVar = "I am global";
function showGlobal() {
console.log(globalVar); // Accessible here
}
showGlobal();
console.log(globalVar); // Also accessible here
Variables declared inside a function (using var, let, or const) are only accessible within that function. They cannot be used outside it.
function myFunc() {
let localVar = "I am local";
console.log(localVar);
}
myFunc();
// console.log(localVar); // ❌ Error: localVar is not defined
With ES6, let and const introduced true block-level scope. A block is any code wrapped in { }, such as an if statement or loop.
if (true) {
let blockVar = "I exist only here";
const blockConst = "Same here";
console.log(blockVar);
}
// console.log(blockVar); // ❌ Error: blockVar is not defined
The choice between var, let, and const affects how variables are scoped:
var is function-scoped and can lead to confusing behavior inside blocks.let is block-scoped and can be reassigned.const is block-scoped and cannot be reassigned.
function testVarLet() {
if (true) {
var x = 10;
let y = 20;
}
console.log(x); // ✅ 10
// console.log(y); // ❌ Error: y is not defined
}
testVarLet();
showGlobal() and the last console.log print "I am global" because globalVar is accessible everywhere.localVar can be logged inside myFunc(), but trying to log it outside the function throws an error because it is not defined globally.blockVar and blockConst exist only inside the if block; accessing them outside causes an error.x (declared with var) is still accessible outside the if block, but y (declared with let) is not.let and const to avoid bugs related to var and hoisting.const by default and switch to let only when you need to reassign.var, let, and const inside an if block and test which ones are accessible outside the block.var with let or const and observe how the scope changes.