Reputation: 31
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?
Upvotes: 1
Views: 6875
Reputation: 586
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)
Upvotes: 0
Reputation: 1403
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
Upvotes: 0
Reputation: 2998
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)
Upvotes: 3