0

I stumbled upon this puzzling error when looping over JavaScript objects using the for..in construct. I have a set of dummy data similar to this:

{
  "12345678" : {
    ...
  },
  "12345679" : {
    ...
  },
  "12345680" : {
    ...
  }
}

Maybe it matters, this object is retrieved from a Firebase database using the response's built-in .val() method. It is a regular js object.

However, when traversing the object, the variable declared inside the for..in loop is somehow undefined. I've removed all surrounding code except the loop, and the error still occurs:

for (key in data) {
 console.log(data[key]);
}
// Throws ReferenceError: key is not defined

I am really baffled. How is this possible? I thought the variable passed to for..in was always available (or at least defined) inside the loop.

AL.
  • 36,815
  • 10
  • 142
  • 281
ppajer
  • 3,045
  • 1
  • 15
  • 22
  • 1
    Did you define `key` somewhere? Like `for (var key in data)`? Also, have you tried printing out `data` with something like `JSON.stringify(data, null, 4)`? – Kevin Ji Feb 14 '17 at 00:55
  • Huh, that was silly. Didn't declare as `var` anywhere. I've been messing around with this for half an hour now. I guess it's time for bed. – ppajer Feb 14 '17 at 01:01

2 Answers2

4

As mentioned in my comment, you'll probably need to define key; otherwise, you'll (probably) define a global variable, which may or may not work correctly. Also, to avoid unrelated properties from appearing in your loop, use hasOwnProperty:

for (var key in data) {
    if (!data.hasOwnProperty(key)) {
        continue;
    }

    console.log(data[key]);
}

See How do I loop through or enumerate a JavaScript object? for further information.

Community
  • 1
  • 1
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
  • Thanks for the tip on `hasOwnProperty`. The initial error was an oversight, but this is something I should actually start using. – ppajer Feb 14 '17 at 01:12
2

you just don't use the right syntax for for..in statement. You need to define key variable with var (or let if you use ES6): in order to use it in the statement:

for(var key in data){
  console.log(data[key])
}
Andrew Kovalenko
  • 6,441
  • 2
  • 29
  • 43
  • That was it, thanks! I think it's time for sleep when one starts overlooking stuff like this. :) – ppajer Feb 14 '17 at 01:05