#10 List ALL the properties


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

for(var x in nyc) {

this code works but i dont get how x is connected to nyc. I never defined it. at first i wrote var x = nyc.property but then deleted it to see if it works without it and i did. and now i just dont understand how the code knows that x is the properties in nyc. or is the loop defining it in the paranthesis?


Yes you did. var x.

When used as the iterator of a for..in loop, x gets defined as a string.

in is an operator that seeks keys within its context object, in the case above, that is nyc. x is given one key at a time, in any order since objects don't know when items were inserted.

for (var key in object) {
    console.log(key + ": " + object[key]);

Think of objects as iterables. There are three such iterable object classes in JavaScript: Object, Array and String. In the case above, nyc is an instance of the Object() constructor, even while we wrote as a literal, {}, So therefore it is iterable, and in lets us do it, one property at a time.

for (var iterator in iterable) {


We should only use in when iterating objects, and not when iterating arrays. They are best iterated with (var i = 0; i < array.length; i++). There is a technical reason for this that will come up later in your studies.

From a terminology standpoint, {} represents an empty object literal. When we write the constructor assignment,

var object = new Object();

we get, {}. The exact same thing as var object = {} only more verbose. Once we know what the object constructor is and how to use it, we can forego it in favor or writing a literal off the hop.

Objects are like arrays in one sense, but their indices are arbitrary strings.

 [ propertya, propertyb, propertyc ]



where a property consists of one unique key, and an associated object, a value.

key: value  => property

We may also refer to properties as members.

JavaScript (at least not ES5) does not have sets in the normal sense but we can treat an object like one since by definition a set has no duplicates. Objects have no duplicate keys. Their values may be the same, without effect.


cool. thank you! makes sense.


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