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.
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#
const cities = ["Hyderabad", "Pune", "Chennai"];
for (const city of cities) {
console.log(city);
}Hyderabad
Pune
ChennaiNo 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:
let vowels = 0;
for (const ch of "JavaScript") {
if ("aeiou".includes(ch.toLowerCase())) vowels++;
}
console.log(vowels);3Getting the index as well#
entries() gives [index, value] pairs, which you can unpack with destructuring:
const steps = ["Boil water", "Add tea", "Add milk"];
for (const [i, step] of steps.entries()) {
console.log(`${i + 1}. ${step}`);
}1. Boil water
2. Add tea
3. Add milkfor...of works on any iterable: arrays, strings, Maps, Sets, and more (Iterators and Generators). It does not work on plain objects:
const user = { name: "Asha" };
try {
for (const x of user) {}
} catch (error) {
console.log(error.message);
}user is not iterablefor...in: object keys#
for...in loops over the property names of an object:
const scores = { maths: 92, science: 85, english: 78 };
for (const subject in scores) {
console.log(`${subject}: ${scores[subject]}`);
}maths: 92
science: 85
english: 78Use 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:
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));maths 92
science 85
english 78
[ 'maths', 'science', 'english' ]
255This 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:
const list = ["a", "b"];
for (const i in list) {
console.log(i, typeof i);
}0 string
1 stringFor arrays, use for...of, a for loop, or array methods.
Summary#
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
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(", "));pens: 40 left
erasers: 12 left
Sold out: notebooksKey takeaway#
Finished this lesson?