Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.