当前位置:网站首页>Differences and recommended uses of VaR, let and const (interview)
Differences and recommended uses of VaR, let and const (interview)
2022-06-12 12:34:00 【Fashion_ Barry】
One 、 Use var Function scope declaration for --- Variable promotion mechanism
In the use of var When variables are declared , Variables are automatically added to the closest context . In the function : The closest context is the local context of the function ; stay with In the sentence , The closest context is also the function context ; If a variable is initialized without declaration , Then it is automatically added to the global context .
function add(num1, num2){
var num = num1 + num2
return sum
}
let result = add(10, 20); // 30
console.log(sum) // Report errors ,sum It's not a valid variable here Here is the function add A local variable is defined sum, Save the result of the addition operation . But variables sum It's not accessible outside the function , If the keyword in the above example is omitted var , that sum stay add After being called, it becomes accessible
function add(num1, num2){
num = num1 + num2
return sum
}
let result = add(10, 20); // 30
console.log(sum) // 30This time, , Variable sum Variable is not used var Statement , Calling add() after ,sum Has been added to Global context , It still exists after the function exits , So that you can access .
summary :
var The declaration will be taken to the function or Top of global scope , In scope Before all the code . This phenomenon is called “ promote ”(hoisting). Promotion allows code with the same scope to be used directly without considering whether the variable has been declared . But in practice , Ascension also leads to Legal but strange phenomenon .
When initializing a variable without declaration JavaScript Programming A very common mistake , It can cause a lot of problems . So , Before initializing variables , Be sure to declare variables first . In strict mode , Variables initialized without declaration will report an error
Two 、 Use let Block level scope declaration for --- Temporary dead zone ( temporal dead zone )
ES6 Newly added let Key words follow var Very similar , But its scope is block level , This is also JavaScript New concept in . The block level scope is composed of the nearest pair { } Definition , such as :if block 、while block 、function block 、 Even individual blocks are let Declare the scope of the variable .
var a;
var a; // No mistake. , The declared variables will override the declared variables
{
let b;
let b;
} // SyntaxError : identifier b It has been stated that Look at the example above :let And var Another difference is that it cannot be declared twice in the same scope . Repetitive var The statement will be ignored , And repeated let Statement Will throw out SyntaxError
for(var i = 0; i < 10; ++i){ }
console.log(i); // 10
for(let j = 0; j < 10; ++j){ }
console.log(j); // ReferenceError : j No definition Look at the above two examples :let The behavior of is well suited for declaring iteration variables in recycling . Use var Declared iteration variables Will leak out of the loop , This situation should be avoided .
summary :
Strictly speaking ,let stay JavaScript The runtime will also be promote , Single cause “ Temporary dead zone ”(temporal dead zone) Why , In fact, you can no longer use before the declaration let Variable . therefore , From writing JavaScript From a code perspective ,let The promotion and development of var It's different .
Temporary dead zone : To sum it up in a word is JavaScript engine Create variables as soon as you enter the scope , The period of time between when a variable can be accessed , It's called TDZ.
3、 ... and 、 Use const Constant declaration for
const a; // SyntaxError : Constant is declared without initialization
const b = 3;
console.log(b); // 3
b = 4; TypeError : Assign a value to a constant
except let ,ES6 It also adds const keyword . Use const Declared variables must also initialize a value , Once declared , You cannot re assign new values in its declaration cycle .const In addition to following the above rules , Other aspects and let The statement is the same ;
const o1 = {};
o1 = {}; // TypeError : Assign a value to a constant
const o2 = {};
o2.name = 'Barry';
console.log(o2.name); // 'Barry';
const o3 = Object.freeze({ });
o3.name = 'Barry';
console.log(o3.name); // undefinedconst Declarations apply only to the top-level primitive or object . let me put it another way , Assigned to const Variable Can no longer be reassigned to other reference values , But the key of the object is not limited ;
If you want the entire object to be immutable , have access to Object.freeze() , In this way, no error will be reported when assigning values to attributes , But silence will fail ;
Four 、let const I prefer that one ?
Development practice shows that , If the development process will not be greatly affected , We should use as much as possible const Statement , Unless you really need a variable that will be reassigned in the future . In this way, it can fundamentally ensure that the result of reassignment can be found in advance bug.
边栏推荐
- VGG小卷积代替大卷积 VS 深度可分离卷积
- vant 标签栏+上拉加载+下拉刷新demo van-tabs+van-pull-refresh+van-list demo
- 二叉树(纲领篇)
- 恭喜Splashtop 荣获2022年 IT Europa “年度垂直应用解决方案”奖
- Quic wire layout specification - packet types and formats | quic protocol standard Chinese translation (2) package type and format
- El select data echo, display only value but not label
- itkMultiResolutionImageRegistrationMethod
- Native JS implements the copy text function
- Dom and BOM in JS
- A short guide to SSH port forwarding
猜你喜欢

Is yuancosmos a short-term speculation or a future trend?

Lightweight ---project

itk itk::BSplineDeformableTransform

itk::SymmetricForcesDemonsRegistrationFilter

一个ES设置操作引发的“血案”

Deep analysis of advanced pointer -- advanced chapter of C language

Advanced C language -- storage of deep anatomical data in memory (with exercise)

NDT配准原理

Numpy numerical calculation basis

Advanced C language -- storage of floating point in memory
随机推荐
时序数据库 - InfluxDB2 docker 安装
Stress - system pressure simulation tool
This direction of ordinary function and arrow function
Traditional DOM rendering?
点云配准--gicp原理与其在pcl中的使用
JS method of exporting DOM as picture
[transfer]placement NEW
【您编码,我修复】WhiteSource正式更名为Mend
Promise knowledge
Records of gdcpc Guangdong Provincial Games in 22 years
ITK 多阶段配准
sublime_ Textuse
机械臂雅可比矩阵IK
Numpy数值计算基础
LDAP和SSO集成能实现什么效果?
Influxdb2.x benchmark tool - influxdb comparisons
22年gdcpc广东省赛记录
Tron API wave field transfer query interface PHP version package based on thinkphp5 attached interface document 20220602 version deployed interface applicable to any development language
AND THE BIT GOES DOWN: REVISITING THE QUANTIZATION OF NEURAL NETWORKS
[译] Go References - The Go Memory Model | golang官方文档中文翻译之内存模型