变量声明被提升到其作用域顶部

huangapple go评论62阅读模式
英文:

let declarations being hoisted to top of their scope

问题

如果我写这个,那么它会打印出未定义:

let a;
console.log(a);
a = 20;

但为什么这会返回一个错误呢?

console.log(a);
let a = 20;

在第二种情况下,a 被提升到顶部,因为在内存分配阶段 JavaScript 不会为 let 分配任何值,所以它返回错误。但是在第一种情况下条件是否也相似呢?为什么在第一种情况下它会打印出未定义呢?

英文:

If I write this then it prints undefined:

let a  
console.log(a)
a = 20

but why does this return an error, then?

console.log(a)
let a = 20

a gets hoisted to the top in case 2 and since JavaScript doesn’t assign any value to let in memory allocation phase it returns error. But isn’t the condition similar in case 1 also? Then why does it print undefined in case 1?

答案1

得分: 2

  • let a 就像 let a = undefined 一样

  • 故意在声明之前访问使用 let(或 constclass)声明的变量是错误的。这就是它的工作方式,因为这样做是最合理的。

绝对不要考虑它作为“内存分配阶段”的概念。

英文:
  • let a is exactly like let a = undefined

  • It’s intentionally an error to access a variable declared with let (or const or class) before the declaration. That’s just how it works, because it makes the most sense that way.

Definitely don’t think about it in terms of a “memory allocation phase”.

huangapple
  • 本文由 发表于 2023年8月5日 12:54:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定