In js, you can use the var, let and const keyword declarations. Variables declared by var can be used to save any type of value, and the scope is the function scope; variables declared by let are used in {}, and the scope of the variable is limited to the block-level domain; const is used to modify constants, and the declaration position is not limited .
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Declare variable keywords var, let and const
ECMAScript variables are loosely typed, that is, variables can be used to save any type of data, and each variable is just a variable used to save any A named placeholder for the value.
1.var keyword
Variables declared by var can be used to save any type of value (a special value undefined will be saved without initialization), like other languages in javascript When defining a variable, you can also assign a value to the variable. The variable is defined as a variable that saves the assigned value. Because JavaScript is a dynamic language, when initializing a variable, it will not be identified as the assigned data type, but Just a simple assignment. Then not only can the saved value be changed, but the type of the value can also be changed:
var message = "hi"; message = 100;
1.1.var declaration scope
A variable defined using the var operator will become a local variable of the function that contains it. . For example, using var to define a variable inside a function means that the variable will be destroyed when the function exits. I think this is what is called garbage collection:
function test( ) { vart message = "hi"; //局部变量 } test( ); console.log(message); //报错!
After the function is called, the variable will be destroyed randomly. Therefore, the last line will report an error. However, you can create a global variable when you omit the var operator when defining variables in a function:
function test( ) { message = "hi"; //全局变量 } test( ); console.log(message); //"hi"
As long as the function test() is called once, the global variable message will be defined and can be accessed outside the function. However, since global variables defined in local scope are difficult to maintain, this is generally not recommended.
1.2. Var declaration promotion
Variables declared using the var keyword will automatically be promoted to the top of the function scope, which is the so-called "hoist" (hoist), that is, all variable declarations will be pulled Go to the top of the function scope:
function fool( ) { console.log(age); var age = 28; } fool( ); //undefined
No error will be reported here, but undefined will be displayed. ECMAScript will treat it as equivalent to the following code when running:
function fool( ) { var age; console.log(age); age = 28; } fool( ); //undefined
2 .let declaration
The functions of let and var are similar, but there are very important differences. The most obvious difference is that the scope of the let declaration is the block scope, while the scope of the var declaration is the function scope:
if (true) { let age = 26; console.log(age); //26 } console.log(age); //ReferceError:age没有定义
The scope of the age variable is limited to the inside of the block, so it cannot be referenced outside the if block. . Block scope is a subset of function scope, so the same scope restrictions that apply to var also apply to let.
Let also does not allow redundant declarations to appear in the same scope (var can):
var name; var name; let age; let age; //SyntaxError;标识符age已经声明过了
In addition, redundant declaration errors will not be affected by mixing var and let. These two keywords do not declare variables of different types, they just indicate how the variables exist in the relevant scope.
2.1. Temporary dead zone
Another important difference between let and var is that variables declared by let will not be promoted in the scope:
//name会提升 console.log(name); //undefined var name = 'matt'; //name不会提升 console.log(name); //ReferenceError:name没有定义 let name = 'matt';
2.2. Global Declaration
Unlike var, variables declared in the global scope using let will not become attributes of the window object (variables declared with var will):
var name = 'matt'; console.log(window.name); //'matt' let name = 'matt'; console.log(window.name); //undefined
However, the let declaration is still If it occurs in the global scope, the corresponding variable will persist within the declaration cycle of the page.
2.3. Conditional declaration
The scope of let is a block, so it is impossible to check whether a variable with the same name has been previously declared using let, and it is also impossible to declare it without a declaration. . Using try/catch or typeof operators cannot solve it, because the scope of the let declaration in the conditional block is limited to that block. For this reason, the new ES6 declaration keyword let cannot rely on the conditional declaration pattern.
2.4. Let statement in for loop
When using var, the most common problem is the strange declaration and modification of iteration variables:
for(var i = 0; i < 5; ++i) { setTimeout( () => console.log(i) ,0) } //你可能以为会输出0、1、2、3、4 //实际上输出的是5、5、5、5、5
When exiting the loop At that time, the iteration variable holds the value that caused the loop to exit: 5. When the setTimeout timeout logic is executed later, i is the same variable, so the final output is the same value.
When using let to declare an iteration variable, the JavaScript engine will declare a new iteration variable for each iteration loop in the background, and each setTimeout refers to a different variable instance:
for(let i = 0; i < 5; ++i) { setTimeout( () => console.log(i) ,0) } //会输出0、1、2、3、4
3 .const declaration
The behavior of const is basically the same as let. The only important difference is that the variable must be initialized at the same time when it declares a variable, and trying to modify a variable declared by const will result in a runtime error.
const声明的限制只适用于它指向的变量的引用。如果const变量引用的是一个对象,那么修改这个对象内部的属性并不违反const的限制:
const person = { }; person.name = 'matt';
4.使用建议
let和const是ES6中新增的,从客观上为JavaScript更精确地声明作用域和语义提供更好的支持。
4.1.不使用var
限制自己只使用let和const有助于提升代码质量,因为变量有了明确的作用域、声明位置,以及不变的值。
4.2.const优先,let次之
使用const声明可以让浏览器运行时强制保持变量不变,也可以让静态代码分析工具提前发现不合法的赋值操作。因此,我们应该优先使用const来声明变量,只有在提前知道未来会有修改时再使用let。
【推荐学习:javascript高级教程】
The above is the detailed content of Which keyword does javascript use to declare variables?. For more information, please follow other related articles on the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version