Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
seal-mask
.a{fill-rule:evenodd;}techdegree
Bella Bradbury
Web Development Techdegree Student 14,361 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:

// ARRAY
var arr = [8, 54, 1];

for (var i in arr) {
  console.log(i);
}

//OBJECT
var example = { name: "Bella"}

for(var i in example) {
  console.log(i)
}

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) {
  console.log(i); 
}

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!