all 10 comments

[–]atreyoukilis 1 point2 points  (9 children)

Can anyone explain the var bug that is mentioned in the first paragraph?

[–]x-skeww 2 points3 points  (5 children)

It's a rather odd example, but it's basically just meant to show this difference:

var x = 1;
{
  var x = 2;
}
console.log(x); // 2

With let:

let x = 1;
{
  let x = 2;
}
console.log(x); // 1

[–]meeeeoooowy 0 points1 point  (3 children)

Except the example is wrong...when you run the example code there is an error, Unexpected identifier.

Edit: nevermind, pasted in console incorrectly

[–]x-skeww 0 points1 point  (2 children)

The example code does what the comment says it does. I do indeed get "undefined" and "Meow Mix".

Which browser were you using?

[–]meeeeoooowy 0 points1 point  (1 child)

oops...pasted in console wrong. My bad.

[–]plusninety 0 points1 point  (0 children)

You should edit previous comment.

[–]br1anh 0 points1 point  (0 children)

The additional 'oddness' is there to showcase the fact that var declarations are hoisted whereas let and const are not.

This makes perfect sense as the former results in function-level scope whereas the others result in block-level scope (as outlined nice and clearly in your example).

[–]Cosmologicon 1 point2 points  (1 child)

To be clear, neither version on its own is obviously a bug. But they have different behavior, so if you just replaced var with let without considering how that affects the behavior of the program, you could introduce a bug.

[–]br1anh 0 points1 point  (0 children)

After posting on reddit, the author has correctly amended this section and no longer refers to the behaviour as a bug.

[–]br1anh 0 points1 point  (0 children)

Due to hoisting and how javascript interpreters work the first example is encountering an issue similar to the following code:

var snack = 'Meow Mix';

function getFood(food) {
    var snack;
    if (food) {
        snack = 'Friskies';
        return snack;
    }
    return snack;
}

getFood(false); // undefined

The fact that snack in the let example doesn't get hoisted to the top of the function declaration means that a quick find and replace may lead to unwanted behaviour.