Mastering Scope in JavaScript

Demystifying Lexical Environments for Proper Encapsulation

Max N
2 min readFeb 16, 2024

Understanding scope in JavaScript is key for writing reliable code that properly accesses variables and functions across execution contexts.

In this article we’ll clarify scoping rules around lexical environments, closures, and the global object to boost encapsulation skills.

Lexical Scoping Primer

First recall functions create new scopes in JavaScript:

function calculate() {

const x = 2;

}

console.log(x); // ReferenceError

The x variable only exists within calculate block — this lexical scoping makes scope depend on locations in code rather than runtime calling contexts.

Nested scopes chain, allowing inner functions to access outer variables:

function outer() {

const outerVar = '123';

function inner() {
console.log(outerVar); // Works!
}

inner();

}

Here inner accesses outerVar due to lexical chaining, despite outer function already returning when inner executes.

Closure Captures Variables

We can leverage scope chaining for closure capturing:

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.