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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects Using `for in` to Loop Through an Object's Properties

Jake Ford
Jake Ford
9,230 Points

So "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

for in loops are used for looping through objects in JS. for each is different in that you can loop though non-objects.

Thomas Nilsen
Thomas Nilsen
14,957 Points

There 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
Jake Ford
9,230 Points

So use forEach to loop through arrays and use "for in" to loop through objects?

Thomas Nilsen
Thomas Nilsen
14,957 Points

Basically - yeah.

But you could also use 'for in' to loop over arrays and strings as well

for 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.

Blake Schwartz
Blake Schwartz
4,282 Points

I'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.

If 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.