Search code examples
javascriptiteratorfor-in-loop

Understanding for in loop (javascript)


Im kinda new to JS and I'm trying to understand how for/in loop really works, here's some sample code:

phoneBook = {};
phoneBook.bill = { name : "bill", lastName "hayder" };
phoneBook.steve = { name : "steve", lastName "garcia" };

for ( obj in phoneBook )
{
    console.log(obj);
};

When I run this code I get bill and steve as an output, my question is if that's what the iterator holds why I am allowed to do phoneBook[obj] and work with that?? If I type manually phoneBook[bill] I get an error, I can only phoneBook.bill or phoneBook["bill"].

Thanks for helping.


Solution

  • When you write phonebook[something] it means that something should be an expression that returns a string, and it should find the property whose name is that string.

    In the case of phonebook[obj], the value of the variable obj will be the string "bill" or "steve", and it will then look up the corresponding property.

    If you write phonebook[bill], it tries to use bill as a variable name, and expects it to contain a string that names a property. But there is no variable named bill, so this gets an error.