0

I am using a for in loop to iterate over keys in an object like so

var Obj = {
    foo: 'bar',
    num: '1234'
}

for(key in Obj){
    console.log(key)
}

Which outputs

foo
bar

However, when I put the exact same code inside a class method, I get

ReferenceError: key is not defined

The class I'm referring to is exported via it's own module. (Not sure if that's significant, because I can't find any info on this behavior online)

So why can't for in loops be used inside classes?

Using Node V 8.6.0

Native Coder
  • 1,792
  • 3
  • 16
  • 34

1 Answers1

1

use let or var

for(let key in Obj){
    console.log(key)
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thanks! that was far too easy. Now, why did this work OUTSIDE of a class? Would you mind to point me to some documentation in your answer? I never used let when I was using a for..in loop outside of a class and it worked perfectly. – Native Coder Oct 22 '17 at 02:35
  • 1
    you should look into https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript https://www.w3schools.com/js/js_scope.asp – Sajeetharan Oct 22 '17 at 02:38
  • 1
    @NativeCoder - You should always declare all of your variables with `var`, `let`, or `const`, even when you want them to be global. – nnnnnn Oct 22 '17 at 02:55
  • Agreed. I have no idea why I though for in loops didn't require a variable declaration. But I don't want to delete the question because @Sajeetharan (and now yourself) deserve the reputation you have gained. – Native Coder Oct 22 '17 at 03:02