let和var的区别

2020-03-02  本文已影响0人  Will_板凳

作用域不同

let的作用域制作用于当前代码块

{
var str1 = "刘能";
let str2 = "赵四";
}
console.log(str1);//undefined
console.log(str2);//str is not defined

let的作用域不会被提升

{
  console.log(str);//undefined
  var str = "刘能";
}

相当于

{
 var str ;
 console.log(str);//undefined
 str = "刘能";
}

let会直接报错

 { 
   console.log(str);//str is not defined
   let str = "刘能";
}

let在相同的作用域下不能声明相同的变量

{
  var str = "刘能";
  var str = "赵四";
  console.log(str);//赵四
}



{
  let str = "刘能";
  let str = "赵四";
  console.log(str);//Identifier 'str' has already been declared
}

let会覆盖前面的变量,而let不允许声明相同变量,会报错

上一篇下一篇

猜你喜欢

热点阅读