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 trialbrandonlind2
7,823 PointsCan someone explain to me why my for in loop isn't working?
var students= [
{
name: "sam" ,
track: "ios" ,
achievements: 50 ,
points: 300,
},
{
name: "jack",
track: "java",
achievements: 50 ,
points: 200,
},
{
name: "dave",
track: "front end dev" ,
achievements: 50 ,
points: 600,
}
];
for(i=0; i < student.length; i+=1;) {
student= students[i];
for(var prop in student) {
console.log(student[prop]);
}
}
3 Answers
Sergey Podgornyy
20,660 PointsYou need to delete semicolons in the first for elements, and change student.length to students.length
for(i=0; i < students.length; i+=1) {
student= students[i];
for(var prop in student) {
console.log(student[prop]);
}
}
This code should work
Neil Anuskiewicz
11,007 PointsApparently you can't use for..in when you use array iteration (See http://stackoverflow.com/questions/5263847/javascript-loops-for-in-vs-for).
As a separate matter, you might want to run your code through JSLint (http://www.jslint.com). It detects a lot of little errors. As a Treehouse student and JavaScript beginner myself, I think JSLint is going to turn out to be very useful.. :-)
I hope this helps.
brandonlind2
7,823 PointsThanks man!!
Sergey Podgornyy
20,660 PointsYou are welcome ;)
Jacob Mishkin
23,118 PointsJacob Mishkin
23,118 PointsThe only problem with this for loop is that you are not initializing the i variable. you need to add the key word var prior to i= 0;
Sergey Podgornyy
20,660 PointsSergey Podgornyy
20,660 PointsAs I know it's not important. Without
var
we just define local scope. It's more then enough for this exercise.Jacob Mishkin
23,118 PointsJacob Mishkin
23,118 Pointsyou mean without var you define the global scope. loops do not create scope in JS.
Sergey Podgornyy
20,660 PointsSergey Podgornyy
20,660 PointsYes, sorry. You are right, global scope. But this code works fine without initialize the
i
variale. You can check this on JSfiddle