当前位置:网站首页>[var const let differences]
[var const let differences]
2022-06-13 06:08:00 【mango660】
var 、const 、let difference
var stay ECMAScript Can be used in all versions .
let and const Only in ES6 And later versions .
var
Function scope .
When declaring uninitialized , The value is
undefined
.Variable promotion mechanism .
In the global scope or in the local scope , Use
var
Keyword declared variables , Will be promoted to the top of the scope .function test(status) { if (status) { var value = "person"; } else { console.log(value); } console.log(value); } test(false);
if
In the code blockvar
The declared variable is promoted to the top of the function .JS When the engine is precompiled , Will automatically put all the code inside
var
Keyword statements are promoted to the top of the current scope .// The above code is parsed as follows function test(status) { var value; if (status) { value = "person"; } else { console.log(value); // undefined } console.log(value); // undefined } test(false);
- Block level declaration :
- Only variables declared under the current function are valid .
- In code blocks and {} Valid in parentheses .
let
Block level declaration , No variable Promotion .
function test(status) { if (status) { let value = "person"; } else { console.log(value); // Report errors } console.log(value); // Report errors } test(false);
Redundant declarations are not allowed in the same block level scope .
If a variable already exists in the same scope , Again using let Keyword declaration will report an error .
var value = "test1"; let value = "test1"; // SyntaxError
const
const Declarations refer to constants , Once defined, it cannot be modified .
Constants must initialize values , If not initialized, an error will be reported .
const test; // error:Missing initializer
const Declare objects .
const Variables cannot modify pointers , But you can change the value .
const obj = { name: "person", age: 21 } obj.name = "Danny"; // That's all right. obj = { }; // error: Cannot modify object pointer
Temporary dead zone
console.log(typeof value); // error:Cannot access 'value' before initialization
let value = "person";
At this time value Still in JS The so-called temporary dead zone (TDZ).
The moment of execution before the declaration is called a temporary deadband .
** working principle :**JS When the engine finds a variable declaration while scanning the code , If you encounter var
Will elevate them to the top of the current scope , encounter let
or const
Will put the declaration in TDZ in , If you visit TDZ The variable in will throw an error , Only after the execution TDZ The variable in will move it out of , And then you can have normal access to . This mechanism will only take effect in the current scope .
Under different scopes :【 This place needs further study 】
console.log(typeof value); // undefined
if(true) {
let value = "person";
}
The biggest difference between the three
- var Variables declared in the global scope have a behavior that will hang in window On the object , It will create a new global variable as the letter of the global object , This behavior may cover window An attribute on an object .
let
andconst
Will not be .
var value1 = "test1";
let value2 = "test2";
const value3 = "test3";
console.log(window.value1);
console.log(window.value2); // undefined
console.log(window.value3); // undefiend
for Application in circulation
var
The declared variable has no block level scope , Iterative variablei
It's going to penetrate outside the circulatory system .
for (var i = 0; i < 4; i ++) {
// ...
}
console.log(i); // 4
let
Declared iteration variables , The scope is limited to for Inside the loop block .
for (let i = 0; i < 4; i ++) {
// ...
}
console.log(i); // error
The real question
for (var i = 0; i < 4; i ++) {
setTimeout( () => {
console.log(i);
}, 0)
}
// 4 4 4 4
setTimeout Asynchronous execution ,for On cycle exit i by 4.【 Study deeply 】
for (let i = 0; i < 4; i ++) {
setTimeout( () => {
console.log(i);
}, 0)
}
// 0 1 2 3
JS The engine declares a new iteration variable for each iteration loop in the background , Every setTimeout All references are different variable instances .
summary
var
The scope of the declaration is the function scope ,let
The declared scope is a block level scope .var
The declared variable is promoted to the top of the function scope ,let
andconst
The declared variable does not exist , And it has the characteristics of temporary dead zone .var
It is allowed to declare the same variable repeatedly in the same scope ,let
andconst
Don't allow .- In global scope ,
var
The declared variable will be hung as window Object properties ,let
andconst
Can't . const
Behavior is basically the same aslet
identical , butconst
Declared variables must be initialized , And can't modify .
边栏推荐
- A glimpse of [wechat applet]
- USB debugging assistant (20191028)
- Echart line chart: multiple line charts show only one line at a time
- Echart柱状图:堆叠柱状图value格式化显示
- Exception after repeated application redeployment on tongweb: application instance has been stopped already or outofmemoryerror:metaspace
- Echart折线图:多条折线图每次仅展示一条
- 不在以下合法域名列表中,微信小程序解决办法
- 【美团笔试题】
- 本地文件秒搜工具 Everything
- How to view APK version number from apk
猜你喜欢
Four shardingsphere JDBC sharding strategies
Shardingsphere JDBC < bind table > avoid join Cartesian product
Use of Nacos configuration center
The Boys x PUBGMOBILE 联动火热来袭!来看最新游戏海报
Sqlplus connection failure
Missing tag identification in cots RFID systems: bringing the gap between theory and Practice
Complete USB debugging assistant
Echart柱状图:echart实现堆叠柱状图
Zero copy technology
[spark]spark introductory practical series_ 8_ Spark_ Mllib (lower)__ Machine learning library sparkmllib practice
随机推荐
Add attributes in storyboard and Xib (fillet, foreground...) Ibinspectable and ibdesignable
1+1>2,Share Creators可以帮助您实现
Echart line chart: multiple line charts show only one line at a time
Power of leetcode-4 - simple
Custom view - extensible collapsexpendview
js-bom
What happens when the MySQL union index ABC encounters a "comparison operator"?
Annotation only integration SSM framework
微信小程序:全局状态变量的使用
= = relation between int and integer
推荐扩容工具,彻底解决C盘及其它磁盘空间不够的难题
本地文件秒搜工具 Everything
Echart柱状图:堆叠柱状图显示value
免费录屏软件Captura下载安装
Waterfall flow layout of uni app Homepage
Test logiciel - résumé des FAQ d'interface
Uniapp hides the scroll bar of scroll view
Leetcode- first unique character in string - simple
Complete USB debugging assistant
Self summarizing