当前位置:网站首页>[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 .
边栏推荐
- DCC888 :Register Allocation
- 2022年第一季度“广州好人”刘磊峰:具有强烈的诚信意识和食品安全意识
- STM32与RC522简单公交卡系统的设计
- OData - API using SAP API hub in SAP S4 op
- 这类人开始被VC疯抢,月薪8万
- 微服务之服务网关
- Mysql database experiment report (I)
- Avoid using 100vh[easy to understand] at mobile terminal
- OData - SAP S4 OP 中使用SAP API Hub 的API
- Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)
猜你喜欢

How to participate in openharmony code contribution

How to use RPA to achieve automatic customer acquisition?

netERR_CONNECTION_REFUSED 解决大全

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

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

Workflow automation low code is the key

Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)

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

First knowledge of the second bullet of C language

Crawler notes (2) - parse
随机推荐
The "business and Application Security Development Forum" held by the ICT Institute was re recognized for the security capability of Tianyi cloud
Is it safe for GF futures to open an account?
“顶流爱豆制造机”携手四个产业资本,做LP
OData - API using SAP API hub in SAP S4 op
Spark BUG實踐(包含的BUG:ClassCastException;ConnectException;NoClassDefFoundError;RuntimeExceptio等。。。。)
Which method is called for OSS upload
Batch processing - Excel import template 1.1- support multiple sheet pages
Brief introduction to game phone platform
netERR_CONNECTION_REFUSED 解决大全
Gartner focuses on low code development in China how UNIPRO practices "differentiation"
医美大刀,砍向00后
[随笔]ME53N 增加按钮,调用URL
Introduction to MySQL operation (IV) -- data sorting (ascending, descending, and multi field sorting)
[electron] 基础学习
结构化机器学习项目(二)- 机器学习策略(2)
Do you know the full meaning of log4j2 configurations? Take you through all the components of log4j2
渗透学习-靶场篇-dvwa靶场详细攻略(持续更新中-目前只更新sql注入部分)
[suggested collection] ABAP essays-excel-4-batch import recommended
[microservices] (16) -- distributed transaction Seata
How to prioritize the contents in the queue every second