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 Introducing ES2015 Objects and New Collection Types For...Of

Daniel Vu
Daniel Vu
6,814 Points

Aside for short circuiting a loop, could you tell me any additional use cases of using the "For...Of" loop?

I was curious to see where else I could use the "For...Of" loop.

3 Answers

Steven Parker
Steven Parker
231,275 Points

:point_right: You can use for...of on iterables other than arrays.

For instance, unlike .forEach you can use it to iterate over the characters in a string.

In the video, Guil mentioned that the for of loop can be used on any data set except Objects. This means they can be used on Strings, Arrays, Maps , Sets and any other Iterables. But they can not be used on Objects.

Jonathan Kuhl
Jonathan Kuhl
26,133 Points

You most definitely can use for . . . of on Arrays. I used it in my Circles game in Codepen. https://codepen.io/jkuhl/pen/NgYBro

     for(let i of baddyArray) {
        i.collisionDetection();
        i.updatePos();
      }

Here's part of a larger code where it's iterating through objects in an array and calling their collisionDetection and updatePos methods, which allow them to collide with the player and move around on the screen.

They can be used to access objects in an array. They just can't be used to access values inside objects. I tried on JSFiddle and got a syntax error in the console.

Hey, Jonathan Kuhl. I played your game for a while ... Great job there.

Jonathan Kuhl
Jonathan Kuhl
26,133 Points

Thanks! It took a lot of work. In the end, the teachers are right; running through the MDN to find answers is one of the best ways to find out how you can accomplish your goal.

A classic example of using a For of in Maps:

`let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);

for (let entry of iterable) { console.log(entry); } // ['a', 1] // ['b', 2] // ['c', 3]

for (let [key, value] of iterable) { console.log(value); } // 1 // 2 // 3`