Lexical Scope in JavaScript

Scope is a fundamental concept present in all programming languages, defining the area within a program where a specific variable can be utilized and modified. It plays a crucial role in managing variables effectively by controlling their accessibility. The primary purpose of scope is to regulate the visibility and lifespan of variables to prevent unintended modifications or conflicts.

Types of Scope:

The primary scope categories in programming languages consist of lexical scope, global scope, as well as local, nested, and block scope.

What is Lexical Scope in JavaScript?

The common phrase for describing lexical scope is static scope, which is established during compilation and is based on the structure of the program. In essence, it refers to lexical scope, where a variable is defined within the code itself. The position in the source code dictates its lexical scope and remains constant throughout all executions.

The term lexical scope is used to describe variables and function accessibility depending on where they are within the source. It can be said that the scope for variables and functions exists at various levels such as:

  • Global Scope: Global Scope variables that are declared outside any function or block are of global scope and can be used anywhere in the program.
  • Local Scope: Local Scope variables that are declared inside a function or block can be accessed only in that particular function or block.
  • Nested Scope: Inner functions can also use the variables that are defined inside the parent functions.
  • Block Scope: Variables declared with let and const are accessible only within the block in which they were defined, such as within loops or if statements.

As illustrated in the diagram provided, it is clear that functions have access to variables within their containing scopes through lexical scoping, reaching up to the global scope. However, variables defined within functions are not accessible to any outer scopes.

This guide aims to elucidate the concept of lexical scope in JavaScript, accompanied by numerous code snippets to demonstrate its functionality.

Global Scope

A variable that is defined outside of any functions or blocks is said to have a global scope, which means it is accessible from any part of the program, including inside functions.

In this illustration, the variable "name" is defined outside of any functions or blocks, categorizing it as a global variable. Consequently, the function provided in the example is capable of retrieving the "name" variable and displaying "Hello World" on the console.

Example

let name = "Example"; // Global variable
function example() {
      console.log("Hello " + name);
}
example(); // Output: "Hello World"

Output

Local Scope

A variable that is defined within a function or a specific block is said to have a local scope. This indicates that the variable can only be accessed within that particular function or block.

In this instance, the variable "name" is defined as a local variable within the "main" function. It is accessible within the function scope, but attempting to access it outside of the function will trigger a "ReferenceError."

Example

function main() {
      let name = "Example"; // Local variable
      console.log("Hello " + name);
}
main(); // Output: "Hello World"
console.log(name); 
// Output: Uncaught ReferenceError: name is not defined

Output

Nested Scope

This functionality enables the declaration of a variable within a different function, making the variables declared in the outer function accessible from the inner function. This concept is referred to as nested scope.

In this instance, the inner function is created inside the outer function. The inner function has access to the variable called name that is defined in the outer function, leading to the display of "Hello WEBSITE" in the console.

Example

function nested() {
    let name = "WEBSITE"; // Outer function variable
    function inner() {
        console.log("Hello " + name);
    }
    inner(); // Output: "Hello WEBSITE"
}
nested();

Output

Block Scope

The introduction of the keywords let and const in ES6 enables the definition of variables with block scope. This means that variables declared within a specific block of code, such as an if statement or a for loop, are limited in scope to only that particular block.

In this instance, the variable message is confined to a block scope. It is solely accessible within the confines of the if block. Any effort to reach it beyond that specific block will result in a "ReferenceError" being triggered.

Example

function reference() {
    if (true) {
        let wish = "Hello"; // Block variable
        console.log(wish + " " + name); 
        // Output: "Hello Yshakan"
    }
    console.log(wish); 
    // Output: ReferenceError: 
    // wish is not defined
}
reference();

Output

Conclusion

The concept of lexical scope in JavaScript pertains to how variables and functions are accessed within nested functions. In JavaScript, a variable or function defined in a nested function can access variables and functions from its containing or parent function, but not the other way around. This is due to the design of the scope chain, which allows access to move only upwards from a child function to its parent, not in the reverse direction. The inner function establishes a lexical link to its parent function, enabling it to access variables and functions declared in the parent's scope at the moment the inner function is created.

Input Required

This code uses input(). Please provide values below: