What is the difference between for...of and for...in in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
for...of loops over the values of an array or other iterable, one value per round. for...in loops over the property names of an object, as strings, which makes it the wrong choice for arrays.This answer is one piece of Chapter 2: Decisions and Loops.
The two loops look almost identical, and swapping one for the other gives no error, only wrong data. That is why it is worth learning which is which.
for...of is the loop for lists. In the example, for (const sku of skus) hands you MRD-1001, MRD-1002 and MRD-1003, the values you actually want to check or click.
for...in walks the keys of an object. Run it over the same array and you get 0, 1 and 2, and typeof shows they are strings, not numbers. A test that then does getByTestId(key) or adds key + 1 is working with the wrong thing. MDN recommends for...of, a numeric for loop or forEach() for arrays, because they give the index as a number and skip extra properties.
Where for...in earns its place is an object such as one order: for (const key in order) lists id, city and qty, and order[key] reads each value. That is handy for logging a test-data row or checking every field of an API response. A simple rule: of for values in a list, in for keys in an object.
const skus = ['MRD-1001', 'MRD-1002', 'MRD-1003'];
for (const sku of skus) {
console.log('of:', sku);
}
for (const key in skus) {
console.log('in:', key, typeof key);
}
const order = { id: 'ORD-4100', city: 'Kochi', qty: 3 };
for (const key in order) {
console.log(`${key} = ${order[key]}`);
}of: MRD-1001 of: MRD-1002 of: MRD-1003 in: 0 string in: 1 string in: 2 string id = ORD-4100 city = Kochi qty = 3
for (const x in ['MRD-1001', 'MRD-1002']) console.log(x) print?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free