List all the properties....but


#1

The code below worked, but I didn’t have to set the variable for the “pro” property name beforehand. How does it know what “pro” is?
Would I normally need to set the variable first?
Simple explanations are appreciated :wink:

```

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 pro in nyc){
console.log(nyc[pro]);
}

<do not remove the three backticks above>

#2

It is set (declared) right there in the loop parameters. The variable will temporarily hold each of the keys, one at a time in no particular order.

The magic of this for loop is the in operator which ‘knows’ to collect all the key names of the object and supply one at a time that redefines the iterator variable, ‘pro’.


#3

Awesome, I love magic! I think I can remember that one : )
Thank you!


#4

Off topic

ES8 was released in June of this year and will be gaining support quickly if trends keep up. It introduces the Python-like functions that retrieve keys and values of an object. That will be on your radar for further research down the line as it does not apply here.

We have the in operator as we know to collect the keys and the for loop to subscript the values. Think of the in operator as returning a list, or iterable which is unordered in construction, but with a set retrieval order similar to an array.

{1: 'one', 2: 'two', 3: 'three}

['2', '1', '3'] 

Notice the order does not match. Objects do not keep track of the order of insertion of new keys and values. The list above is a random snapshot. The order could not be predicted. However, now it is ordered so retrieval will be start to finish, first to last. That is how in works. It is this list that the key variable iterates over. Once we bind to a key, the value is its subscript.

key, object[key]

#5

Great info!
It helps to understand the whys & hows.
Appreciated, thanks again!


#6

One last thing about the above illustration to notice and think about… The list contains strings, not the numbers that were in the object. If we query the type of any key in an object, it will be string. The in iterable therefore contains strings, always.


#7

Thanks for pointing that out.


#8

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