Scope in JavaScript: Types and Working Principles
What is Scope?
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.
Types of Scope
Global Scope
- Description: Variables declared in global context (outside all functions and blocks) are accessible throughout the code.
- Features:
- Pollutes global namespace, which can lead to conflicts.
- Use of global variables should be minimized.
var globalVar = "I am global"; // or let/const declared outside functions
function showGlobal() {
console.log(globalVar); // access to global variable
}
Function Scope
- Description: Variables declared inside a function are only accessible inside that function.
- Features:
- Function scope helps isolate variables and avoid conflicts between functions.
- Keyword
varhas function scope.
function example() {
var localVar = "I am local";
console.log(localVar); // accessible inside function
}
console.log(localVar); // ReferenceError: localVar is not defined
Block Scope
- Description: Variables declared with
letorconstinside a block (e.g., inside curly braces{}), are only accessible in that block. - Features:
- Allows limiting variable scope inside conditional constructs, loops and other blocks.
- Helps avoid errors related to variable redeclaration.
if (true) {
let blockVar = "I am block-scoped";
console.log(blockVar); // accessible inside block
}
console.log(blockVar); // ReferenceError: blockVar is not defined
Scope Working Features
- Lexical Scope: In JavaScript scope is determined at compile time (lexically), not at runtime. This means nested functions have access to outer function variables, even if called outside their parent function.
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
- Closures: Closure is a function that "remembers" its lexical scope, even when executed outside its original scope. This allows the function to use variables declared in its outer environment.
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.
Summary
Scope in JavaScript is divided into:
- Global scope: accessible throughout code.
- Function scope: accessible only inside function.
- Block scope: accessible inside specific block defined by curly braces.