There may be times where you need to cycle through the properties in an object as you try to look for something. This is especially useful when an object is set up like a dictionary, among other things. You can't use a regular for loop for this like you can with an array. JavaScript has its own special construct, the for...in loop.
You start with some object you want to work with. This loop will take the name of each property in the object. It assigns that name to the variable, in this case propertyName. You can get the value of the property using array notation by passing the variable to the object. You'll see this in action in a moment.
Let's start with a quick object. This one uses string properties because we need some with spaces in them (like
"living room"
). Technically, kitchen and office don't need the quotes. I have them here for a consistent look.
If I want to display all the colors in the house, I'd want to cycle through all these properties and display the values. Now even though there are three properties, we can't use a standard for loop. It just doesn't work.
Using the same roomColors object from above, let's rewrite that last broken loop and try again.
i
may be a coding standard for loops, but why not give a name that means something
to us? Since these properties are the names of rooms, why not use room
for the variable instead?
Remember the golden rule of coding: the code should always be readable.
We still need a variable, such as i
, to iterate through what we're doing. This goes through the roomColors object and takes each property and passes its name
to i
in this case. That's what gets printed to console window.
That's great if you need the names of the properties. But we want the values—the colors—don't we? This is where the array notation of objects really comes in handy. Let's modify our code a little to do this.
We could even put the two ideas together:
It all depends on what you need for any given project. You could even use a loop like to this to change values of properties and so on.
You can easily insert an if statement into the loop to check for specific properties. You're not even limited to that.
How about, as we go through the properties, let's change the colors.