Using for/in and for/of loops

·

2 min read

'For in' loops over the keys in an object.

'For of' loops over the items in an array.

For example when interrogating array teamIndex to get all the playerNames use for/of

let teamIndex = [
            {
                type: "player",
                playerName: "Tim",
                playerTown: "New York"
            }, 
            {
                type: "player",
                playerName: "Sally",
                playerTown: "Amsterdam"
            },
           {
               type: "player",
               playerName: "John",
               playerTown: "Riyadh"
           },
]


        for(let player of teamIndex) {
               player.playerName
                }
     //gives Tim, Sally, John

So in the above example we are 'for of'-ing over an array eg 'for(let player of teamIndex)' to get each item in the array. This item happens to be an object, which within the loop is referred to as 'player '. Then using dot notation we can extract properties from this object eg 'player.playerName'


Now let's use the for/in loop

Our object has three (enumerable) properties, the for in loop can loop over these properties, and extract the key, then use this to access the value, eg ${object[property]}.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

What happens if we try to use a for of loop on object

for (const element of object) {
  console.log(element);
}
Uncaught TypeError: object is not iterable

We get an error because object is not iterable, only arrays are iterable. Object properties are enumerable though and that is why we can loop over them with a for/in loop.