Home Web Front-end Front-end Q&A What is scope in javascript

What is scope in javascript

Jan 18, 2022 pm 05:50 PM
javascript Scope

In JavaScript, scope is the accessible range of variables (objects, functions), and the effective range of variables that can be read and written in script code; scope can control the visibility and life cycle of variables. .

What is scope in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Almost all languages ​​have the concept of scope. Simply put, scope (scope) is the accessible scope of a variable, that is, the scope controls the visibility and life cycle of the variable. .

In JavaScript, objects and functions are also variables.

Before ECMAScript6, the scope of variables was mainly divided into global scope and local scope (also called function scope); in ECMAScript6 and after, the scope of variables was mainly divided into There are three types: global scope, local scope and block-level scope.

The variables in the corresponding scope are called global variables, local variables and block-level variables respectively.

  • Global variables are declared outside all functions;

  • Local variables are variables declared within the function body or named parameters of the function;

  • Block-level variables are variables declared in the block and are only valid in the block.

The scope of a variable is closely related to the declaration method. Variables declared using var have global scope and function scope, and there is no block-level scope; variables declared using let and const have global scope, local scope and block-level 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

<!DOCTYPE html>

<html>

    <head>

        <meta charset="utf-8">

    </head>

    <body>

        <script>

            var v1 = "JavaScript"; //全局变量

            let v2 = "JScript"; //全局变量

            let v3 = "Script"; //全局变量

            scopeTest(); //调用函数

            function scopeTest() {

                var lv = "aaa"; //局部变量

                var v1 = "bbb"; //局部变量

                let v2 = "ccc"; //局部变量

                if (true) {

                    let lv = "123"; //块级变量

                    console.log("块内输出的lv = " + lv); //123

                }

                console.log("函数体内输出的lv = " + lv); //aaa

                console.log("函数体内输出的v1 = " + v1); //bbb

                console.log("函数体内输出的v2 = " + v2); //ccc

                console.log("函数体内输出的v3 = " + v3); //Script

                //v4为全局变量,赋值在后面,因而值为undefined

                console.log("函数体内输出的v4 = " + v4);

            }

            var v4 = "VBScript"; //全局变量

            console.log("函数体外输出的lv = " + lv); //① 报ReferenceError错误

            console.log("函数体外输出的v1 = " + v1); //JavaScript

            console.log("函数体外输出的v2 = " + v2); //JScript

            console.log("函数体外输出的v3 = " + v3); //Script

            console.log("函数体外输出的v3 = " + v4); //VBScript

        </script>

    </body>

</html>

Copy after login

The above script code declares 4 global variables, 3 local variables and 1 block-level variable respectively. Outside the scopeTest function, variables v1, v2, v3 and v4 are global variables; within the scopeTest function body, lv and v2 are global variables; in the if judgment block, lv is a block-level variable.

We see that local variables v1 and v2 have the same names as global variables v1 and v2. In the scopeTest function body, local variables v1 and v2 are valid, so the output results of these two variables in the function body are "bbb" " and "ccc"; outside the function body, the global variables v1 and v2 are valid, so outside the function body, the output results of these two variables are "JavaScript" and "JScript" respectively.

In addition, the block-level variable lv and the local variable lv have the same name. In the if judgment block, the block-level variable lv is valid, so the output result in the block is "123", while outside the block, the local variable lv Valid, the output result of the lv variable is "aaa".

In addition, the global variables v3 and v4 are not overwritten in the function body, so the value of the global variable is output, so the output result of v3 in the function body and outside the body is "Script", and the v4 variable The assignment is after the function call, so the output result of v4 in the function body is "undefined", while the output outside the function body is after the declaration, so the result is "VBScript". lv is a local variable, so accessing it outside the function will report a "ReferenceError" error.

After the above code is run in the Chrome browser, open the browser's console and you can see the output shown in the figure below.

What is scope in javascript

The reason for the error in line 28:

The lv variable is a local variable and is invalid after leaving the function. Comment this line of code and then run it. At this time, open the browser console and you will see:

What is scope in javascript

[Related recommendations: javascript learning tutorial

The above is the detailed content of What is scope in javascript. 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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
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.

C++ Smart Pointers: From Basics to Advanced C++ Smart Pointers: From Basics to Advanced May 09, 2024 pm 09:27 PM

Smart pointers are C++-specific pointers that can automatically release heap memory objects and avoid memory errors. Types include: unique_ptr: exclusive ownership, pointing to a single object. shared_ptr: shared ownership, allowing multiple pointers to manage objects at the same time. weak_ptr: Weak reference, does not increase the reference count and avoid circular references. Usage: Use make_unique, make_shared and make_weak of the std namespace to create smart pointers. Smart pointers automatically release object memory when the scope ends. Advanced usage: You can use custom deleters to control how objects are released. Smart pointers can effectively manage dynamic arrays and prevent memory leaks.

See all articles