**Scope** is the region of code where a variable is accessible. JavaScript has: **global scope** (window/globalThis), **function scope** (inside a function), and **block scope** (inside `{}`with let/const). **Lexical scope** means scope is determined by where code is written, not where it runs. **Context** is `this` — determined by how a function is called.
1Understanding Scope & Context
Scope is the region of code where a variable is accessible. JavaScript has: global scope (window/globalThis), function scope (inside a function), and block scope (inside {}with let/const). Lexical scope means scope is determined by where code is written, not where it runs. Context is this — determined by how a function is called.
Scope is lexical (static) — set at write time. Context (this) is dynamic — set at call time. Arrow functions unify them by using lexical 'this'.
// Scope chain: inner can access outer
const global = 'global';
function outer() {
const outerVar = 'outer';
function inner() {
const innerVar = 'inner';
// Can access: innerVar, outerVar, global
console.log(innerVar, outerVar, global);
}
inner();
// Can access: outerVar, global (NOT innerVar)
}
outer();2Practical Example
Here is a real-world application of Scope & Context showing how it is used in production JavaScript code.
// Block scope
let x = 1;
{
let x = 2; // different x!
console.log(x); // 2
}
console.log(x); // 1
// No block scope with var
var y = 1;
{
var y = 2; // SAME y!
console.log(y); // 2
}
console.log(y); // 2 (changed!)3Best Practices
Follow these guidelines when working with Scope & Context:
1. Minimize global scope pollution
2. Use closures for privacy
3. Understand lexical scope for debugging closure issues
Tip: Scope is lexical (static) — set at write time. Context (this) is dynamic — set at call time. Arrow functions unify them by using lexical 'this'.
// Scope chain: inner can access outer
const global = 'global';
function outer() {
const outerVar = 'outer';
function inner() {
const innerVar = 'inner';
// Can access: innerVar, outerVar, global
console.log(innerVar, outerVar, global);
}
inner();
// Can access: outerVar, global (NOT innerVar)
}
outer();