let x = 10;
if (true) {
console.log(x);
let x = 12;
}
console.log(x);
Output: Uncaught ReferenceError: x is not defined.
Q1. Why it's give an error?
Q2. How to access x = 10 in first console in above example?
let x = 10;
if (true) {
console.log(x);
let x = 12;
}
console.log(x);
Output: Uncaught ReferenceError: x is not defined.
Q1. Why it's give an error?
Q2. How to access x = 10 in first console in above example?
let allows you to declare variables that are limited in scope. unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Like what everyone mentioned, let
is limited in scope. If you declared a variable using let
, the variable is scoped to the nearest enclosing block. Meaning that you can only use it in the same block of code, if you declared it outside a function or another block, the block can't use it.
But if you declared a variable using var
, the variable will be scoped to the nearest function block , meaning that it is global but with a restriction of : you can't use the declared value inside a function only, but still be able to define it inside the function. without having to declare it again.
For a more detailed explaination, you can check this out : What's the difference between using "let" and "var" to declare a variable?
So to answer your question : It gives an error because you used let
and it was declared outside the if
block, hence it is not defined/visible for if
block. To make it access x = 10
, use var
instead of let
.