当前位置:网站首页>[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 .
边栏推荐
- Character interception triplets of data warehouse: substrb, substr, substring
- 「R」使用ggpolar绘制生存关联网络图
- Is it safe to open a stock account through the account opening link given by the CICC securities manager? I want to open an account
- The "business and Application Security Development Forum" held by the ICT Institute was re recognized for the security capability of Tianyi cloud
- Learn to go concurrent programming in 7 days go language sync Application and implementation of cond
- Learn rnaseq analysis by following the archiving tutorial (I)
- Process judgment - ternary operation - for loop
- Where can I set the slides on the front page of CMS applet?
- Crawler notes (3) -selenium and requests
- 通过tidymodels使用XGBOOST
猜你喜欢

Service gateway of microservices

Introduction to MySQL operation (IV) -- data sorting (ascending, descending, and multi field sorting)

Netease cloud lost its "feelings" card

Crawler notes (1) - urllib

99 multiplication table - C language

“顶流爱豆制造机”携手四个产业资本,做LP

Arcgis-engine二次开发之空间关系查询与按图形查询

《7天学会Go并发编程》第7天 go语言并发编程Atomic原子实战操作含ABA问题

Day 7 of "learning to go concurrent programming in 7 days" go language concurrent programming atomic atomic actual operation includes ABA problem

Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)
随机推荐
《7天学会Go并发编程》第7天 go语言并发编程Atomic原子实战操作含ABA问题
mysql操作入门(四)-----数据排序(升序、降序、多字段排序)
OData - SAP S4 OP 中使用SAP API Hub 的API
Zabbix6.0升级指南-数据库如何同步升级?
ABAP随笔-关于ECC后台server读取Excel方案的想法
99 multiplication table - C language
STM32与RC522简单公交卡系统的设计
Solve the problem that the virtual machine cannot be connected locally
Spatial relation query and graph based query in secondary development of ArcGIS Engine
The most illusory richest man in China is even more illusory
各种loam总结(激光slam)
ABAP随笔-物料主数据界面增强-页签增强
[can you really use es] Introduction to es Basics (II)
PHP connects to database to realize user registration and login function
「R」 Using ggpolar to draw survival association network diagram
中金证券经理给的开户链接办理股票开户安全吗?我想开个户
初识C语言 第二弹
从学生到工程师的蜕变之路
Passerelle de service pour les microservices
Aggregation and index optimization of mongodb basic operations