当前位置:网站首页>[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 .
边栏推荐
- Follow the archiving tutorial to learn rnaseq analysis (IV): QC method for de analysis using deseq2
- Process judgment - ternary operation - for loop
- MapReduce初级编程实践
- Advertising is too "wild", Yoshino "surrenders"
- 通过tidymodels使用XGBOOST
- 同花顺炒股软件可靠吗??安全嘛?
- 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
- PHP connects to database to realize user registration and login function
- Netease cloud lost its "feelings" card
- [随笔]ME53N 增加按钮,调用URL
猜你喜欢

Crawler notes (2) - parse

This year's examinees are more "desperate" than the college entrance examination

渗透学习-靶场篇-dvwa靶场详细攻略(持续更新中-目前只更新sql注入部分)

《7天学会Go并发编程》第六天 go语言Sync.cond的应用和实现 go实现多线程联合执行

average-population-of-each-continent

"I make the world cooler" 2022 Huaqing vision R & D product launch was a complete success

First knowledge of the second bullet of C language

月薪3万的狗德培训,是不是一门好生意?

广告太「野」,吉野家「渡劫」

average-population-of-each-continent
随机推荐
资深猎头团队管理者:面试3000顾问,总结组织出8大共性(茅生)
average-population-of-each-continent
使用SQL进行数据去重的N种方法
Basics of operators
基于 ESXi 的黑群晖 DSM 7.0.1 安装 VMware Tools
[随笔]ME53N 增加按钮,调用URL
How to prioritize the contents in the queue every second
游戏手机平台简单介绍
go语言切片Slice和数组Array对比panic: runtime error: index out of range问题解决
Workflow automation low code is the key
《7天学会Go并发编程》第六天 go语言Sync.cond的应用和实现 go实现多线程联合执行
这届考生,报志愿比高考更“拼命”
Improving deep neural networks: hyperparametric debugging, regularization and optimization (III) - hyperparametric debugging, batch regularization and program framework
PHP connects to database to realize user registration and login function
"Top stream Aidou manufacturing machine" cooperates with four industrial capitals to become LP
Using xgboost with tidymodels
Common APIs (Methods) for scope -number and string
个人TREE ALV 模版-加快你的开发
Character interception triplets of data warehouse: substrb, substr, substring
Advertising is too "wild", Yoshino "surrenders"