0

I had encountered something unclear to me in 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" 
    }
};

I'm looping through this object with this 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;

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?

3 Answers3

0

var means that you're declaring a new variable, key is the name you give this variable.

Since you're looping through everthing in info.links you want to be able to call each var individually

Shogunivar
  • 1,237
  • 11
  • 18
0

Look this for a sample solution. The key represents the keys of the info.links object say blog, facebook etc, thus info.links[key] represents the value i.e,

info.links["blog"] = "JohnDoe.com", 
info.links["facebook"] = "http://facebook.com/JohnDoe"

Hope this is clear.

Look this link for loop description

Community
  • 1
  • 1
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

Go thorough this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for (variable in object) { ...
}

Variable "A different property name is assigned to variable on each iteration." In your case "facebook", "twitter" , etc are your property names in object

Ninja
  • 2,050
  • 1
  • 23
  • 27