let and const
let
- let 可以用來宣告一個變數,並且將它限制在一定的區塊內,而非 global
if (true) {
let x = 1;
console.log(x); // 1
}
console.log(x); // undefined
- let 如果在程式的最上方或是 function 的最上方宣告變數,let 的行為和 var 的行為是一樣的
var x = 'global';
let y = 'global';
console.log(x); // global
console.log(y); // global
- 使用 let 重覆宣告同一變數將會得到 type error;
if (x) {
let foo;
let foo; // TypeError thrown.
}
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // The scope is inside the if-block
var b = 1; // The scope is inside the function
console.log(a); // 4
console.log(b); // 1
}
console.log(a); // 5
console.log(b); // 1
const
- const 宣告的變數值不能改變,亦不能重覆宣告同一變數
const a; // SyntaxError: missing = in const declaration
const a = 5;
const a = 4; // trying to redeclare a constant throws an error
var a = 3; // a is reserved for constant above, so this will also fail