Need Someone To Explain "Objects II"


#1

"List all the properties!"

Link to exersice

My code

var nyc = {
fullName: “New York City”,
mayor: “Bill de Blasio”,
population: 8000000,
boroughs: 5
};


var x = “fullName”;
nyc[x] = “New York City”;


for(var x in nyc){console.log(nyc[x])}

Output>

New York City
Bill de Blasio
8000000
5

Issue

I finished this exersice, the problem is I don't understand the concept. Could somebody explain how this works, please?


#2

for-in loop is actually really simple, JS assign each property of the object to the loop iterator.


#3

Ok, I’ll try my best to explain. Read slowly:

//Make the object called nyc
var nyc = {
  fullName: “New York City”,
  mayor: “Bill de Blasio”,
  population: 8000000,
  boroughs: 5
};


/*var x = “fullName”;
nyc[x] = “New York City”;*/ //I'm not certain what the point of these is... I'm pretty sure you can go without this. 


//Create a for/in loop. Read about it if needed:
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for(var x in nyc) { //for (var x (This part creates the variable called x) in nyc) { (Specifying that it is in our nyc object)
  console.log(nyc[x]); //The variable x is all of the key names. So, the output is the key values.
  /*console.log(nyc[mayor]); Would log Bill de Blasio for example.*/
}

#4

I understand ‘for in’ loops - what I don’t understand is how logging the values works in this exersice.

var nyc = {
fullName: “New York City”,
mayor: “Bill de Blasio”,
population: 8000000,
boroughs: 5
};
var x = “fullName”;
nyc[x] = “New York City”;

for(var x in nyc){console.log(nyc[x])}

So you set var x as a string “fullName”, so now it’s the value of nyc.fullName?
Then you set nyc[x] to equal to the value of nyc,fullName?
I don’t understand how this works.


#5

let me guess, you got the inspiration here:
And if we say:

var x = "species";

then

dog[x] = "bulldog"

poor choice by th exercise, they should have put this instead:

var x = "species";
console.log(dog[x]) // bulldog

now we can use x can be used as property to get value. That they choice to show this with dog[x] = "bulldog" is really confusing


#6

Oh, I see - That makes sense. Thanks for helping me understand! :grinning:


#7

one more thing:

var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};
var x = "fullName";
nyc[x] = "Boston";
console.log(nyc)

its possible to use nyc[x] = "new value" but this will give the property a new value as you can see in the code above when you run it


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.