JavaScript Scope and Scope Chain Explained
Scope determines where variables are accessible and can be referenced within your code.
In JavaScript, scope can be divided into three types: global, function, and block scope.
-
Global scope refers to the execution environment created when JavaScript code begins running. Variables defined outside of any function or block belong to the global scope. These global variables can be accessed from anywhere in your code.
-
Function scope refers to the environment created by a function declaration. Variables defined inside a function are only accessible within that function and any nested functions. They cannot be accessed from outside the function where they’re declared.
-
Block scope was introduced in ES6 and is defined within a pair of curly braces
{}
. Note that only variables declared withlet
andconst
respect block scope. Variables declared withvar
only have function scope and ignore block boundaries.
The scope chain describes how JavaScript looks up variables during execution. When code references a variable, JavaScript first searches for it in the current scope. If not found, it continues searching upward through parent scopes until reaching the global scope. If the variable isn’t found in the global scope, JavaScript throws a reference error. This hierarchical lookup process forms the scope chain.
You can see the scope chain in action through this example:

In this example, when the find()
function tries to access variable a
, it doesn’t find it in its local scope. JavaScript then looks up the scope chain and finds a
in the global scope, successfully logging the value 100
.
Reference
What Is the Scope and Scope Chain of JavaScript?| ExplainThis