ES6变量声明问题

新增letconst

letconst是ES6新增的声明变量的命令
let用于声明变量
const用于声明常量

关于letconst相对于var的区别:

1.letconst声明的变量属于块作用域,而var声明的变量属于全局作用域和函数作用域

{
  var foo = 1
}
console.log(foo)
// output: 1
{
  let bar = 2
}
console.log(bar)
// output: ReferenceError: bar is not defined

2.var声明的变量可以在同一个作用域内不能重复声明

var num = 10
var num = 1
console.log(num)
// output: 1

letconst声明的变量在同一个作用域内不能重复声明

let num = 10
let num = 1
//  output: SyntaxError: Identifier 'num' has already been declared

3.使用var声明变量,存在“变量提升”的现象,即变量可以在声明之前使用,默认值为undefined

console.log(num)
// output: undefined
var num = 10

使用letconst则不存在“变量提升”

console.log(num)
// output: ReferenceError: num is not defined
let num = 10

关于暂时性死区(TDZ:temporal dead zone)

ES6 明确规定,如果区块中存在letconst命令,这个区块对这些命令声明的变量,从一开始就形成了封闭作用域。凡是在声明之前调用这些变量吗,就会报错

let tmp = 1
if (tmp) {
  tmp =  0
  // 因为下面使用 let 重新声明了 tmp,所以形成了TDZ
  let tmp = 2
  console.log(tmp)
  // output: ReferenceError: tmp is not defined
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值