The difference between const, let, var

const, let, var

var will promote the variable in the scope, let not

console.log(str)
var str = 'foo'

Output result:

Insert picture description here

console.log(str)
let str = 'foo'

Output result: 在初始化以前,不能获取str
Insert picture description here
Comparison description:

varVariable promotion letis 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 varare 变量提升in 作用域perform the lift inside, then compare the first varand letscope

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:
Insert picture description here

{
    
    
	let str = 'foo'
}
console.log(str);

Output result: It can str没有定义
Insert picture description here
be seen that letthere are block-level scope {}constraints, but varno

Function scope
function print(){
    
    
    var str = 'foo'
    console.log('print内部:', str)
}
print()
console.log('print外部:', str)

Output result:
Insert picture description here

function print(){
    
    
    let str = 'foo'
    console.log('print内部:', str)
}
print()
console.log('print外部:', str)

Output result: The output result of
Insert picture description here
using letand vardefining 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:
Insert picture description here

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

constIs added on letthe 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:
Insert picture description here
found that the objobject has namechanged

Suggest

Try not to use it varto define a variable, give priority to it const, and consider using it when the variable needs to be changed let, such as in a forloop.

Guess you like

Origin blog.csdn.net/weixin_44736584/article/details/108847481