What exactly do "For-In" loops do?


#1

Hi,

I'm having a hard time understanding how "For-In" loops work. The tutorial gives us the block of code below, but doesn't dive much into the logic of how the syntax works. What exactly is a "For-In" loop supposed to do?

for (var key in object) {
// Access that key's value
// with object[key]
}

Thanks!


#2

for..in statements are used to enumerate an object by iterating over the keys. An object is like an array with a string index, and as such we can iterate over that array. Since there is no ordering in the properties of an object, the order of iteration can vary, but all the keys will be enumerated.

var object = {
    one: {},
    two: {},
    three: {},
    four: {}
};

The keys are one .. four We can list these keys using a for..in statement...

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

Output

    one
    one: {}
    two
    two: {}
    three
    three: {}
    four
    four: {}

#3

Thanks @mtf. A few follow-up questions:

  1. Given the set-up you've mentioned above, how come logging "object[key]" gives you the output "{}"? Why isn't it logging "one" instead?

  2. If you were to use the for-in loop you listed above in a function, how would you do it? What argument would you have to place if you wanted to get the same results?


#4

#1. It is logging {} because that is the associated value for each key.

#2. As a function, we would set up a generic re-usable code block.

Eg.

function list(object){
    for (var key in object){
        console.log(key + ": " + object[key]);
    }
}
var myObj = {
    one: {},
    two: {},
    three: {},
    four: {}
};
list(myObj);

one: {}
two: {}
three: {}
four: {}

The logic would be nested if we were to enumerate the internal objects.

myObj.ten = {};
myObj.ten.decimal = 10;
myObj.ten.hexadecimal = "A";
myObj.ten.binary = "1010";

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

Output

decimal: 10
hexadecimal: A
binary: 1010

#5

That clarified it. Thanks @mtf!


#6

As a final clarification pertaining to nesting...

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