-2

I've been working my way through the Javascript development track on Treehouse and am struggling with for in loops. I have been unable to locate any explanation of this loop in everyday language and am subsequently getting confused. What does for in actually do, and why would you use this loop as oppose to another loop? Is it basically just a way to assign a common label to each individual property of an object?

JSJunkie
  • 39
  • 5
  • Question: how do you loop through all the properties of an object? Answer: `for..in`. – In what detail *do* you understand what `for..in` does? Then it may be easier to fill in the gaps of what you're missing. – deceze May 16 '16 at 02:13
  • This post isn't a programming issue, this is just lack of research for understanding. First read this http://stackoverflow.com/help/how-to-ask and then read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in – NewToJS May 16 '16 at 02:13
  • Possible duplicate. http://stackoverflow.com/a/242888/1657076 might answer you – venkatKA May 16 '16 at 02:14

2 Answers2

2

for(key in obj) is used to traverse objects:

x = {"Sam": 5, "Billy": 9, "Joe": 3}
for(var name in x){
    document.getElementById("output").innerHTML+=(name+": "+x[name]+"  ");
}
<p id="output"></p>

Because objects do not have a .length parameter, and you cannot access them through indices.

A.J. Uppal
  • 17,608
  • 6
  • 40
  • 70
-3

actually loops are a very confusing concept for beginners. I still today remember the first time I understood what a for loop does.

basically, like other loops (while) the idea is to have something happen repeatedly. the for loop is most commonly used to make sure your commands happens for every object in something else.

for example, if you want to print all objects in an array, it would make sense to do it is with a loop hence:

for (i=0 ; i< arr.length; i++) { window.console.log (arr[i]); }
akiva
  • 2,408
  • 3
  • 27
  • 38
  • 1
    This doesn't answer the question at all, which is about the `for(var x in obj)` construct – Eric May 16 '16 at 02:21
  • @Eric - you're right. I misread the title what's the purpose of "for" in loops instead of what's the purpose of "for in" loops :-) – akiva May 16 '16 at 03:29