For loop: are you of or in?

July 13, 2024 - Reading time: 2 minutes

Aren't you? I'm always struggling to know where to use the for... of loop or the for... in loop.

Let's have here a quick note for reference:

for... of loop

Iterates over an iterable object (object, array, string, map...) and temporarily assign to a variable

const chars = ["Jack", "Daniel", "Sam", "Teal'c"];

for (const char of chars) {
console.log(char); }

Note that you can use const if the variable is not reassigned within the loop.

for... in loop

Loops for properties of an array or object. Not to be used if the order is important.

// array
const chars = ["Jack", "Daniel", "Sam", "Teal'c"];

for (let char in chars) {
console.log(char); // prints the indexes as strings
console.log(chars[char]); // prints the value }

// object
const soldier = {firstname: "Jack", lastname: "O'Neill", team: "SG1"};

for (let key in soldier) {
console.log(key); // prints the key (firstname, lastname, team)
console.log(soldier[key]); // prints the value (Jack, O'Neill, SG1) }

forEach() method

The same result can be obtained using forEach() method (on an array).

const chars = ["Jack", "Daniel", "Sam", "Teal'c"];

chars.forEach(function (char, index) {
console.log(index); // prints the indexes as numbers
console.log(char); // prints the names
});