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

Daniel Vu
Daniel Vu
6,808 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
218,596 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) {

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`