js variable declaration var, const, let

1.where Declare global or local variables

var a=1;
function sum(){
    
    
	var b=2;
}
console.log(a-b);

The b declaration is inside the function, so it is not accessible outside the function
Insert picture description here

2.letDeclaring local variables is only valid in the code block where the let command is located. The
correct use is: use it wherever it is defined

var a=1;
function sum(){
    
    
	let b=2;
	console.log(a-b);//返回值为-1
}

Wrong use: internally defined and externally unusable

var a=1;
function sum(){
    
    
	let b=2;
}
console.log(a+b); //错误类型

Translation: b is the definition
Insert picture description here

3.const Declare a read-only constant. After the variable is declared and assigned, it cannot be changed

const c=3;
c+=2;//尝试改变c的值
console.log(c)

Translation: The assignment to c is invalid
Insert picture description here

Guess you like

Origin blog.csdn.net/isfor_you/article/details/110374806