The similarities and differences between let, const and var (features and differences)

describe

var, const, let can all declare variables,

For example

var a = 1;
const b = 1;
let c = 1;

1. The characteristics of var

1. There is variable promotion

console.log(a);//undefined
var a = 10;
var a;
console.log(a);//unfined
a = 10;
console.log(a);//10

2. A variable can be declared multiple times, and the later statement will overwrite the previous statement

var a = 10;
var a = 20;
console.log(a);//20

3. Using var in a function is local

var a = 10;
function change(){
    var a =20;
    return a;
}
condole.log(a);//10
console.log(change());//20;

4. If the var declaration variable is not inside the function, the variable is global

var a = 10;
function change(){
    a = 20;
}
change();
console.log(a);//20;

2. The characteristics of let

1. There is no variable promotion, and the variable cannot be used before let is declared (temporary dead zone).

console.log(a);//因为a后面使用let声明的,这里会报一个错误
let a = 10;

2.let can declare variables, which are valid in block-level scope

{
    let a = 10;
}
console.log(a);//块级作用域,这里会报错,a is not defined

3.let does not allow repeated declarations in the same scope,

let a = 10;
let a = 20;
//报错

Three.const

Let has some consts, and on the basis of let, it has the following characteristics:

1. const can declare read-only variables, after declaration, the value cannot be changed

const a = 10;
a = 20; //Assignment to constant variable

2. The variable declared by const is not that the value cannot be changed, but the memory address pointed to by the variable cannot be changed. If an object is declared with const, the properties in the object can be changed

const cat = {
    name:'Tom',
    age:3
}
cat.age = 4; //可以改变对象内属性

cat={
    name:'Garfield',
    age = 4
}//'cat' has already been declared

3. const must be initialized

const a;//SyntaxError: Missing initializer in const declaration
const a=10;

the difference

1. Variable promotion

The variable declared by var has variable promotion, the variable can be used before the declaration, and the value is undefined

The variables declared by let and const must be declared first and then used. If they are used before the declaration, an error will be reported

2. Scope

let and const have block-level scope

And var does not have block-level scope

3. Repeat statement

var allows repeated declaration of variables

let and const do not allow repeated declaration of variables in the same scope

4. Modify the declared variable

Both var and let can modify declared variables

const declares a constant, and the constant value cannot be changed. If the declaration is an object, the properties in the object can be modified, but the object itself cannot be modified, that is, the memory address cannot be modified

Guess you like

Origin blog.csdn.net/Angel_Tears_/article/details/127281162