1
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?

Nirav Patel
  • 480
  • 4
  • 14
  • A1 - unlike `var`, `let` variables aren't hoisted A2 - you can't ... with the error message, Firefox's message is a little clearer in this code `ReferenceError: can't access lexical declaration 'x' before initialization` – Jaromanda X Jan 17 '17 at 05:55
  • remove the let inside the if condition its work's..Refer [What's the difference between using “let” and “var” to declare a variable?](http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable) – prasanth Jan 17 '17 at 05:56
  • By having the `let` definituon "somewhere" inside your `if`-block you have made this variable local to that whole block. If you want to be able to reference the value, that was set outside the block, just leave away the `let` in front if the `x=12`. But that will of course reset the original variable `x`. – Carsten Massmann Jan 17 '17 at 05:59
  • before changing inner scope value of X = 12 i want to use x value as x = 10. if i remove the let in if condition it change the value of outer x and second console give me out as a 12. but i want to keep 10 outside of if condition and need to change value of x in inside. – Nirav Patel Jan 17 '17 at 06:05

2 Answers2

1

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.

Mitesh Pant
  • 544
  • 2
  • 15
0

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 .

Community
  • 1
  • 1
Kaynn
  • 3,335
  • 2
  • 17
  • 23