一、let const var之间的区别
二、代码演示
<script> // 1、const let不存在变量提升 var 存在变量提升 //var console.log(`fullName`,fullName);//fullName undefined //var fullName='cai'; /* var 声明变量的方式会存在变量提升,var在声明变量之前,首先会将var fullName提升到代码块的最前面 */ //let console.log(`fullName`,fullName);//Uncaught ReferenceError: Cannot access 'fullName' before initialization let fullName='cai'; //const //console.log(`fullName`,fullName); //const fullName='cai'//let const.html:13 Uncaught ReferenceError: Cannot access 'fullName' before initialization </script>
var fullName='cai'; function f(){ console.log(`fullName`,fullName)//undefined if(false){ var fullName='kiki' } } f();
let fullName='cai'; function f(){ console.log(`fullName`,fullName)//cai 全局作用域 if(false){ //块级作用域 只在当前范围内生效 let fullName='kiki' } } f();
// 暂时性死区 声明变量之前不能提前给变量赋值 var fullName='cai' if(true){ fullName='test' let fullName;//声明变量之前不能提前给变量赋值 }
//不能重复声明 function f(){ let a='10'; let a='20'; }
var fullName='cai' console.log(`window`,window.fullName);//cai //let 和const声明的变量不会挂载在window对象下面 const fullName1='cai' console.log(`window`,window.fullName1);// undefined
//const声明的基本类型变量的值不能被改变,引用类型可以 const familyName='cai'; //familyName='cai1' console.log(familyName)//Uncaught TypeError: Assignment to constant variable. const fruit=['apple']; fruit[0]='orange'; console.log(fruit);//['orange']