skip to content
Alvin Lucillo

for..in and for..on with arrays and objects

/ 1 min read

💻 Tech

for..in is used for iterating over enumerable properties like objects, while for..of is used for iterating over iterable objects like arrays. Both can be used in a array but behave differently. With an object, for..of will throw an error because objects are not iterable.

const nourritureChinois: string[] = ["bing cha", "mifan", "hanbaobao", "doufu"];

console.log("using array in for..in")
for (const p in nourritureChinois) {
  console.log(p)
}
console.log("using array in for..of")
for (const p of nourritureChinois) {
  console.log(p)
}

interface Palavra {
  deIdioma: string;
  deValor: string;
  paraIdioma: string;
  paraValor: string;
}

const palavra: Palavra = {deIdioma: "pt", deValor: "obrigado", paraIdioma: "en", paraValor: "thanks"};
console.log("using object in for..in")
for (const p in palavra) {
  console.log(p)
}
console.log("using object in for..of")
for (const p of palavra) {
  console.log(p)
}
using array in for..in
0
1
2
3

using array in for..of
bing cha
mifan
hanbaobao
doufu

using object in for..in
deIdioma
deValor
paraIdioma
paraValor

using object in for..of
TypeError: palavra is not iterable
    at <anonymous>:22:17
    at mn (<anonymous>:16:5455)