Table of Contents
In Es5, there are only global scope and function scope
New block-level scope in Es6
Home Web Front-end Front-end Q&A What is the difference between es5 and es6 scopes

What is the difference between es5 and es6 scopes

Apr 11, 2022 pm 02:56 PM
es5 es6 Scope

Difference: There are only two types of scope in es5: global scope and function scope, while there are three types of scope in es6: global scope, function scope and block-level scope, with a new one added Block-level scope. The role of block-level scope: It can solve the problem of outer variables being overwritten due to the promotion of inner scope variables, and prevent variables used for loop counting from leaking into global variables.

What is the difference between es5 and es6 scopes

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer

The scope of es5 and es6 Difference:

  • There are only two scopes in es5: global scope and function scope

  • Scope in es6 There are three types: global scope, function scope and block-level scope

In Es5, there are only global scope and function scope

ES5 Use var to declare variables. Variables declared with var may exist in the global scope or in the local scope. The specific situation is as follows

1. Global scope

Three situations of having global scope

a. Variables declared outside the function have global scope
b. Undefined variables with direct assignment automatically Declared as a global variable
c. The properties of the window object have global scope

2. Local scope (function scope)

The scope of variables in the function body

  • Variables defined within the function can only be accessed within the function

Example

1

2

3

4

5

6

7

8

9

10

11

12

var a = 1;

console.log(a);// 1                  此处a为全局变量,在全局作用域下都可访问得到

 

b = 2

console.log(b); // 2                 此处b未被var定义,而是被直接赋值,自动声明为全局变量

 

function fun() {

  var c = 3;

  console.log(c);//3                 此处c存在在函数作用域中,仅在函数fun中可访问

}

fun()

console.log(c);// undefined         全局作用域下访问函数作用域中的变量c,得到undefined

Copy after login

New block-level scope in Es6

Block-level scope can be simply understood as: the content enclosed in curly brackets {}, it can Contains a scope of its own. Variables in block-level scope are declared by let and const

Why is block-level scope needed?

1. Solve the problem of outer variables being overwritten due to promotion of inner scope variables

1

2

3

4

5

6

7

8

9

var i = 5;

function fun(){

  console.log(i);//undefined

  if(true){

    var i = 6

    console.log(i);//6

  }

}

fun()

Copy after login

Execution results
What is the difference between es5 and es6 scopes
The variable i in function fun is declared using var. This involves the issue of variable promotion. The so-called variable promotion means that function declarations and variable declarations are always quietly "promoted" to the top of the method body by the interpreter. So the i here is equivalent to reaching the top of function fun in advance, but the assignment is still performed when i = 6 is running. The above code is actually equivalent to:

1

2

3

4

5

6

7

8

9

10

var i = 5;

function fun(){

  var i;

  console.log(i);

  if(true){

    i = 6

    console.log(i)

  }

}

fun()

Copy after login

When the first i is printed , i is only declared but not assigned (i is assigned a value of 6 in the if statement), so the first printed i is undefined, and the second printed i is 6

1

2

3

4

5

6

7

8

9

var i = 5;

function fun(){

  console.log(i);//5

  if(true){

    let i = 6

    console.log(i);//6

  }

}

fun()

Copy after login

If used let declares the variable i in if, then the curly braces { } where the if statement is located will form a block-level scope, and the variables declared in this scope will be "bound" in this area and will no longer be affected by the outside. (i.e. temporary dead zone), so the first i output when executing the fun function is var i=5 in the global scope, and the i output in the if statement is let i=6## declared in the block-level scope.

#2. Prevent variables used for loop counting from leaking into global variables

1

2

3

4

for(var i = 0; i < 3; i++){

  doSomething()

}

console.log(i)//3

Copy after login

The above code declares the i variable with var for loops. Ideally, i should only be used in loops. It is valid in the body, but i here is exposed in the global scope, so after the loop ends, the value of i can still be accessed in the global scope

1

2

3

4

for(let i = 0; i < 3; i++){

  console.log(i)

}

console.log(i)//undefined

Copy after login

If you use block-level scope let to declare i, then the i variable declared here is only valid within the for loop curly braces { }. Accessing variables in the block-level scope in the global scope will result in undefined

Block-level scope features

1. Variables declared by let are only valid in the scope (within the current curly braces), so arbitrary nesting is allowed, at each level They are all separate scopes

2. The inner scope can have the same name as the outer scope variable (no scopes are used without interfering with each other)

3. let can only exist in the current scope Top level

Note: If there are variables/constants declared by let or const in { } in if statements and for statements, the scope of the { } also belongs to the block scope

Examples about scope

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

<script type="text/javascript">

    {

        var a = 1;

        console.log(a); // 1

    }

    console.log(a); // 1

    // 可见,通过var定义的变量可以跨块作用域访问到。

 

    (function A() {

        var b = 2;

        console.log(b); // 2

    })();

    // console.log(b); // 报错,

    // 可见,通过var定义的变量不能跨函数作用域访问到

 

    if(true) {

        var c = 3;

    }

    console.log(c); // 3

    for(var i = 0; i < 4; i++) {

        var d = 5;

    };

    console.log(i); // 4   (循环结束i已经是4,所以此处i为4)

    console.log(d); // 5

    // if语句和for语句中用var定义的变量可以在外面访问到,

    // 可见,if语句和for语句属于块作用域,不属于函数作用域。

 

    {

        var a = 1;

        let b = 2;

        const c = 3;   

         

        {

            console.log(a);     // 1    子作用域可以访问到父作用域的变量

            console.log(b);     // 2    子作用域可以访问到父作用域的变量

            console.log(c);     // 3    子作用域可以访问到父作用域的变量

 

            var aa = 11;

            let bb = 22;

            const cc = 33;

        }

         

        console.log(aa);    // 11   // 可以跨块访问到子 块作用域 的变量

        // console.log(bb); // 报错   bb is not defined

        // console.log(cc); // 报错   cc is not defined

    }

</script>

Copy after login
[Related recommendations:

javascript video tutorial, web front-end

The above is the detailed content of What is the difference between es5 and es6 scopes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

The difference between let and var in vue The difference between let and var in vue May 08, 2024 pm 04:21 PM

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

There are several situations where this in js points to There are several situations where this in js points to May 06, 2024 pm 02:03 PM

In JavaScript, the pointing types of this include: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.

See all articles