List ALL the Properties!


#1

how does this code work when x is not even defined

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

// write a for-in loop to print the value of nyc's properties
for(var x in nyc){console.log(nyc[x]);

};

#2

note:
this is the code in the hint

and when i replace x with z or any thing it does work too


#3

Actually, x is defined...

for (var x in nyc) {

}

Notice the var declaration? That declares it, and for..in assigns it key names (defines it) as it iterates through the nyc object.

function listValues(object){
    for (var key in object) {
        console.log(object[key]);
    }
}
listValues(nyc);

#4

The rationale behind declaring a key variable directly inside the for..in is to emulate block scope. In ES6 this is a reality, but in previous JS versions it is not. At least by doing this, we start with a fresh variable, and if we are inside a function, it will be scoped locally. Of course, any such variable that exists by the same name (if the loop is in global context) will be overwritten.

function listKeys(object){
    for (var key in object) {
        console.log(key);
    }
}
listKeys(nyc);

#5

@mtf

please i need more explanation on these two codes
i used for (var x in nyc)
in the first one i got the property keys printed out
whereas in the second one (var x in nyc) printed the values
what is different?

// first code from lesson 9
var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

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

/* result
fullName
mayor
population
boroughs
*/

// second code from lesson 10
var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

// write a for-in loop to print the value of nyc's properties
for(var x in nyc){console.log(nyc[x]);

};

result;
New York City
Bill de Blasio
8000000
5 */