const, let, var
var will promote the variable in the scope, let not
console.log(str)
var str = 'foo'
Output result:
console.log(str)
let str = 'foo'
Output result: 在初始化以前,不能获取str
Comparison description:
var
Variable promotion let
is performed without variable promotion. This can be summarizedVariable promotion: Is to promote the definition of the variable to the front of the scope, using the following code analogy
console.log(str)
var str = 'foo'
// 上方代码等价于下方代码
let str;
console.log(str);
str = 'foo'
Scope
The aforementioned var
are 变量提升
in 作用域
perform the lift inside, then compare the first var
and let
scope
The scope of var :
- Global scope
- Function scope
Scope of let
- Global scope
- Function scope
- Block scope
{}
Block scope
{
var str = 'foo'
}
console.log(str);
Output result:
{
let str = 'foo'
}
console.log(str);
Output result: It can str没有定义
be seen that let
there are block-level scope {}
constraints, but var
no
Function scope
function print(){
var str = 'foo'
console.log('print内部:', str)
}
print()
console.log('print外部:', str)
Output result:
function print(){
let str = 'foo'
console.log('print内部:', str)
}
print()
console.log('print外部:', str)
Output result: The output result of
using let
and var
defining variables is the same. Functions can constrain the defined variables. Therefore, the two ways of defining variables have function scope.
Think about it, output the result
var str = 'foo';
f();
console.log(str);
function f() {
console.log(str);
var str = 'bar';
console.log(str);
}
Output result:
Variables with the same name cannot be used in the let scope
// 这种情况会报错
let iNum = 90
let iNum = 23
// 这种情况不会报错(建议不要有这种编码习惯)
var iNum = 90
var iNum = 23
const
const
Is added on let
the basis ofRead onlyProperty, const is immutable when defining the basic type, and the address of the object is required to be unchanged for the object
// 这种情况就会报错
const obj = {
}
obj = {
}
let student ={
name:'foo', age:12}
const obj = student;
console.log(obj)
student[name]='radish'
console.log(obj)
Output result:
found that the obj
object has name
changed
Suggest
Try not to use it var
to define a variable, give priority to it const
, and consider using it when the variable needs to be changed let
, such as in a for
loop.