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?
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
letdeclaration in the JavaScript documentation about declarations and statements.xis not accessible outside the block. If you want to access a variable outside a bock, declare it outside the block.