简体   繁体   中英

Block scope with “let” keyword

Example 1 : the result is what I expected.

If we declare let inside of block, it shouldn't access from outside scope.

{
  let privateScope = 1;
  function thing() {
    privateScope = 2
  }
}
console.log(typeof privateScope); //undefined

Example 2 : variable can be accessed outside scope!

{
  let privateScope = 1;
}
console.log(typeof privateScope); // number

Why can privateScope be accessed from outside the block in Example 2 ?

 { let privateScope = 1; } console.log(typeof privateScope); 

Here's your example in an SO snippet with ES2015 checked. As you can see when you run it, privateScope is undefined. I can only assume StackBlitz is doing something odd when transpiling the code, or it's a configuration error.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM