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 trialJake Ford
9,230 PointsSo "For in" is same as "Foreach" in other languages?
I think the the for in is the same as foreach in other languages. Is there not a foreach in javascript?
5 Answers
Jacob Mishkin
23,118 Pointsfor in loops are used for looping through objects in JS. for each is different in that you can loop though non-objects.
Thomas Nilsen
14,957 PointsThere is a forEach in javascript:
[1, 2, 3, 4 ,5].forEach(function(i) {
console.log(i);
})
and if interested - the implementation looks like this (simplified version):
Array.prototype.forEach = function (callback) {
for (var i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
}
Jake Ford
9,230 PointsSo use forEach to loop through arrays and use "for in" to loop through objects?
Thomas Nilsen
14,957 PointsBasically - yeah.
But you could also use 'for in' to loop over arrays and strings as well
Jacob Mishkin
23,118 Pointsfor in with objects yes. for each is perfect with arrays. Please review the answer in this stack overflow question:
a very good explanation of loops
It's a bit of a read, but its very helpful.
Jake Ford
9,230 PointsThanks, guys.
Blake Schwartz
4,282 PointsI've mostly avoided for...in loops as many people say they can be problematic; however, the author does a great job of explaining them very simply and it seems like a very useful tool. I may give it another try in the future.
Jacob Mishkin
23,118 PointsIf you are using Jquery then you can use a the $.each loop that will loop through an object, but if you are only justing vanilla Js then to loop through an object you need to us the for in loop.