JavaScript Introducing ES2015 Objects and New Collection Types For...Of

Daniel Vu
Daniel Vu
6,799 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
170,377 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,129 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.

Nafis Fuad
Nafis Fuad
35,498 Points

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

Jonathan Kuhl
Jonathan Kuhl
26,129 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.

izzy goldman
izzy goldman
12,542 Points

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`