一、var宣告的變數會掛載在window上,而let和const宣告的變數不會:
var a = 100;console.log(a,window.a); // 100 100
let b = 10;
console.log(b,window.b); // 10 undefined
const c = 1;
console.log(c,window.c); // 1 undefined
二、var宣告變數存在變數提公升,let和const不存在變數提公升
console.log(a); // undefined ===> a已宣告還沒賦值,預設得到undefined值
vara = 100;
console.log(b); // 報錯:b is not defined ===> 找不到b這個變數
letb = 10;
console.log(c); // 報錯:c is not defined ===> 找不到c這個變數
constc = 10;
三、let和const宣告形成塊作用域
if(1)console.log(a); // 100
console.log(b) // 報錯:b is not defined ===> 找不到b這個變數
if(1)console.log(a);
//100
console.log(c) //
報錯:c is not defined ===> 找不到c這個變數
四、同一作用域下let和const不能宣告同名變數,而var可以
vara = 100;console.log(a); // 100
vara = 10;
console.log(a); // 10
let a = 100;let a = 10;
// 控制台報錯:identifier 'a' has already been declared ===> 識別符號a已經被宣告了。
五、暫存死區
var a = 100;if(1)
六、const
var與let const的區別
一 var宣告的變數會掛載在window上,而let和const宣告的變數不會 var a 100 console.log a,window.a 100 100 let b 10 console.log b,window.b 10 undefined const c 1 console.log c,...
var與let const的區別
一 var宣告的變數會掛載在window上,而let和const宣告的變數不會 var a 100 console.log a,window.a 100 100 let b 10 console.log b,window.b 10 undefined const c 1 console.log c,...
var與let const的區別
1.var宣告的變數會掛載在window上,而let和const宣告的變數不會 var a 0 window.a 0 let a 1 window.a undefined const a 2 window.a undefined 2.var宣告變數存在變數提公升,let和const不存在變數提公升 ...