Scope and The Scope Chain in JavaScript
Scope and The Scope Chain in JavaScript
1. Global Scope: Variables or functions declared in the global scope are accessible
from anywhere in the code. This means they are available throughout your JavaScript
files.
2. Local (or Function) Scope: Variables or functions declared within a function are
accessible only within that function and not from outside it. This includes
variables declared with `var` within a function.
With the introduction of ES6 (ECMAScript 2015), two new types of scope were
introduced with the `let` and `const` keywords:
3. Block Scope: Variables declared with `let` or `const` are scoped to the block
(`{}`) in which they are defined, as well as in any contained sub-blocks. This
allows for more precise control over where variables are accessible.
function checkScope() {
console.log(globalVar); // Accessible here
}
function localScope() {
var localVar = 'I am in the local scope';
console.log(localVar); // Accessible here
}
function blockTest() {
if (true) {
let blockVar = 'I am in a block';
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
}
blockTest();
The Scope Chain in JavaScript is a concept used to explain how child scopes have
access to variables defined in their parent scopes, forming a "chain" of scopes.
When a variable is used, the JavaScript engine looks up the scope chain to find the
variable's value, starting from the current scope and moving outwards until it
reaches the global scope. If the variable is not found, a `ReferenceError` is
thrown.
The scope chain is created based on the lexical scoping of the code, meaning the
structure of the code itself determines the scope chain at the time the code is
written.
function outerFunction() {
var outerVar = 'outer';
function innerFunction() {
var innerVar = 'inner';
console.log(innerVar); // inner
console.log(outerVar); // outer
console.log(globalVar); // global
}
innerFunction();
}
outerFunction();
Understanding scope and the scope chain is crucial for managing variable visibility
and lifetimes, debugging code, and writing efficient, error-free JavaScript
applications.