Why Does JavaScript Scope Really Matter?

Let’s not get into an argument about definitions again… from the dictionary:

Scope: “the extent of the area or subject matter that something deals with” and “the opportunity or possibility to do or deal with something”.

Encapsulation: “the action of enclosing something in or as if in a capsule”.

As you can see and is often the case with definitions, the meanings of scope and encapsulation are quite similar to each other, and they also overlap.

The names you choose for the variables, functions, and classes in your program, are only visible in certain parts of your program. The parts (i.e. areas; blocks) of your program within which any such element is visible (i.e. accessible) is known as the element’s scope (i.e. context).

Typically in programming languages, you’ll have scope such as…

Conceptually, we can simply think of scopes as being locally accessible regions within our program. Therefore scopes can overlap. For example, block scope can exist locally inside function scope like this…

function myFunc() {
	let var1 = 25;

	for (x = 1; x < 5; ++x) {
		let var2 = 50;
		console.log(var1 + var2); // OK
	console.log(var1 + var2); // Error: var2 is not defined