1
var x = 10;
{
    let x = 9;
    console.log(x)
}
console.log(x)

This logs 9 and 10

how to get a log as 10 and 10? how to access x declared outside the block?

3
  • There isn't any TypeScript in your question. Read about the let declaration in the JavaScript documentation about declarations and statements. Commented Jul 18, 2021 at 10:59
  • 1
    You use blocks to limit the scope of a variable. The main reason of a block is that x is not accessible outside the block. If you want to access a variable outside a bock, declare it outside the block. Commented Jul 18, 2021 at 10:59
  • Does this answer your question? Is there a way to access a shadowed variable in JavaScript? Commented Jul 18, 2021 at 11:11

3 Answers 3

3

No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.

let x;
{
    x = 9
    console.log(x)
}
x = 10
console.log(x)
Sign up to request clarification or add additional context in comments.

Comments

0

let has block scope so it is scoped only inside the brackets. You can define it outside or use var instead of let keyword as below:

{
 var x = 10;
 console.log(x)
}
console.log(x)

With let keyword:

let x = 10;
{
 console.log(x)
}
console.log(x)

For detailed explanation about the variable scope refer this

Comments

0

you can use 'var' keyword instead of 'let', it can be accessed globally

{
    var x = 10;
    console.log(x)
}
console.log(x)

or in your solution you can also declare let outside the block and reassign it inside the block

 let x = 10;
 {
    x = 9
    console.log(x)
 }
 console.log(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.