7

I was going through the javascript style guide by Airbnb (https://github.com/airbnb/javascript).

In section 2.2 it is explained that

let is block-scoped rather than function-scoped like var.

// bad
var count = 1;
if (true) {
  count += 1;
}

// good, use the let.
let count = 1;
if (true) {
  count += 1;
}

I didn't get why the first one is bad practise and second is bad and if both let and var are block scoped then what difference does it make, if I use either of them?

Also what is the difference between function scoped and block scoped?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ankit
  • 1,499
  • 5
  • 29
  • 46

1 Answers1

4

When something is block scoped it means that you can control the lifetime better and more intutive ways

for example

function a() {
    if (true) {
        var a = 7;
        let b = 42;
    }
}

The var a is pulled out in the scope of the function, rather than stying isolated in the block for the if, so like this;

function a() {
    var a;  // The JS compiler pulls the var out to this level
    if (true) {
        a = 7;
        let b = 42; // but keeps the let in this block.
    }
}

.. and that is counter intuitive and sometimes lead to problems -- the let does not have that problem.

Mingo
  • 78
  • 4
  • In the first example both a & b won't be visible outside the if block and in the second example, since you defined a outside if so it will be visible. Still, didn't understood the difference between function and block scoped – ankit May 09 '16 at 20:31
  • 1
    The answers in [this question](http://stackoverflow.com/questions/762011/let-keyword-vs-var-keyword) are very good -- have a look at those. – Mingo May 09 '16 at 20:33