Skip to content
Laviyx Learn

Try

JavaScript course menu

JavaScript for...of and for...in Loops: Arrays, Strings and Objects

Learn the difference between for...of and for...in in JavaScript: looping over array values and string characters with for...of, getting indexes with entries(), looping over object keys with for...in or Object.entries, and why not to use for...in on arrays.

Beginner6 min readUpdated
On this page

Two loops make walking through collections easier than a counting for loop: for...of for the values of an array, string, Map or Set, and for...in for the keys of an object.

for...of: values#

JavaScript
const cities = ["Hyderabad", "Pune", "Chennai"];

for (const city of cities) {
  console.log(city);
}
Output
Hyderabad
Pune
Chennai

No index, no length, no off-by-one mistakes. Use const for the loop variable unless you reassign it inside the loop.

It works on strings too, one character at a time:

JavaScript
let vowels = 0;
for (const ch of "JavaScript") {
  if ("aeiou".includes(ch.toLowerCase())) vowels++;
}
console.log(vowels);
Output
3

Getting the index as well#

entries() gives [index, value] pairs, which you can unpack with destructuring:

JavaScript
const steps = ["Boil water", "Add tea", "Add milk"];
for (const [i, step] of steps.entries()) {
  console.log(`${i + 1}. ${step}`);
}
Output
1. Boil water
2. Add tea
3. Add milk

for...of works on any iterable: arrays, strings, Maps, Sets, and more (Iterators and Generators). It does not work on plain objects:

JavaScript
const user = { name: "Asha" };
try {
  for (const x of user) {}
} catch (error) {
  console.log(error.message);
}
Output
user is not iterable

for...in: object keys#

for...in loops over the property names of an object:

JavaScript
const scores = { maths: 92, science: 85, english: 78 };

for (const subject in scores) {
  console.log(`${subject}: ${scores[subject]}`);
}
Output
maths: 92
science: 85
english: 78

Use square brackets (scores[subject]) to read a property whose name is in a variable.

Object.entries: often better#

Object.keys, Object.values and Object.entries turn an object into an array, which you can loop over with for...of:

JavaScript
const scores = { maths: 92, science: 85, english: 78 };

for (const [subject, mark] of Object.entries(scores)) {
  console.log(`${subject.padEnd(8)} ${mark}`);
}
console.log(Object.keys(scores));
console.log(Object.values(scores).reduce((a, b) => a + b, 0));
Output
maths    92
science  85
english  78
[ 'maths', 'science', 'english' ]
255

This style only includes the object's own properties and works with array methods.

Do not use for...in on arrays#

for...in gives array indexes as strings, can include extra properties, and is meant for objects:

JavaScript
const list = ["a", "b"];
for (const i in list) {
  console.log(i, typeof i);
}
Output
0 string
1 string

For arrays, use for...of, a for loop, or array methods.

Summary#

LoopGives youUse on
for...ofValuesArrays, strings, Maps, Sets
for...of with entries()Index and valueArrays
for...inProperty namesPlain objects
for...of with Object.entries(obj)Key and valuePlain objects

Practice#

Practice exercise

Given const stock = { pens: 40, notebooks: 0, erasers: 12 }, print each item that is in stock, then print the names of items that are sold out.

Show solution
JavaScript
const stock = { pens: 40, notebooks: 0, erasers: 12 };

for (const [item, count] of Object.entries(stock)) {
  if (count > 0) console.log(`${item}: ${count} left`);
}

const soldOut = [];
for (const item in stock) {
  if (stock[item] === 0) soldOut.push(item);
}
console.log("Sold out:", soldOut.join(", "));
Output
pens: 40 left
erasers: 12 left
Sold out: notebooks

Key takeaway#

Finished this lesson?