Scope in JavaScript
Scope refers to the context in which variables are declared and can be accessed. JavaScript has function and block scope (introduced with let and const).
Function Scope
Variables declared with var are function-scoped, meaning they are accessible within the function where they are defined.
function foo() {
var x = 10;
console.log(x);
}
foo(); // Output: 10
console.log(x); // Error: 'x' is not defined
Block Scope
Variables declared with let and const are block-scoped, meaning they are limited to the block in which they are defined (e.g., inside loops or conditionals).
if (true) {
let y = 5;
console.log(y);
}
console.log(y); // Error: 'y' is not defined
Closures in JavaScript
Closures are functions that remember the environment in which they were created, including variables from their outer scopes.
function outerFunction() {
let outerVar = 'I am from outerFunction';
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
let innerFunc = outerFunction();
innerFunc(); // Output: I am from outerFunction