TMOTTM
TMOTTM

Reputation: 3381

Difference between var and let

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); 
        }
    }   
}

Upvotes: 0

Views: 2164

Answers (2)

user7270034
user7270034

Reputation:

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.

Upvotes: 1

mpetrov
mpetrov

Reputation: 391

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); 
}

Upvotes: 4

Related Questions