Search code examples
javascriptnode.jsclassmodulefor-in-loop

Using a for in loop inside a class results in a reference error


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


Solution

  • use let or var

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