0

I just read the discussion about var and let in Kyle Simpsons "You Dont Know Javascript."

Chapter 2: Nested Scopes

The function foo uses block declaration of variables with let, the function bar uses ordinary declaration with var. For my clarity, in this example, the variables b and c are actually available in the same scopes, correct? So what is the point of presenting the foo function here?

function foo() {
    var a = 1;
    if (a >= 1) {
        let b = 2;

        while (b < 5) {
            let c = b*2;
            b++;
            console.log(a + b); 
        }
    }   
}

function bar() {
    var a = 1;
    if (a >= 1) {
        var b = 2;

        while (b < 5) {
            var c = b*2;
            b++;
            console.log(a + b); 
        }
    }   
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
TMOTTM
  • 3,286
  • 6
  • 32
  • 63
  • 1
    The statement before the example says "Besides some nuanced details, the scoping rules will behave roughly the same as we just saw with functions:". Sounds like he's just repeating the example. – Jerinaw Jul 01 '18 at 13:41
  • in `bar` b is available outside of if statement – Hikmat G. Jul 01 '18 at 13:43
  • Possible duplicate of [What's the difference between using "let" and "var" to declare a variable in JavaScript?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav) – RIYAJ KHAN Jul 01 '18 at 15:01
  • Not a duplicate, because I understand the difference. After reading the answers, I understand that my interpretation of `let` was to assume, that a variable is available only to the declaring scope and no inner scope. – TMOTTM Jul 01 '18 at 20:39

2 Answers2

4

In the foo function the b variable is not accessible outside of the if statement as well as the c variable is not accessible outside of the while.

The reason for this is that let declared variables are block scoped.

For example the following log(b) will result in b is undefined:

function foo() {
    var a = 1;
    if (a >= 1) {
        let b = 2;

        while (b < 5) {
            let c = b*2;
            b++;
            console.log(a + b); 
        }
    }   

    console.log(b); 
}
mpetrov
  • 391
  • 2
  • 8
  • Ok, that is fine. I was kind of confused in the context of the text (inner / lower scope), where a variable declared with `let` still is available to the inner scope of the declaration scope. I was understanding `let` as declaring exclusively to the current scope and no inner scopes. – TMOTTM Jul 01 '18 at 20:37
1

var scope is the nearest function block, while let is only visible in the nearest pairs of {...}.

Thus, in bar() you could use b and c outside the if statement because they "belong" to the whole function.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32