for...of vs for...in in JavaScript
Beginner · 4 min read
JavaScript has two loops that look almost the same: for (const x of list) and for (const x in list). One letter apart, and they hand you completely different things. Mixing them up is one of the most common beginner bugs, and it often doesn't throw an error. It just gives strange results.
In this tutorial you will walk the same array with both loops, see exactly what each one gives you, and find out what happens when an array has an extra property attached. Then you will meet entries(), which gives you the position and the value together. You need to know what an array and an object are.
Values and keys
Every item in an array has a value (what is stored) and a key (where it is stored, its position). In ['a', 'b', 'c'], the value 'b' sits at key 1.
for...ofgives you the values:'a','b','c'.for...ingives you the keys:'0','1','2'.
A way to remember it: "in" is for what's in the labels, "of" is for the things themselves. Or simply: for arrays, use of.
Keys are text
Here is the surprise. Object keys in JavaScript are always strings (text), and an array is a kind of object. So for...in gives you '0', the text, not the number 0.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
76 for...of and for...in are not the same loop
easyWalk the same array with for...of and with for...in, and show what each one hands you. Then add a stray property to the array and walk it again.
Stuck? Three hints, smallest first
- 1.
for...ofgives values;for...ingives keys. - 2. Check the type of what
for...ingives you before you do arithmetic on it. - 3.
array.entries()gives index and value together, with the index as a real number.
Step 1: for...of gives values
The example array holds three bus fares in kobo (100 kobo make one naira):
const fares = [200_00, 350_00, 150_00];
const values = [];
for (const fare of fares) values.push(fare);
console.log(values); // [ 20000, 35000, 15000 ]
The underscores in 200_00 only make the number easier to read. Each turn of the loop, fare is the next value in the array. This is the loop you want almost every time you walk an array.
Step 2: for...in gives keys, as text
const fares = [200_00, 350_00, 150_00];
const keys = [];
for (const i in fares) keys.push(i);
console.log(keys); // [ '0', '1', '2' ]
console.log(typeof keys[0]); // string
typeof tells you what type a value is. The keys are strings, which is easy to miss because they look like numbers.
Step 3: the string trap
Try to use those keys as numbers:
const fares = [200_00, 350_00, 150_00];
let joined = '';
for (const i in fares) joined += i;
console.log(joined); // 012
for (const i in fares) {
console.log(i + 1); // 01, then 11, then 21
}
The + operator joins text instead of adding when one side is a string. So '0' + 1 is '01', not 1. If you were working out "the next stop", you would get nonsense, with no error to warn you.
Step 4: a stray property tags along
Arrays are objects, so you can attach a named property to one. for...in walks every key, so it finds that property too:
const tagged = [1, 2, 3];
tagged.note = 'from the depot';
const taggedKeys = [];
for (const key in tagged) taggedKeys.push(key);
const taggedValues = [];
for (const value of tagged) taggedValues.push(value);
console.log(taggedKeys); // [ '0', '1', '2', 'note' ]
console.log(taggedValues); // [ 1, 2, 3 ]
console.log(tagged.length); // 3
for...in treats 'note' like a fourth item. for...of only walks the array's real items, and length agrees with it. Libraries and older code sometimes add properties like this, which is one more reason to keep for...in away from arrays.
Step 5: when you need the position too
Sometimes you need both the position and the value, for example to print "stop 1: 20000". Use entries() with for...of:
const fares = [200_00, 350_00, 150_00];
const pairs = [];
for (const [i, fare] of fares.entries()) pairs.push(i + ':' + fare);
console.log(pairs); // [ '0:20000', '1:35000', '2:15000' ]
entries() gives a pair [position, value] for each item, and [i, fare] unpacks the pair into two names. Here i is a real number, so i + 1 would be 1, 2 and 3, as you'd expect.
So what is for...in for?
Plain objects, where the keys are names:
const bus = { route: 'CMS-Ikorodu', seats: 40 };
for (const key in bus) console.log(key); // route, then seats
If you want keys from an array, Object.keys(fares) gives the same strings '0', '1', '2', and on an array with a stray property it would include that too, so the same care applies.
The full solution
The answer panel walks the fares with both loops, shows the string keys and the '012' they join into, walks an array with a stray property, and uses entries() for number positions. Press Run to see the output.
const fares = [200_00, 350_00, 150_00]; // kobo, three stops
// for...of hands you each value.
const values = [];
for (const fare of fares) values.push(fare);
// for...in hands you each KEY, and an array's keys are strings.
const keys = [];
for (const i in fares) keys.push(i);
// Which is why this looks like addition and is not.
let joined = '';
for (const i in fares) joined += i;
// A stray property rides along in for...in, but not in for...of.
const tagged = [1, 2, 3];
tagged.note = 'from the depot';
const taggedKeys = [];
for (const key in tagged) taggedKeys.push(key);
const taggedValues = [];
for (const value of tagged) taggedValues.push(value);
// entries() is the one that gives both, with a number index.
const pairs = [];
for (const [i, fare] of fares.entries()) pairs.push(i + ':' + fare);
console.log('for...in keys:', keys, 'first is a', typeof keys[0]);
console.log('with a stray property:', taggedKeys);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('for...of gives the values', values, [20000, 35000, 15000]);
test('for...in gives the keys', keys, ['0', '1', '2']);
test('and those keys are strings, not numbers', typeof keys[0], 'string');
test('so adding them concatenates instead', joined, '012');
test('a stray property shows up in for...in', taggedKeys, ['0', '1', '2', 'note']);
test('but for...of never sees it', taggedValues, [1, 2, 3]);
test('nor does length', tagged.length, 3);
test('entries() gives a real number index', pairs, ['0:20000', '1:35000', '2:15000']);
for...in walks enumerable string keys, including inherited ones and anything else bolted onto the object. On an array that means the indices arrive as '0', '1', '2' — so i + 1 gives '01', not 1, and a property someone attached to the array turns up as a fourth "index". Neither is a bug; it is what the loop is for, and an array is not what it is for.
Use for...of for values, entries() when you need the index too, and keep for...in for plain objects. Object.keys(fares) gives the same three strings, without the stray property, if you really want keys from an array.
Common mistakes
- Using
for...inon an array to get values. You get the positions, as text. Usefor...of. - Doing math with
for...inkeys.'1' + 1is'11'. Useentries()for a number position. - Using
for...ofon a plain object. A plain object can't be walked withfor...ofand throws aTypeError. Usefor...inorObject.entries(obj).
Try it yourself
- Use
for...ofto add up all the fares into a total. - Use
entries()to print each fare as "stop 1: 20000", starting the count at 1. - Walk the object
{ route: 'CMS-Ikorodu', seats: 40 }withfor...inand print each key with its value.