1

Why does the console.log return undefined? Even if let limits the scope of v, that scope is within the if statement (which is also where the console.log is), so shouldn't it still get logged?

var x = 1;

if(x < 10) {
    let v = 1;
    v = v + 21;
    v = v * 100;
    v = v / 8;

    console.log(v);
}

console.log(v); //v is not defined
mangocaptain
  • 1,435
  • 1
  • 19
  • 31
  • 1
    `v` isn't defined outside the `if` statement, hence the undefined output from `console.log` outside of the if – Andrew Li Aug 10 '16 at 01:57
  • 2
    You are saying that the log statement within the if is reporting undefined? – Robert Moskal Aug 10 '16 at 02:11
  • 1
    Variables being declared with let have a block scope. So these variables only can be accessed in that block where variable being declared. Because of it, the first 'console.log' can access v, but the second 'console.log' can not access v in the example code. you can see more in detail: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/let – KimCoding Aug 10 '16 at 02:17
  • 1
    @mangocaptain Which of the two log statements are you talking about? – Bergi Aug 10 '16 at 02:28
  • 2
    `console.log` only receives the value. It can't know if it was a `let` variable, a `var` variable, an expression, or whatever. So it's unrelated. – Oriol Aug 10 '16 at 02:29
  • I was referring to the 2nd console.log, but I get it now, thanks – mangocaptain Aug 11 '16 at 00:03

1 Answers1

1

Variable declared let is limited within if block.

xblymmx
  • 39
  • 2
  • 3