What causes the different behaviors between “var” and “let” when assign them a returned value of a function which throws an error

送分小仙女□ 提交于 2019-11-28 02:07:19

Declarations of var variables get hoisted - the variable name initialization gets hoisted to the top of the containing function (or, if no function, to the top of the outer block). So

var withVar = (function() {throw 'error!'})()

is parsed by the interpreter as

var withVar;
withVar = (function() {throw 'error!'})()

The same is not true for let - let variables become initialized once the let __ line runs. When there's assignment, the right-hand side is parsed first; if the right-hand side throws an error, it never gets to the left-hand side, and the variable declared with let never gets properly initialized; it'll stay in the demilitarized zone / temporal dead zone forever, so trying to reassign it throws an error.

It's kind of weird because the code is being run in the console - ordinarily, JS runs inside a <script> tag, and if such an error occurs, usually no more code will run, and the fact that a variable declared with let is no longer reassignable is the least of your worries.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!