Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Different ways to write for in loop.

What difference does it make if we use the for in loop as follow: (var key in property) or simply (key in property)? As the example in video lesson and optional case uses different for in loop methods.

2 Answers

hey for key in Object is generally used to loop through JSON Objects

Example :

var a = {name :"John", age:"44"};
 for (var key in a){
  if(a.hasOwnProperty(key){
     var key =  key // gives key like name , age ...
     var value = a[key]; // gives value for that key ex John, 44 ..
  }
}
Stanley Thijssen
Stanley Thijssen
22,831 Points

Hi Ammar,

The difference is when you use var key and just key is that when you use it for example inside a function:

          (function() {
                         for(var key in property) {
                                       console.log(a); //Works
                         }
                        console.log(a); // Works
           })();
console.log(a); //Doesnt Work.

The variable key will only be accessible inside the function now. But if you use just the key in property for in loop, your key variable will be accessible in your global scope. So outside of your function too:

          (function() {
                         for(key in property) {
                                       console.log(a); //Works
                         }
                        console.log(a); // Works
           })();
console.log(a); //Works.

So when you're not using the var word your variable will be a global variable. If you use the var keyword it will just be available inside that function or scope.