当前位置:网站首页>[js]var, let, const
[js]var, let, const
2022-06-27 23:01:00 【Guardian of loving angels】
let、var、const The difference between
Declare variable keyword summary
stay JavaScript in , There is a total 3 A way to declare variables :
- var
- let
- const
It has been 3 Ways of planting , This is due to historical reasons . The initial keyword for declaring variables was var, But to solve the scope problem , So the following new let and const The way .
Scope
First, let's look at the scope .
ES5 The scope in is : Global scope 、 Function scope ,ES6 New block level scope... In . Block scope is defined by { } Include ,if Statement and for In the sentence { } It's also block scoped .
var keyword
- There is no concept of a block level scope
//Global Scope
{
var a = 10;
}
console.log(a); //10
In the above code , stay Global Scope( Global scope ) in , And in Block Scope( Block level scope ) { } in ,a The output is 10, From this we can see that var Declared variable does not exist Block Scope The concept of
- There is a global scope 、 The concept of function scope
//Global Scope
var a = 10;
function checkscope(){
//Local Scope
var b = 20;
console.log(a); //10
console.log(b); //20
}
checkscope();
console.log(b); //ReferenceError: b is not defined
In the above code , stay Global Scope of use var The statement a, stay checkscope Function Local Scope( Local scope 、 Function scope ) It's printed out in the 10, But in Global Scope Variables printed in b Wrong report .
- The uninitialized value defaults to undefined
//Global Scope
var a;
console.log(a); //undefined
In the above code , stay Global Scope of use var The statement a, But there is no initialization value , Its default value is undefined, Here is undefined yes undefined type , Instead of strings .
- There is variable promotion
//Global Scope
console.log(a); //undefined
var a = 10;
checkscope();
function checkscope(){
//Local Scope
console.log(a); //undefined
var a;
}
In the above code , First print a, And then use var Declare variables a. The variable is raised because js You need to go through the compilation and execution phases . and js During the compilation phase , All variable declarations will be collected and declared in advance .
You can visualize this process as all statements ( Variable ) Will be “ Move ” To the top of their respective scopes , This process is called ascension .
- The global scope uses var Declared variables are mounted to window Under the object
//Global Scope
var a = 10;
console.log(a); //10
console.log(window.a); //10
console.log(this.a); //10
In the above code , Printed out 3 individual 10, visit a and window.a or this.a They're all equivalent .
for instance : For example, I want to visit location object , Use location You can visit , Use window.location You can also visit , It's just window Objects can be omitted without writing , It's like new Array( ) and new window.Array( ) It is equivalent. .
- Duplicate declarations are allowed in the same scope
//Global Scope
var a = 10;
var a = 20;
console.log(a); //20
checkscope();
function checkscope(){
//Local Scope
var b = 10;
var b = 20;
console.log(b); //20
}
In the above code , stay Global Scope The statement is made. 2 Time a, Valid with the last declaration , Print as 20. Empathy , stay Local Scope It's the same .
let keyword
- There is the concept of block level scope
{
//Block Scope
let a = 10;
}
console.log(a); //ReferenceError: a is not defined
In the above code , Print a Report errors , That there is Block Scope The concept of .
- No variable promotion
{
//Block Scope
console.log(a); //ReferenceError: Cannot access 'a' before initialization
let a = 10;
}
In the above code , Print a Report errors : Cannot access... Before initialization . Indicates that there is no variable promotion .
- Temporary dead zone
{
//Block Scope
console.log(a); //ReferenceError: Cannot access 'a' before initialization
let a = 20;
}
if (true) {
//TDZ Start
console.log(a); //ReferenceError: Cannot access 'a' before initialization
let a; //TDZ end
console.log(a); //undefined
a = 123;
console.log(a); //123
}
In the above code , Use let Declared variables a, Result in binding this block level scope , So in let Before declaring variables , Printed variables a Report errors .
This is because of the use of let/const The declared variable will have a temporary deadband .
What is a temporary dead zone ?
ES6 Standard middle right let/const Explanation in the statement The first 13 Chapter , There is a passage as follows :
The variables are created when their containing Lexical Environment is instantiated but may not be accessed inany way until the variable’s LexicalBinding is evaluated.
The adult translation is :
When the control flow of a program is in a new scope (module、function or block Scope ) When instantiating , Use... In this scope let/const Declared variables are created in the scope first , However, there is no lexical binding at this time , So it can't be accessed , If you access it, you will throw an error . therefore , Run the process here, go into scope, create variables , The time between variables can be accessed , It's called a temporary dead zone .
Another simple understanding is :
ES6 Regulations ,let/const The command makes the block form a closed scope . If you use variables before declaration , You're going to report a mistake .
All in all , In code block , Use let/const Before a command declares a variable , This variable is not available .
This is in grammar , be called “ Temporary dead zone ”( temporal dead zone, abbreviation TDZ).
In fact, there is no variable promotion in the above example , In fact, it is also a temporary dead zone , Because it has the concept of temporary dead zone , So there is no variable promotion at all .
- Duplicate declarations are not allowed in the same scope
{
//Block Scope
let A;
var A; //SyntaxError: Identifier 'A' has already been declared
}
{
//Block Scope
var A;
let A; //SyntaxError: Identifier 'A' has already been declared
}
{
//Block Scope
let A;
let A; //SyntaxError: Identifier 'A' has already been declared
}
const keyword
- Must be initialized immediately , It cannot be left for later assignment
// Block Scope
const a; // SyntaxError: Missing initializer in const declaration }
In the above code , use const Declared variables a No initialization , So wrong reporting .
- The value of a constant cannot be changed
//Block Scope
{
const a = 10;
a = 20; // TypeError: Assignment to constant variable
}
In the above code , use const Variable declared a And initialized to 10, Then try to modify a Value , Report errors .
const Actually guaranteed , It's not that the value of a variable can't be changed , Instead, the memory address that the variable points to holds the same data .
Feature summary
- var keyword
- There is no concept of a block level scope
- There is a global scope 、 The concept of function scope
- The uninitialized value defaults to undefined
- There is variable promotion
- The global scope uses var Declared variables are mounted to window Under the object
- Duplicate declarations are allowed in the same scope
- let keyword
- There is the concept of block level scope
- No variable promotion
- Temporary dead zone
- Duplicate declarations are not allowed in the same scope
- const keyword
- And let Same characteristics , have only 2 A difference
- difference 1: Must be initialized immediately , It cannot be left for later assignment
- difference 2: The value of a constant cannot be changed
summary
- let const var The difference between ? What is block scope ? How to use ?
- var Variables defined , There's no concept of blocks , Can be accessed across blocks , Cannot be accessed across functions , There is variable Promotion .
- let Variables defined , Can only be accessed in block scope , Cannot access across blocks , It can't be accessed across functions , No variable promotion , Cannot repeat declaration .
- const Used to define constants , Must be initialized when used ( That is, it must be assigned a value ), Can only be accessed in block scope , And it can't be modified , No variable promotion , Cannot repeat declaration .
Initially in JS In the scope of : Global scope 、 Function scope . There is no concept of block scope .
ES6 New block level scope... In . Block scope is defined by { } Include ,if Statement and for In the sentence { } It's also block scoped .
When there was no block scope before , stay if perhaps for Variables declared in a loop are exposed as global variables , The second is { } Inner variables in may override outer variables . The emergence of block level scopes solves these problems .
边栏推荐
- Basics of operators
- [essay]me53n add button to call URL
- Livox Lidar+APX15 实时高精度雷达建图复现整理
- Zabbix6.0 upgrade Guide - how to synchronize database upgrades?
- mongodb基础操作之聚合操作、索引优化
- 【经典干货书】数据科学中的信息理论方法,561页pdf
- Open source of local run / development library of hiplot online drawing tool
- Livox lidar+ Haikang camera generates color point cloud in real time
- Learn to go concurrent programming in 7 days go language sync Application and implementation of cond
- 元气森林的5元有矿之死
猜你喜欢

