Scope refers to the area in a program where variables are defined, determining where these variables can be accessed and used. Scopes in JavaScript include global scope, function scope and block-level scope.

1. What is scope?

Scope is the area in code where a variable is defined and determines its visibility and lifetime. Scope specifies which parts of a program can access a variable and where the variable is available.

The biggest role of scope is to isolate variables.

2. Global scope and function scope

  • Global Scope : Global scope is a scope that can be accessed from anywhere in the code. Variables declared in the global scope have global scope and can be accessed from anywhere in the code.
let globalVar = 10;

function test() {
    console.log(globalVar); // 
}
  • The outermost function and variables defined outside the outermost function have global scope.
  • All variables that are not defined for direct assignment are automatically declared to have global scope
  • All properties of the window object have global scope

The big drawback of global scope is global pollution. So this is why the source code of libraries such as jQuery is placed in immediate execution functions.

  • Function scope : Function scope refers to the scope in which variables declared inside a function can only be accessed within that function. Variables declared inside the function cannot be accessed outside the function.
function test() {
    let localVar = 20;
    console.log(localVar); // 
}

console.log(localVar); // 

It is worth noting: block statements (statements between curly brackets “{)”), such as if and switch conditional statements or for and while loop statements, unlike functions, they do not create a new scope. Variables defined within a block statement will remain in the scope in which they already exist.

3. Block-level scope

Block-level scope was introduced in ES6, and variables declared using the letand keywords have block-level scope. constBlock-level scope means that variables declared inside a code block (such as ifforwhile{}etc.) are only visible inside the code block.

if (true) {
    let blockVar = 30;
    console.log(blockVar); // 
}

console.log(blockVar); // 

scope chain

A scope chain is a chain structure used to find and resolve variable identifiers.

1. What is a free variable?

Free variables are variables that are not declared but are referenced (used) in the current function scope.

When the JavaScript engine cannot find a variable in the current scope, it looks up the scope chain until it finds the variable. If the variable is not found in the global scope, then the variable is a free variable.

let globalVar = 'Global Variable';

function outerFunction() {
    let outerVar = 'Outer Variable';

    function innerFunction() {
        console.log(outerVar); // 
        console.log(globalVar); // 
    }

    innerFunction();
}

outerFunction();

In the above example, and innerFunctionare referenced internally , but neither variable is declared in the function scope, so they are both free variables.outerVarglobalVar

2. What is scope chain?

A scope chain is a dynamic data structure in JavaScript used to resolve identifier references. When the JavaScript engine encounters a variable reference, it looks up the scope chain until it finds the corresponding variable or reaches the global scope. The scope chain is a chain structure composed of variable objects of the current execution environment and variable objects of all external environments.

3. Regarding the values ​​of free variables

When the JavaScript engine cannot find a variable in the current scope, it looks up the scope chain. If the corresponding variable is found in an environment of the scope chain, the value of the variable is used; if the corresponding variable is still not found at the top of the scope chain (global scope), a ReferenceError will be thrown.

It is not accurate to find this statement from superiors (or parents).

let x = 10
function fn() {
    console.log(x)
}
function show(f) {
    let x = 20
    ;(function () {
        f()  // 
    })()
}
show(fn)

The value of the free variable must be obtained in the scope of the function that created fn, no matter where fn is called.

This is called “static scope”. The values ​​in the scope are already stored when the function is created and are static.

Scope and execution context

JavaScript is an interpreted language, and the execution of JavaScript is divided into two stages: interpretation and execution.

Interpretation stage:

  • lexical analysis
  • Gramma analysis
  • Scope rules determined

Execution phase:

  • Create execution context
  • Execute function code
  • Garbage collection

The execution context is determined at runtime and may change at any time, whereas the scope is determined at definition time and does not change.

Leave a Reply

Your email address will not be published. Required fields are marked *