JavaScript creation date: update date:

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.

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