const,var,let 區別

js中const,var,let區別

1.const定義的變量不能夠修改,並且必須初始化。 聲明的是常量html

1 const b = 2;//正確
2 // const b;//錯誤,必須初始化 
3 console.log('函數外const定義b:' + b);//有輸出值
4 // b = 5;
5 // console.log('函數外修改const定義b:' + b);//沒法輸出 

2.var定義的變量能夠修改,若是不初始化會輸出undefined,不會報錯。變量會提高函數

複製代碼
1 var a = 1;
2 // var a;//不會報錯
3 console.log('函數外var定義a:' + a);//能夠輸出a=1
4 function change(){
5 a = 4;
6 console.log('函數內var定義a:' + a);//能夠輸出a=4
7 } 
8 change();
9 console.log('函數調用後var定義a爲函數內部修改值:' + a);//能夠輸出a=4
複製代碼

3.let是塊級做用域,函數內部使用let定義後,對函數外部無影響。只管本身範圍內的事 變量不會提高post

複製代碼
1 let c = 3;
2 console.log('函數外let定義c:' + c);//輸出c=3
3 function change(){
4 let c = 6;
5 console.log('函數內let定義c:' + c);//輸出c=6
6 } 
7 change();
8 console.log('函數調用後let定義c不受函數內部定義影響:' + c);//輸出c=3
複製代碼
相關文章
相關標籤/搜索