search
HomeWeb Front-endJS TutorialDetailed explanation of js variables and their scope_javascript skills

1. Variable type
Javascript is different from languages ​​such as Java and C. It is an untyped and weakly detected language. Its definition of variables does not require declaring the variable type. We can assign various types of data to the same variable through assignment. For example:
Copy code The code is as follows:

i=100;//Number type
i="variable";//String type
i={x:4};//Object type
i=[1,2,3];//Array type

Although this feature of JS makes our coding more flexible, it also brings a drawback, which is not conducive to debugging. The compiler's weak detection makes it quite painful for us to maintain lengthy code.
2. Variable declaration
Variable declaration in JS is divided into explicit declaration and implicit declaration.
var i=100;//Explicit declaration
i=100;//Implicit declaration
Variables explicitly declared using the var keyword in a function are used as local variables and are useless The var keyword declares global variables using direct assignment.
When we access an undeclared variable, JS will report an error. When we assign a value to an undeclared variable, JS will not report an error. On the contrary, it will think that we want to implicitly declare a global variable. This must be paid attention to.
3. Global variables and local variables
When the JS parser is executed, it will first build a global object in the execution environment. The global properties we define are properties of the object. Read, in the top-level code we can access it using the this keyword and the window object. The local variables in the function body only exist in the calling object generated when the function is executed. The local variables are destroyed immediately when the function is executed. Therefore, in programming, we need to consider how to declare variables reasonably, which not only reduces unnecessary memory overhead, but also largely avoids the debugging trouble caused by repeated definition of variables and overwriting previously defined variables.
4. Variable Scope
The scope of variables is a critical detail in any programming language. The scope of variables in JS is relatively free compared to languages ​​​​such as JAVA and C. A big feature is that JS variables do not have block-level scope. The variables in the function are valid in the entire function. Run the following code:
Copy code The code is as follows:



Output The result is 0 1 0. From the above, it can be proved that if JS uses var to declare a variable in the function body, then this variable is valid in and only within the function body. When the function ends, the local variable can be destroyed.
Due to the above JS features, there is another key issue that needs attention. ActionScript has been used before. Although it and JS are both based on the ECMA standard, it is slightly different here. For example, the following code:
Copy code The code is as follows:



You may think that the output result is 0 0 1 0. In fact, this is indeed the case in AS, but the input in JS is 0 undefined 1 0. Why is this happening? We just mentioned that the local variables declared in the JS function body are valid in the entire function, so in the above code var i = 1; are valid in the inner function. In fact, the explicitly declared variable i is precompiled. It has been compiled into the calling object. Unlike implicitly declared variables, which are defined as global variables when interpreted, only when outPut(i) is called, the variable has not been initialized. At this time, the local variable i is an unassigned variable. , instead of undefined variables, so undefined is output. The above code is equivalent to the following code:
Copy code The code is as follows:

function inner( ){
var i; //Define but not assign
outPut(i); //undefiend
i=1;
outPut(i); //1
}

In order to avoid the above problems, it is highly recommended to make function declarations at the beginning of the function.
5. Basic types and reference types
JS is different from languages ​​such as JAVA and C. It does not need to declare the storage space of the variable when declaring the variable. The data stored in variables can be divided into two categories: basic types and reference types. Among them, numeric values, Boolean values, null and undefined are basic types, and objects, arrays and functions are reference types.
Basic types have a fixed memory size in memory. For example: Numeric type occupies eight bytes in memory, and Boolean value only occupies one byte. For reference data, they can have any length, so their memory size is variable, so what is stored in the variable is actually a reference to the data, usually a memory address or pointer, through which we can find the data.
There are also differences in usage behavior between reference types and basic types:
Copy code The code is as follows:



When assigning a value to basic type b, another area is actually opened up memory space, so changing the value of variable a has no effect on variable b.
Copy code The code is as follows:



The above are variable assignments of reference types. In fact, what they pass is a reference to the memory address, so the access to a_array and b_array are actually both It is the same memory area that is operated on. If I want to reallocate memory space to store reference variables, then I need to use the cloning method or a custom method to copy the data of the reference variable.

JS variable scope
Copy code The code is as follows:



var defines a variable in a scope. Before a is output for the first time, JS has assigned a to change in the pre-compilation analysis, so the first Change is output for the first time. When the fun() function is called, JS creates a new scope. Before outputting a, it initializes the values ​​​​of all var variables to undefined, so the first output in fun() is undefined. The secondary output has been assigned a value, so a new value is output; the two a's are two different variables inside and outside the function, such as:
Copy code The code is as follows:



