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 and the DOM Getting a Handle on the DOM Select Elements by Class Name

difference between " for in " and " for of "

Based on my understanding, For in is used strictly for Objects only

While for of is used for strings and arrays but they work pretty much the same but the difference is only if it's objects {} or arrays [].

Did I get this right?

1 Answer

Bella Bradbury
.a{fill-rule:evenodd;}techdegree seal-36
Bella Bradbury
Front End Web Development Techdegree Graduate 32,788 Points

Hi Peter!

The biggest difference between for..in and for..of is all to do with how your code is able to/needs to interact with data!

The for..in loop deals with the organizational part of the data rather than the specific values. This could mean returning the keys for an array or the properties of an object. If we were to run the following code both with an array and an object:

var arr = [8, 54, 1];

for (var i in arr) {

var example = { name: "Bella"}

for(var i in example) {

the console would log 0, 1, 2 from the array and name from the object because it's referring to the keys/properties IN the data structure.

The for..of loop deals with the actual values of iterable data (which is why it can't be used with objects). If we ran the following code using only the array example from above:

var arr = [8, 54, 1];

for (var i of arr) {

The console would log 8, 54, 1 because it is referring to the value OF the data itself.

To sum up:

  1. for..in
    • works with objects & arrays (but is more suited to objects)
    • deals with data structure over data value
  2. for..of
    • works with arrays only
    • deals with data value over data structure

Hope this helps!

THANK YOU for this!