What Is the Scope and Scope Chain of JavaScript?

What is Scope?

Scope, as the name suggests, refers to the range that a variable can be accessed. There are three types of scope in JavaScript: global scope, function scope, and block scope. According to MDN, the scope is the current execution context in which values and expressions are "visible" or can be referenced. In other words, if a variable or expression is not in the current scope, it cannot be accessed.

JavaScript has three types of scope:

  • Global Scope: When JavaScript code is executed, a global execution context will be created. Variables defined outside the function or block level will belong to the global scope. These variables is known as Global variable and can be used anywhere. The value of variable a in the following example is a global variable in the global scope.

    var a = 'global scope';
    function call() {
      console.log(a); // global scope
      a = 'Hello Global Scope~~';
    console.log(a); // Hello global scope~~
  • Function Scope: the scope created by function

    function scope() {
      let a = 'function scope';
      console.log(a); // function scope
    // a is not accessible here because a is function scoped
  • Block Scope: Introduced in ES6, block scope is defined in a block level. It should be noted that only variables declared by let and const will have to block-level scope, and variables defined by var will have function scope. As in the following example, in the if condition, variable a has a block scope but b has a function scope.

    function checkScope() {
      if (true) {
        let a = 'block scope';
        var b = 'function scope';
      } else {
        // The variable a has a block scope in the if statement, so it is not accessible here
        // The variable b has a function scope and is accessible here
        console.log(b); // function scope
      // a is not accessible here, b is accessible here since it's still in the function
    // a,b are not both accessible here

What is a scope chain?

Scope chain is a mechanism in JavaScript to resolve the value of variable names. The process of resolving a variable value is like a chain, so we call it scope chain

The scope chain starts with the innermost (or local) scope. If the variable cannot be found in the current scope, it will keep looking for the variable in the parent scope and all the way up to the global scope. If it's still not found in the global scope, an error will be thrown directly.

In a scope chain, if a variable with the same name is declared in multiple scopes, the innermost (or local) declaration takes precedence.

let a = 100;
function find() {
  // There is no variable a in the scope of the find function, so look for the parent layer through the scope chain,
  // The parent layer here is the whole domain, so the a variable is found
  console.log(a); // 100