Variable b has been defined outside the function. A value is assigned to b in the function, but the output is undefined.
Statement
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
switch case 内变量的范围switch case 内变量的范围Feb 09, 2024 am 09:00 AM

packagemainimport"fmt"funcmain(){x:=10switchx{case0:y:='a'fmt.Printf("%c\n",y)case1://y='b'//thiscan'tcompile,y:='b'fmt.Printf("%c\n",y)default:y:=

Linux多线程编程锁详解:如何避免竞争和死锁Linux多线程编程锁详解:如何避免竞争和死锁Feb 11, 2024 pm 04:30 PM

在Linux多线程编程中,锁是一种非常重要的机制,可以避免线程间的竞争和死锁。然而,如果不正确使用锁,可能会导致性能下降和不稳定的行为。本文将介绍Linux中的常见锁类型,如何正确使用它们,以及如何避免竞争和死锁等问题。在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为”互斥锁”的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。Linux实现的互斥锁机制包括POSIX互斥锁和内核互斥锁,本文主要讲POSIX互斥锁,即线程间互斥锁。信号量用在多线程

详解Golang函数中的变量作用域详解Golang函数中的变量作用域Jan 18, 2024 am 08:51 AM

Golang函数中的变量作用域详解在Golang中,变量的作用域指的是变量的可访问范围。了解变量的作用域对于代码的可读性和维护性非常重要。在本文中,我们将深入探讨Golang函数中的变量作用域,并提供具体的代码示例。在Golang中,变量的作用域可以分为全局作用域和局部作用域。全局作用域指的是在所有函数外部声明的变量,即在函数之外定义的变量。这些变量可以在整

掌握JavaScript函数的嵌套和作用域掌握JavaScript函数的嵌套和作用域Nov 03, 2023 pm 07:55 PM

掌握JavaScript函数的嵌套和作用域,需要具体代码示例在JavaScript编程中,函数是非常重要的概念。函数的嵌套和作用域能够极大地提高代码的可读性和灵活性。本文将介绍如何正确地使用嵌套函数和作用域,并提供具体的代码示例。函数的嵌套可以理解为在一个函数中定义了另一个函数。这种嵌套的方式能够将代码分成多个小块,使得程序的逻辑更加清晰。同时,嵌套函数还可

Python Lambda表达式:让编程变得更轻松Python Lambda表达式:让编程变得更轻松Feb 19, 2024 pm 09:54 PM

pythonLambda表达式是一个小的匿名函数,它可以将一个表达式存储在变量中并返回它的值。Lambda表达式通常用于执行简单的任务,这些任务可以通过编写一个单独的函数来完成,但Lambda表达式可以使代码更简洁和易读。Lambda表达式的语法如下:lambdaarguments:expressionarguments是Lambda表达式接收的参数列表,expression是Lambda表达式的体,它包含需要执行的代码。例如,以下Lambda表达式将两个数字相加并返回它们的和:lambdax,

JavaScript const关键字的用法及作用JavaScript const关键字的用法及作用Feb 19, 2024 pm 06:30 PM

JavaScript中const的作用和用法JavaScript是一种广泛应用于网页开发的编程语言,其具有灵活性和动态性是其特点之一。在JavaScript中,我们可以使用const关键字来声明一个常量。本文将介绍const关键字的作用和用法,并提供一些具体的代码示例来帮助读者更好地理解。const的作用const(常量)是一种用于声明不可更改的变量的关键字

c语言static的作用和用法是什么c语言static的作用和用法是什么Jan 31, 2024 pm 01:59 PM

c语言static的作用和用法:1、变量作用域;2、生命周期;3、函数内部;4、修饰全局变量;5、修饰函数;6、其他用途;详细介绍:1、变量作用域,当一个变量前有static关键字,那么这个变量的作用域被限制在声明它的文件内,也就是说,这个变量是“文件级作用域”,这对于防止变量的“重复定义”问题很有用;2、生命周期,静态变量在程序开始执行时初始化一次,并在程序结束时销毁等等。

如何解决Python的变量未定义错误?如何解决Python的变量未定义错误?Jun 24, 2023 pm 10:12 PM

Python是一种高级编程语言,它的易用性和流行程度使得它成为了众多程序员的首选语言。与其他语言一样,Python也存在一些常见的错误类型,例如变量未定义错误。当我们在Python中使用一个未定义的变量时,程序就会抛出一个名为“NameError”的异常。这种错误通常出现在以下几种情况下:拼写错误:可能是因为变量名拼写错误导致了变量未定义错误,我们需要仔细检

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.