JS 中 var、let 与 const 的用法和区别

2020-09-29  本文已影响0人  limengzhe

varletconst 都是 JavaScript 中声明变量/常量的关键字。

var

var a = 1;
var a = 2;
console.log(a); // expected output: 2
console.log(a); // expected output: undefined
var a = 1;
// 泄露
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 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
上一篇 下一篇

猜你喜欢

热点阅读