All Articles

How to use for...in and for...of in JavaScript

for...in and for...of help us iterate over properties(keys) and values of an object. We use them with strings, arrays, and object literals in most cases.

Test cases:

const fruitsArray = ['🍎', 'πŸ₯­', 'πŸ₯', 'πŸ₯‘', '🍌']
const appleString = 'apple'
const saladObject = {
  apple: '🍎',
  banana: '🍌',
  avocado: 'πŸ₯­'
}

for…in

Iterates over properties (keys) of an object.

// Logs 0, 1, 2, 3, 4
for (let fruit in fruitsArray) {
  console.log(fruit)
}

// Logs 0, 1, 2, 3, 4
for (let char in appleString) {
  console.log(char)
}

// Logs apple, banana, avocado
for (let ing in saladObject) {
  console.log(ing)
}

for..of

Iterates over values in the iteratable object.

// Logs a, p, p, l, e
for (let char of appleString) {
  console.log(char)
}

//Logs 🍎, πŸ₯­, πŸ₯, πŸ₯‘, 🍌
for (let fruit of fruitsArray) {
  console.log(fruit)
}

Also, it works fine with maps, sets, a DOM collection, the arguments object passed in JavaScript functions.