JS 中 var、let 与 const 的用法和区别
2020-09-29 本文已影响0人
limengzhe
var、let与const都是JavaScript中声明变量/常量的关键字。
var
- 声明的变量可以被再次声明并覆盖;
var a = 1;
var a = 2;
console.log(a); // expected output: 2
- 会造成变量提升(已声明,未赋值);
console.log(a); // expected output: undefined
var a = 1;
- 在
if和for循环中声明的变量会泄露成全局变量并且覆盖之前声明的变量。
// 泄露
if (true) {
var a = 1;
}
console.log(a); // expected output: 1
// 泄露
for (var i = 0; i < 5; i++) {
// some function
}
console.log(i); // expected output: 5
// 不泄露
function b() {
var c = 2;
}
console.log(c); // ReferenceError: c is not defined
let
- 不允许重复声明;
let a = 1;
let a = 2;
console.log(a); // SyntaxError: Identifier 'a' has already been declared
- 不会造成变量提升;
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 1;
-
具有块级作用域,声明的变量只在所在的
{}代码块内有效。
if (true) {
let a = 1;
}
console.log(a); // ReferenceError: a is not defined
const
-
const用来声明常量,即不允许重新赋值(修改变量指向的内存地址),也不允许重复声明;
// 不允许重新赋值
const data = { a: 1 };
data = { a: 1, b: 2 };
console.log(data); // TypeError: Assignment to constant variable.
// 不允许重复声明
const data = { a: 1 };
const data = { a: 1, b: 2 };
console.log(data); // SyntaxError: Identifier 'data' has already been declared
// 允许
const data = { a: 1 };
data.b = 2;
console.log(data); // expected output: { a: 1, b: 2 }
- 不会造成变量提升;
console.log(a); // ReferenceError: Cannot access 'a' before initialization
const a = 1;
- 具有块级作用域,声明的常量只在所在的代码块内有效。
if (true) {
const a = 1;
}
console.log(a); // ReferenceError: a is not defined