Home Web Front-end JS Tutorial How to better understand JavaScript variable types and variable scopes

How to better understand JavaScript variable types and variable scopes

Jul 18, 2017 am 10:19 AM
javascript js variable

Type of variable

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:

i=100;//Number类型 
i="variable";//String类型 
i={x:4};//Object类型 
i=[1,2,3];//Array类型
Copy after login

Although this feature of JS makes our coding more flexible, it also brings a drawback, which is not conducive to debugging. The weak detection of the compiler makes it quite painful for us to maintain lengthy code.

Global variables and local variables
When the JS parser is executed, it will first build a global object in the execution environment, and the global properties we define are used as the objects Property reading, 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.

Variable Scope
The scope of variables in any programming language is a critical detail. The scope of variables in JS is more 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:

<SCRIPT LANGUAGE="JavaScript" type="text/javascript"> 
//定义一个输出函数 
function outPut(s){ 
document.writeln(s) 
} 
//全局变量 
var i=0; 
//定义外部函数 
function outer(){ 
//访问全局变量 
outPut(i); // 0 
//定义一个类部函数 
function inner(){ 
//定义局部变量 
var i = 1; 
// i=1; 如果用隐式申明 那么就覆盖了全局变量i 
outPut(i); //1 
} 
inner(); 
outPut(i); //0 
} 
outer(); 
</SCRIPT>
Copy after login

The output 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 characteristics, 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:

<SCRIPT LANGUAGE="JavaScript" type="text/javascript"> 
//定义一个输出函数 
function outPut(s){ 
document.writeln(s) 
} 
//全局变量 
var i=0; 
//定义外部函数 
function outer(){ 
//访问全局变量 
outPut(i); // 0 
//定义一个类部函数 
function inner(){ 
outPut(i); //undefiend 
var i=1; 
outPut(i); //1 
} 
inner(); 
outPut(i); //0 
} 
outer(); 
</SCRIPT>
Copy after login

JS variable scope

<script language ="javascript" type ="text/javascript" > 
var a = "change"; 
function fun() { 
alert(a);//输出undefined 
var a = "改变了"; 
alert(a);//输出改变了 
} 
alert(a);//输出change 
fun(); 
</script>
Copy after login

var defines a variable in the scope. Before a is output for the first time, JS will In the compilation analysis, a has been assigned the value of change, so change is output for the first time. When the fun() function is called, JS creates a new scope. Before outputting a, the values ​​of all var variables are initialized to undefined, so The first output in fun() is undefined, and the second output has already assigned a value, so a new value is output; the two a's are two different variables inside and outside the function, such as:

<script language ="javascript" type ="text/javascript" > 
var b; 
function fun() { 
b = "change"; 
} 
alert(b);//输出undefined 
</script>
Copy after login

Variable b has been defined outside the function, and a value is assigned to b in the function, but the output is undefined.

The above is the detailed content of How to better understand JavaScript variable types and variable 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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

What are instance variables in Java What are instance variables in Java Feb 19, 2024 pm 07:55 PM

Instance variables in Java refer to variables defined in the class, not in the method or constructor. Instance variables are also called member variables. Each instance of a class has its own copy of the instance variable. Instance variables are initialized during object creation, and their state is saved and maintained throughout the object's lifetime. Instance variable definitions are usually placed at the top of the class and can be declared with any access modifier, which can be public, private, protected, or the default access modifier. It depends on what we want this to be

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

jQuery usage practice: several ways to determine whether a variable is empty jQuery usage practice: several ways to determine whether a variable is empty Feb 27, 2024 pm 04:12 PM

jQuery is a JavaScript library widely used in web development. It provides many simple and convenient methods to operate web page elements and handle events. In actual development, we often encounter situations where we need to determine whether a variable is empty. This article will introduce several common methods of using jQuery to determine whether a variable is empty, and attach specific code examples. Method 1: Use the if statement to determine varstr="";if(str){co

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles