I came across something confusing to me within the for loop:
var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
"blog" : "JohnDoe.com",
"facebook" : "http://facebook.com/JohnDoe",
"youtube" : "http://www.youtube.com/JohnDoe",
"twitter" : "http://twitter.com/JohnDoe"
}
};
When running through this object with the following loop:
var output = "";
for (var key in info.links ) {
if (info.links.hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + info.links[key] +
'">' + key + '</a>' +
'</li>';
console.log(key);
}
}
var update = document.getElementById('links');
update.innerHTML = output;
My question is, what exactly is var key in this loop and how does it work without defining var key within the scope of this loop? In this scenario, var key takes on the values blog, facebook, etc. inside the info.links object. But why does it behave this way?