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.