-1

I noticed a bug in my code a couple days ago and have no idea why it's happening. It seems a variable defined in a lower scope is somehow jumping up to a higher one. Anyone know what's happening here? Dumbed down code:

console.log(a) 

for(var k = 0; k < 5; k++)
    var a = 5 

console.log(a) 

The first console log always prints undefined But the second console log always prints 5? Shouldn't variable a only exist in the for loop's scope and be cleared from memory once the for loop is done?

jomak73
  • 137
  • 10

1 Answers1

3

Variables defined with var are "function scoped", so they are accessible anywhere in the function. let and const however have "block scoping", they will behave like you expect:

{
  let a = 1;
  var b = 2;
}

console.log(a, b); // not defined, 2
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151