10. List ALL the properties - Need help understand for-in loops using x


#1

I understand for loops using "property" but I don't understand the next part with for-in loops using x. Here is some code:

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

If x in this example was replaced with "property" then I understand it iterates through all the properties. But why do we get the same result with x? x isn't defined yet so how does the compiler know that we want x to be?


#2

for (var key in object) {

}

key in this instance is a variable (obviously) but more importantly, it is a string type, not an integer (index). And JavaScript objects have implicit quotes on unbroken strings with no whitespace and only legal characters.

var object = {
    property: "property value"
};
for (var key in object) {
    console.log(key, typeof key)    // property string
}

The for..in statement is for dynamically enumerating an object for which we do not need to know any of the key names. There are no literals, save the object reference which we make dynamic by wrapping the loop with a function. There is also no order by which the loop iterates over the object property list. Objects are unordered.

Addendum

I should add that we would be over-thinking if we used this approach to see if a property exists. JavaScript objects have a method in their prototype for seeking a property: .hasOwnProperty().

console.log(object.hasOwnProperty('property'));    // true

#3

Sorry, I'm a bit confused. Are you saying that "key" and "property" are unique keywords in that they refer to the objects keys and the keys values? Then why do we get the list of properties if we replace "key" with "x"? What significance does x have in this situation? Obviously it's a variable but it's not assigned to anything currently.


#4

Always bear in mind the difference between key and "key". The latter can only ever be a three letter string literal. The former can represent every property name of the object, which are all strings. It is dynamic.

console.log(nyc['x']);    // type error no such key
x = "fullNname"
console.log(nyc[x]);      // New York City

In the above, x is the key pointer variable; nyc[x] is the value associated with that key.


#5

Consider this code:

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]);   
}

I execute this code and it lists all the properties in the array. Why does it do this if x hasn't been defined?


#6

x is defined by the var declaration in block scope. for (var x ...


#10

2 posts were split to a new topic: Print out on console.log


#11