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?

Upvotes: 0

Views: 109

Answers (1)

Rich Churcher
Rich Churcher

Reputation: 7654

{
  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.

Upvotes: 3

Related Questions