Very confused about for/in loops and the key


#1

How do for/in loops work, and how does key work?. I am a bit confused and need clarification


#2

var colors = {
    red: "#FF0000",
    green: "#00FF00",
    blue: "#0000FF"
};

In the above,

red: "#FF0000"

is a property of the colors object, for which, red is the key and "#FF0000" is the value associated with that key.

for key in object uses the special operator, in, which attaches to one key at a time as the object is iterated over by the loop.

for (var color in colors) {
    console.log(color + ": " + colors[color]);
    //           key               value
}

Output

red: #FF0000
green: #00FF00
blue: #0000FF

Note how in the above we attach each value using subscript, or bracket notation. This is because there is no key, color since it is a dynamic variable (always changing). Inside the loop we could not write,

 console.log(colors.color)

This would raise a TypeError. We may only write property specific variables with dot notation:

colors.red
colors.green
colors.blue

when those properties exist. We may also create new properties using dot notation.

colors.gray = "#808080";

The less common approach to creating new properties is,

colors["gray"] = "#808080"

Notice the quotes on the property name? That is because the key of an object is actually a string.


#3

Thanks for the help mtf.:slight_smile:


#4

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