使用if语句和let/const语句,不带块语句



在JavaScript中,我可以在if语句中使用var声明变量,而不需要块语句:

if (true)
  var theAnswer = 42

但是,尝试使用letconst声明变量而不使用块语句会产生错误:

if (true)
  let theAnswer = 42

Chrome抛出SyntaxError: Unexpected identifier, Firefox - SyntaxError: lexical declaration not directly within block .

if (true)
  const theAnswer = 42

Chrome抛出SyntaxError: Unexpected token const, Firefox抛出SyntaxError: const declaration not directly within block

那是什么原因?规范中有什么可以解释这种行为吗?

这将是一架没有什么好处的步兵炮。var初始化是提升的,因此该变量保证始终存在于函数内部并且始终有一个值。letconst的作用域在块/函数中,初始化不会被提升。这意味着如果允许您呈现的情况,那么像下面这样的代码将抛出:

if (false) let foo = 4;
console.log(foo);

因为let foo行永远不会执行,所以foo变量永远不会被初始化。这意味着访问foo变量总是会触发一个"时间死区"错误,就像

console.log(foo);
let foo = 4;

在没有直接块/函数包装的情况下禁止let, let将是危险的,并且提供最小的增益。

最新更新