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

Solve MySQL deadlock routine by updating different indexes

The previous articles introduced how to debug loc...

Application nesting of HTML ul unordered tables

Application nesting of unordered lists Copy code T...

Conditional comment style writing method and sample code

As front-end engineers, IE must be familiar to us...

Comprehensive analysis of MySql master-slave replication mechanism

Table of contents Master-slave replication mechan...

Comprehensive understanding of line-height and vertical-align

Previous words Line-height, font-size, and vertica...

Example code of javascript select all/unselect all operation in html

Copy code The code is as follows: <html> &l...

HTML form tag tutorial (2):

This tutorial introduces the application of vario...

In-depth analysis of the diff algorithm in React

Understanding of diff algorithm in React diff alg...

Summary of Vue first screen performance optimization component knowledge points

Vue first screen performance optimization compone...