医美大刀,砍向00后

"Top stream Aidou manufacturing machine" cooperates with four industrial capitals to become LP

Design of STM32 and rc522 simple bus card system

Penetration learning - shooting range chapter - detailed introduction to Pikachu shooting range (under continuous update - currently only the SQL injection part is updated)

Structured machine learning project (I) - machine learning strategy

从学生到工程师的蜕变之路

Service gateway of microservices

Consumer finance app user insight in the first quarter of 2022 - a total of 44.79 million people

Liuleifeng, a "good man in Guangzhou" in the first quarter of 2022, has a strong sense of integrity and food safety

First knowledge of the second bullet of C language
随机推荐
Structured machine learning project (I) - machine learning strategy
[网络]常见的请求方法
医美大刀,砍向00后
Azure Kinect DK realizes 3D reconstruction (Jetson real-time version)
批量处理-Excel导入模板1.1-支持多Sheet页
Basic data type and complex data type
月薪3万的狗德培训,是不是一门好生意?
Death of 5 yuan youkuang in Yuanqi forest
元气森林的5元有矿之死
Improving deep neural networks: hyperparametric debugging, regularization and optimization (III) - hyperparametric debugging, batch regularization and program framework
移动端避免使用100vh[通俗易懂]
About the SQL injection of davwa, errors are reported: analysis and verification of the causes of legal mix of settlements for operation 'Union'
Consumer finance app user insight in the first quarter of 2022 - a total of 44.79 million people
Web Worker介绍及使用案例
ABAP随笔-关于ECC后台server读取Excel方案的想法
mongodb基础操作之聚合操作、索引优化
Basic knowledge of loop traversal and function
Crawler notes (1) - urllib
average-population-of-each-continent
The most illusory richest man in China is even more illusory