28

I am following a code academy tutorial and i am finding this difficult.

The assignment is the following:

Use a for-in loop to print out all the properties of nyc.

var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

// write your for-in loop here
for (var  in nyc){
    console.log(population);
}
Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54
Rtr Rtr
  • 375
  • 1
  • 3
  • 4
  • i could try typing all the properties i want, but i want to select all – Rtr Rtr Jul 13 '13 at 07:14
  • http://jsfiddle.net/rJBf3/ – Ian Jul 13 '13 at 07:16
  • 1
    If you have so much trouble with the Codeacademy assignments, then maybe you should follow another tutorial to get a better grasp of the basics. For example: http://eloquentjavascript.net/contents.html. – Felix Kling Jul 13 '13 at 07:29

2 Answers2

57

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

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

lostsource
  • 21,070
  • 8
  • 66
  • 88
10

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}
Tomas Nekvinda
  • 524
  • 1
  • 5
  • 15