当前位置:网站首页>The difference between VaR, let and Const
The difference between VaR, let and Const
2022-04-23 06:50:00 【Yao Cen】
Catalog
Variable
ECMAScript A variable is loose typing Of , That is, variables can be used to hold any type of data , Each variable is just a named place holder for holding any value .
There are three keywords to declare variables :var let const,var stay ECMAScript Can be used in all versions of ,let and const Only in ECMAScript6 And later versions .
var
var message;
This code declares a code named message The variable of , Can be used to hold any type of value . Without initialization , Will save a special value undefined.
var message = ' Yao Cen '
message = 10 // legal But not recommended
message It's just defined as a variable that holds the string value , Initializing a variable does not mark it as a string type , It's just a simple assignment . You can change the saved value later , You can also change the type of value , But it's not recommended .
var message = 10
message = 20
message = 73
console.log(message) //73
Use it over and over again var Declare the same variable It's OK, too .
var message = ' Yao Cen ',
num = 5,
text = false;
because ECMAScript It's loose type , therefore Variables initialized with different data types can be declared in one statement , Line breaks and indents are not necessary , But it helps to understand .
In strict mode , Cannot define the name eval and arguments The variable of , Otherwise, it will lead to grammatical errors .
var Declaration scope
ES6 Previously, there were only global scope and function scope ,var It can be used as Global scope , It can also be used as Function scope .
// Global scope
var message = ' Yao Cen '
function test() {
// Function scope
var message = ' Fei a '
console.log(message) // Fei a
}
test()
console.log(message) // Yao Cen
Use var Define a variable inside the function , This means that the variable will be destroyed when the function exits .
If Defining variables within functions ignores var, You can create a global variable ; But it's not recommended , Global variables defined within a local scope are difficult to maintain , It can also cause trouble , It cannot be directly concluded that var Is it intentional . In strict mode , If you assign values to undeclared variables in this way , Will throw an error .
Variable Promotion
console.log(message) //undefined
var message = ' Yao Cen '
// amount to
var message
console.log(message)
message = ' Yao Cen
Variables declared with this keyword are automatically promoted to the top .
let
let and var It's about the same , But there are important differences ,let The scope of the declaration is Block scope .
if(true) {
var message = ' Yao Cen '
console.log(message) // Yao Cen
}
console.log(message) // Yao Cen
if(true) {
let name = 'yc'
console.log(name) //yc
}
console.log(name) // Report errors
name The scope of a variable is limited to within a block , So you can't reference... Externally .
let name
let name // Report errors
let Redundant declarations are not allowed in the same block scope .
js The engine records the identifier used for variable declaration and its block scope , Therefore, nesting the same identifier will not report an error , This is because there are no repeated declarations in the same block .
var name
let name // Report errors
These two keywords do not declare variables of different types , They simply indicate how variables exist within the relevant scope .
Temporary dead zone
let The declaration will not be promoted in the scope .
console.log(name) // Report errors
let name = 'yc'
stay let Undeclared variables cannot be referenced in any way before declaration . stay let The moment of execution before the declaration is called Temporary dead zone , Any reference to a variable is thrown at a later stage .
Block level scope
let name = 'yc'
console.log(window.name) //undefined
let Even if declared in the global scope, it will not be mounted in window Under the object , however let The declaration still occurs in the global scope , The corresponding variables will be stored in the life cycle of the page .
for In the loop let Statement
stay let Before appearance ,for The iteration variables defined by the loop will penetrate outside the loop body .
for(var i=0;i<5;i++) {
setTimeout(()=>console.log(i),0)
}
//5 5 5 5 5
for(let i=0;i<5;i++) {
setTimeout(()=>console.log(i),0)
}
//0 1 2 3 4
When exiting the loop , The iteration variable holds the value that causes the loop to exit 5, When the timeout logic is executed later , be-all i It's the same variable , The output is the same final value .
While using let When declaring iteration variables ,js The engine declares a new iteration variable for each iteration loop in the background , Every setTimeout All references are different variable instances . This behavior of declaring an instance of an independent variable per iteration applies to all styles of for loop , Include for in and for of.
const
const And let Almost the same , The difference is that it must declare variables at the same time Initialize variable , Modifying the declared variable will report an error .
const num = 7
num = 8 // Report errors
const num = 7
const num = 9 // Cannot repeat declaration
const Also belong to Block level scope , Assignment declaration cannot be repeated , There is Temporary dead zone .
const num = {
name:'yc',
age:24
}
num.age = 18
console.log(num)
const The declaration restriction applies only to the... It points to References to variables , If you are referring to an object , Then it is possible to modify the properties of this object .
for(const i=0;i<5;i++){
} // Report errors
for(const key in {
a:1,n:9}) {
console.log(key) //a n
}
const Cannot be used to declare iteration variables , But it can be declared that it will not be modified for Loop variable , That is, each iteration just creates a new variable .
difference
- var: Mount the top-level object under the global scope window Next ; Undeclared variables are implicitly created as global variables ; Assignment can be declared multiple times ; Variable Promotion
- let: Block level scope , Even in the global context, in the block level scope ; Cannot repeat declaration in the same block , It can be assigned repeatedly ; Variables cannot be accessed before they are declared , There is a temporary dead zone
- const: Block level scope ; Declaration and assignment cannot be repeated ; There is a temporary dead zone ; Read only constants , Must be initialized , The variable points to the memory address unchanged
summary
var Variables that are not declared and directly assigned will be automatically hung under the top-level object , It will cause confusion of global environment variables .var You can declare the same variable multiple times without error , It will also make the code difficult to maintain . and ES6 Newly added let and const Objectively, it provides better support for the language's more precise declaration scope and semantics , Use let and const Helps improve code quality .
版权声明
本文为[Yao Cen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230552213405.html
边栏推荐
猜你喜欢
SiteServer CMS5.0使用总结
VHDL finite state machine (FSM) code example
Error in created hook: “ReferenceError: “Promise”未定义“
FOC SVPWM function pwmc_ Setphasevoltage parsing
Devexpress Gridview 添加全选列
Analysis and setting of dead time
获取当前一周的时间范围
MOS tube characteristics and conduction process
C# Task.Delay和Thread.Sleep的区别
Set up a personal blog of jpress
随机推荐
深入理解控制反转和依赖注入
2022ldu winter vacation training - program patch
C# Dapper 基本使用 增删改查事务等
Set up a personal blog of jpress
Redux概述
千呼万唤始出来
Unity3D对象池的理解与小例子
.Net Core 下使用 Quartz —— 【6】作业和触发器之触发器的日历
ASP.NET CORE配置选项(下篇)
查漏补缺(八)
SQLite compilation
VHDL arbitrary frequency divider (50% duty cycle)
C# 监听WMI事件
oninput 一个函数达到控制多个oninput的效果(将本输入框的内容作为参数)【很实用,很实用】
MOS tube characteristics and conduction process
.Net Core3.1 使用 RazorEngine.NetCore 制作实体生成器 (MVC网页版)
Palindromic Primes
服务器常见错误代码 总结
获取当前一周的时间范围
uniapp 自定义搜索框适配小程序对齐胶囊