JavaScript `for..in` `for..of` and other loops

  • for..in - iterates over keys of all objects - loops over enumerable property names of an object.
  • for..of - iterates over values of iterable objects (Array, TypedArray, String, Map, Set) - does use an object-specific iterator and loops over the values generated by that.
  • forEach - specific method for arrays
  • map - specific method for arrays

Example with an object

1
2
3
4
5
6
7
const obj = { 1: 1, 2: true, 3: "str" }
for (let i in obj) console.log(i) // console logs 1, 2, 3
for (let i of obj) console.log(i) // console error `Uncaught TypeError: obj is not iterable`

obj[Symbol.iterator] = function*() { for (let i in obj) yield obj[i] }

for (let i of obj) console.log(i) // console logs 1, true, "str"

Example with a set

1
2
3
4
5
6
7
8
9
10
let pets = new Set(["Cat", "Dog", "Hamster"])
pets["species"] = "mammals"

for (let pet in pets) {
console.log(pet) // "species"
}

for (let pet of pets) {
console.log(pet) // "Cat", "Dog", "Hamster"
}

Example with for..in and enumerable method

Because for..in loops over all enumerable properties, this means if you add any additional properties to the array’s prototype, then those properties will also appear in the loop.

1
2
3
4
5
6
7
8
9
10
11
Array.prototype.decimalfy = function() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].toFixed(2)
}
}

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for (const index in digits) {
console.log(digits[index]) // it also print decimalfy function
}

Above for for..of

1
2
3
4
5
6
7
8
9
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for (const digit of digits) {
if (digit % 2 === 0) {
continue
}
console.log(digit)
}
// prints 1, 3, 5, 7, 9