0

Why does block A result in a ReferenceError?

const something = 'something';

console.log ();

try {

    // Block A
    {

        const something = something;

    }

} catch (e) { console.log(e); }

console.log ();

// Block B
{

    const something = 'somethingElse';

}

This prevents one from shadowing a variable with one of its properties.

Stephen Carboni
  • 193
  • 1
  • 5
  • 1
    You can just change the name of the outer variable and move on. Unless I am missing something this does not really pose a real-life issue. – Thilo May 08 '18 at 10:40
  • check doc [block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block) – Durga May 08 '18 at 10:42
  • @Thilo It's good to understand how the language works, and I think that's what Stephen is going for here. – Alexander Wallin May 08 '18 at 11:13

1 Answers1

0

Because const variables are hoisted, and you are trying to access it in its own temporal dead zone. There are three ways of solving this:

  • Just use a different variable name, don't shadow non-global variables. It's confusing.
  • Don't use const, don't make a local scope - just reassign the variable inside the block. This solution might not be applicable everywhere.
  • Use an IIFE:

    const something = 'something';
    (function(something) {
    //        ^^^^^^^^^ inner scope
        …
    }(something));
    //^^^^^^^^^ outer scope
    
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks. I see now what the issue is. From all the JS guides I've read, I got the impression that const and let were spared from hoisting. – Stephen Carboni May 09 '18 at 15:25