for in loop

russian_doll

Objects in JavaScript are a lot like hashes and we can access their content the same way we would access content from a hash. What if we wanted to print out all the keys from an object? I wrote about “for loops” in a previous post and today I am going to go over a “for in” loop.


var theater = {

     name: "Angelika",

     location: "Houston",

     showing: "The Lunchbox"

};

To print all the keys to the screen you would write the following:


for(var theKeys in theater) {
     console.log(theKeys);
};

  • The “for” is a JavaScript keyword that tell us that this is a “for loop”.
  • Inside the parenthesis we see the “var” keyword, which is how we define a variable. The “theKeys” is the name of our variable.
  • Next is the word “in” which is how we can tell that this is a “for in” loop!
  • The last word we see is “theater” which is how we tell the loop what object we want to loop through.

Inside the loop in between the curly braces is where we have all the code for our loop. Above we are just writing to print our keys “theKeys” to the screen. What if we wanted to print out the values in our object? We can use the “for in” loop again.


for(var theKeys in theater) {
     console.log(theater[theKeys]);
};