Javascript 中有三種宣告的保留字:var、let、const:
var: 函式作用域,最早出現的宣告方式,宣告與賦值可分開進行。let: 區塊作用域,ES6 引入,適合一般變數,宣告與賦值可分開進行。const: 區塊作用域,ES6 引入,常數,宣告與賦值須一起完成。
作用域 Scope
var是函式作用域,只有函式擋得住,寫在if或for容易變數外洩let/const是區塊作用域,只要有{}就可以擋住
function test() {
if (true) {
var a = 5;
let b = 6;
const c = 7;
console.log(a); // 5,可正常印出
console.log(b); // 6,可正常印出
console.log(c); // 7,可正常印出
}
console.log(a); // 5,可正常印出
// console.log(b); // ReferenceError: b is not defined
// console.log(c); // ReferenceError: c is not defined
}
test();
重宣告 Redeclear
var可以重宣告let/const不可以重宣告
var a = 1;
var a = 2;
console.log(a);// 2
/*------------------------*/
let a = 1;
let a = 2; // SyntaxError: Identifier 'a' has already been declared
console.log(a);
/*------------------------*/
const a = 1;
const a = 2; // SyntaxError: Identifier 'a' has already been declared
console.log(a);
重賦值 Reassign
var/let可以重賦值const不可以重賦值
var a = 1;
a = 2;
console.log(a); // 2
/*------------------------*/
let a = 1;
a = 3;
console.log(a); // 3
/*------------------------*/
const a = 1;
a = 5; // TypeError: Assignment to constant variable.
console.log(a);
提升 Hoisting
var/let/const 皆會提升,但是處理的方式不一樣:
var會被初始化為 undefined,不會報錯let/const 會進入 temporal dead zone,會出現錯誤
console.log(a); // undefined
var a = 0;
/*------------------------*/
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 0;
/*------------------------*/
console.log(c); // ReferenceError: Cannot access 'c' before initialization
let c = 0;










