Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Scope is a part of code where variables and functions are accessible for use. In JavaScript, scope determines where you can reference variables, and plays a key role in memory management and preventing name conflicts.
var globalVar = "I am global"; // or let/const declared outside functions
function showGlobal() {
console.log(globalVar); // access to global variable
}
var has function scope.function example() {
var localVar = "I am local";
console.log(localVar); // accessible inside function
}
console.log(localVar); // ReferenceError: localVar is not defined
let or const inside a block (e.g., inside curly braces {}), are only accessible in that block.if (true) {
let blockVar = "I am block-scoped";
console.log(blockVar); // accessible inside block
}
console.log(blockVar); // ReferenceError: blockVar is not defined
function outer() {
let x = 10;
function inner() {
console.log(x); // x is accessible here thanks to lexical scope
}
return inner;
}
const innerFunc = outer();
innerFunc(); // 10
function counter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const increment = counter();
increment(); // 1
increment(); // 2
Important Note:
Scope determines where variables and functions are accessible in your code. Understanding its principles helps avoid errors and improve code readability.
Scope in JavaScript is divided into: