JavaScript static scope and dynamic scope explained with examples

JavaScript static scope and dynamic scope explained with examples

Preface

At the beginning of the article, let’s learn a few concepts:

  • Scope: "You Don't Know JS" points out that the scope is a set of rules that manage how the engine searches for variables based on identifier names in the current scope and nested subscopes. In simple terms, scope specifies how variables are looked up.
  • Static scope: also known as lexical scope, the scope of a function is determined when the function is defined. In layman's terms, it is determined by where you write the variables and block scopes when writing code.
  • Dynamic scope: The scope of a function is determined when the function is called.

Static scope vs. dynamic scope

JavaScript uses static scope, and the location of the function definition determines the scope of the function.

Let's take a look at an example to understand the difference between static scope and dynamic scope.

var val = 1;
function test() {
    console.log(val);
}
function bar() {
    var val = 2;
    test();
}

bar();
// turn out? ? ?

In the above code:

  • We first define a global variable val and assign it a value of 1
  • Declare a function text, the function is to print the value of the variable val
  • Declare a function bar, define a local variable val inside the function, assign it a value of 2, and execute the test() function inside the function
  • Execute the bar() function

Static scope execution process

When executing the test function, first check whether there is a variable val inside the test function. If not, search along the location where the function is defined, search the code of the previous layer, and find the global variable val, whose value is 1.

Scope lookup always starts at the innermost scope at runtime and moves outwards until the first matching identifier is encountered.

No matter where a function is called or how it is called, its scope is determined only by where the function is defined.

Dynamic scope execution process

When the test function is executed, the val variable is first searched from within the function. If not found, the variable val is searched from the scope of the calling function, that is, the scope of the bar function. Therefore, the print result is 2.

exercise

Let's look at three exercises to digest and understand static scope: the scope is determined by where the function is defined.

Exercise 1

var a = 1
function fn1(){
    function fn3(){
        var a = 4
        fn2()
    }
    var a = 2
    return fn3
}
function fn2(){
    console.log(a)
}
var fn = fn1()
fn()

In the above code:

  • We first define a global variable a and assign it a value of 1
  • Declare a function fn1, declare function fn3 inside the function, define local variable a, assign value 2, and return value fn3 function
  • The fn3 function defines a local variable a, assigns it a value of 4, and executes fn2()
  • Declare function fn2, the function's function is to print the value of a
  • fn is assigned the return value of fn1()
  • Execute fn() (equivalent to executing fn3 function)

Before doing the questions, you must understand the concept of static scope. In this question, fn2 is defined globally. When variable a cannot be found in fn2, it will search globally, which has nothing to do with fn1 and fn3, and print 1.

Exercise 2

var a = 1
function fn1(){
    function fn2(){
        console.log(a)
    }
    function fn3(){
        var a = 4
        fn2()
    }
    var a = 2
    return fn3
}
var fn = fn1()
fn()

fn2 is defined inside function fn1, so when there is no variable a inside fn2, it will look for it in fn1, which has nothing to do with function fn3. If it cannot be found in fn1, it will look for it in the previous level (global) where fn1 is defined, until the first matching identifier is found. In this question, you can find the variable a in fn1 and print 2

Exercise 3

var a = 1;
function fn1(){
    function fn3(){
        function fn2(){
            console.log(a)
        }
        var a;
        fn2()
        a = 4
    }
    var a = 2
    return fn3
}
var fn = fn1()
fn()

In this question, fn2 is defined in function fn3. When variable a cannot be found in fn2, it will first look in fn3. If it still cannot be found, it will look in fn1. In this question, the variable a can be found in fn3, but since a is not assigned a value when fn2() is executed, undefined is printed.

Summarize

Regarding JavaScript's static scope, we only need to remember one sentence: the location of the function definition determines the scope of the function. When encountering questions, don't be disturbed by other codes.

This is the end of this article about JavaScript static scope and dynamic scope. For more relevant JS static scope and dynamic scope content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript Advanced Programming: Variables and Scope
  • Graphical explanation of the underlying principle of JavaScript scope chain
  • Javascript scope and closure details
  • JS Difficulties Synchronous and Asynchronous and Scope and Closure and Detailed Explanation of Prototype and Prototype Chain
  • Detailed explanation of the usage of scoped slots in Vue.js slots
  • Summary of js execution context and scope
  • Thoughts and sharing on scope issues in JS

<<:  Where is the project location deployed by IntelliJ IDEA using Tomcat?

>>:  How to add a column to a large MySQL table

Recommend

Simple implementation of html hiding scroll bar

1. HTML tags with attributes XML/HTML CodeCopy co...

Detailed explanation of three ways to cut catalina.out logs in tomcat

1. Log4j for log segmentation 1) Prepare three pa...

Summary of Docker common commands and tips

Installation Script Ubuntu / CentOS There seems t...

Solve the Docker x509 insecure registry problem

After installing Docker, I encountered the x509 p...

The perfect solution to the Chinese garbled characters in mysql6.x under win7

1. Stop the MySQL service in the command line: ne...

Some conclusions on developing mobile websites

The mobile version of the website should at least...

Web page HTML code explanation: ordered list and unordered list

In this section, we will learn about list element...

Essential bonus items for optimizing and packaging the front end of Vue projects

Table of contents Preface 1. Routing lazy loading...

Comparison of two implementation methods of Vue drop-down list

Two implementations of Vue drop-down list The fir...

Dynamic SQL statement analysis in Mybatis

This article mainly introduces the dynamic SQL st...

Eight common SQL usage examples in MySQL

Preface MySQL continued to maintain its strong gr...

Detailed explanation of the cache implementation principle of Vue computed

Table of contents Initialize computed Dependency ...

Summary of the use of TypeScript in React projects

Preface This article will focus on the use of Typ...