Why does re-declaring an argument inside of a try/catch throw a ReferenceError?

后端 未结 4 646
北恋
北恋 2020-12-28 13:20

I mistakenly wrote a re-declaration of an argument as a const in a function and instead of throwing SyntaxError: Identifier \'bar\' has already been decla

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 13:57

    It's a myth that const and let aren't hoisted at all. They're half-hoisted. :-) That is: Within a block, if const bar or let bar (or class bar { } for that matter) appears anywhere in that block, then bar cannot be used prior to that declaration in the block — even if it exists in a containing scope. This area between the beginning of the block and the declaration is called the Temporal Dead Zone:

    function foo(bar) {
      // `bar` is fine here
      try {
          // Temporal Dead Zone, `bar` cannot be used here
          console.log(bar);
          // End of TDZ
          const bar = 123;
          // `bar` would be fine here
      } catch(err) { console.log(err) }
    }
    foo(456);    
    

提交回复
热议问题