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 trialDaniel Vu
6,814 PointsAside 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
231,275 Points
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.
nfs
35,526 PointsHey, Jonathan Kuhl. I played your game for a while ... Great job there.
Jonathan Kuhl
26,133 PointsThanks! 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.
izzy goldman
12,542 PointsA 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`
kobbyberks
10,722 Pointskobbyberks
10,722 PointsIn 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
26,133 PointsJonathan Kuhl
26,133 PointsYou most definitely can use for . . . of on Arrays. I used it in my Circles game in Codepen. https://codepen.io/jkuhl/pen/NgYBro
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.