The for...of and for...in Loops
for...of is a loop that gives you each value of an iterable collection in turn: each item of an array, each character of a string, each entry of a Map. for...in is a loop that gives you each key (property name) of an object. The names are one letter apart and easy to mix up, and using for...in on an array is a classic bug. Remember: of for values, in for keys.
In One Minute
for (const item of list)gives each value: arrays, strings, Maps, Sets, and anything iterable.for (const key in object)gives each property name of an object, as a string.- Don't use
for...inon arrays: keys come as strings, inherited properties can appear, and it is slower. - Plain objects aren't iterable; loop over
Object.entries(obj)withfor...ofinstead. - Both loops support
breakandcontinue.
The for...of Loop
Syntax
for (const value of iterable) {
// value is the next item
}Use const unless you reassign the variable inside the body. Each round gets a fresh variable.
Example
const students = ["Navika", "Srihitha", "Advitha"];
for (const name of students) {
console.log(`Hello, ${name}`);
}
for (const letter of "Fee") {
console.log(letter);
}Hello, Navika
Hello, Srihitha
Hello, Advitha
F
e
eWhat Is Iterable
An iterable is any value that can hand out its items one at a time. Built-in iterables:
| Iterable | for...of gives |
|---|---|
| Array | Each item |
| String | Each character (full Unicode characters, including emoji) |
Map | Each [key, value] pair |
Set | Each value |
arguments, NodeList (from the DOM) | Each item |
| Generators and iterators | Each yielded value |
Plain objects ({ name: "Navika" }) are not iterable: for (const x of {}) throws TypeError: {} is not iterable. The iterators chapter shows how to make your own objects iterable.
Getting the Index Too
for...of gives values only. When you also need the position, loop over list.entries(), which gives [index, value] pairs, and destructure each pair into two variables:
const fees = [120, 85, 45];
for (const [index, fee] of fees.entries()) {
console.log(`${index + 1}. $${fee}`);
}1. $120
2. $85
3. $45The for...in Loop
Syntax
for (const key in object) {
// key is a property name (a string); object[key] is its value
}Example
const student = { name: "Advitha", grade: 9, city: "San Francisco" };
for (const key in student) {
console.log(`${key}: ${student[key]}`);
}name: Advitha
grade: 9
city: San FranciscoExplanation: key is each property name as a string. Use bracket notation student[key] to read the value, because student.key would look for a property literally named "key".
for...in visits enumerable properties (the normal ones you create), including properties inherited from the object's prototype. For plain objects that is usually nothing extra, but for objects built from classes or older libraries, inherited keys can sneak in. That is one reason modern code prefers Object.keys and Object.entries, covered next.
Why for...in Is Wrong for Arrays
Arrays are objects whose keys are "0", "1", "2"... so for...in "works" on them, but badly:
const fees = [120, 85];
fees.note = "fall term"; // arrays can have extra properties
for (const i in fees) {
console.log(i, typeof i);
}
let total = 0;
for (const i in fees) {
total += i; // i is a string!
}
console.log(total);0 string
1 string
note string
001noteExplanation: three problems at once. The keys are strings, so total += i joins text instead of adding numbers. The extra note property is visited as if it were an item. And for...in visits keys, not values; the fees themselves were never used. for...of has none of these problems.
Looping Through Objects the Modern Way
Object.keys, Object.values and Object.entries turn an object's own properties into arrays, which for...of can loop over:
const feesByGrade = { 9: 400, 10: 415, 11: 430 };
for (const [grade, fee] of Object.entries(feesByGrade)) {
console.log(`Grade ${grade}: $${fee}`);
}
let total = 0;
for (const fee of Object.values(feesByGrade)) {
total += fee;
}
console.log("Total:", total);Grade 9: $400
Grade 10: $415
Grade 11: $430
Total: 1245These three methods skip inherited properties, and they return arrays, so you can also use array methods on them. The objects chapter covers them in detail.
In Practice
The Fee Tracker groups payments by student. A for...of loop walks the payments array; a second loop walks the resulting object with Object.entries:
const payments = [
{ name: "Navika", amount: 120 },
{ name: "Advitha", amount: 95 },
{ name: "Navika", amount: 60 },
{ name: "Srihitha", amount: 85 },
];
const totals = {};
for (const { name, amount } of payments) {
totals[name] = (totals[name] ?? 0) + amount;
}
for (const [name, total] of Object.entries(totals)) {
console.log(`${name}: $${total}`);
}Navika: $180
Advitha: $95
Srihitha: $85The loop variable { name, amount } destructures each payment object into two variables, just as [grade, fee] destructured each entry pair above.
Common Mistakes
for...in on arrays. String keys, extra properties, no values. Use for...of.
for...of on a plain object. TypeError: obj is not iterable. Use Object.entries(obj).
Reading object.key inside for...in. That reads a property named "key". Use object[key].
Changing an array while looping over it with for...of. Removing items shifts the rest, so items get skipped. Build a new array (filter) instead.
Interview Corner
What is the difference between for...of and for...in?
for...of iterates the values of an iterable (arrays, strings, Maps, Sets, generators) using the iteration protocol. for...in iterates the enumerable string keys of any object, including inherited ones, in property order. Use for...of for arrays, and Object.keys, values or entries for objects.
Why shouldn't you use for...in on an array?
It yields string indexes, includes any extra enumerable properties (including some added to Array.prototype by old libraries), and was historically not guaranteed to follow index order. for...of, a classic for, or array methods are correct and clearer.
Practice
Challenge: Given an object of fees by item, use for...of with Object.entries to print each item on its own line and then the total. Skip any item whose fee is 0.
Show solution
const fees = { tuition: 400, books: 85, lab: 0, uniform: 45 };
let total = 0;
for (const [item, fee] of Object.entries(fees)) {
if (fee === 0) continue;
console.log(`${item}: $${fee}`);
total += fee;
}
console.log(`Total: $${total}`);tuition: $400
books: $85
uniform: $45
Total: $530Key Takeaways
| Loop over | Write |
|---|---|
| Array values | for (const v of arr) |
| Array index and value | for (const [i, v] of arr.entries()) |
| String characters | for (const ch of str) |
| Object keys and values | for (const [k, v] of Object.entries(obj)) |
| Map entries | for (const [k, v] of map) |
Was this tutorial helpful?