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.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.