The difference between for .. in and for .. of in javascript

Jun 9, 2024·
Gert de Pagter
Gert de Pagter
· 1 min read

If you want to do a for loop over an array in javascript you generally want to do a for (const value of array) {. Because this will loop over all the items of an array. A for (const key in array) { will instead loop over the keys of an array (or of an object).

const letters = ['a', 'b', 'c'];

for (const value of letters) {
  console.log(value); // 'a', 'b', 'c'
}

for (const key in letters) {
  console.log(key); // 0, 1, 2
}

My personal mnemonic to remember this is that you can do an in check to see if a key exists in javascript. So you can do a for in loop to loop over the keys. e.g.:


const person = {
  age: 30,
  job: 'Software Engineer',
  name: 'Gert',
};

console.log('age' in person); // true
console.log('intellect' in person); // false

So in conclusion, use for .. of to loop over values, and for .. in to loop over keys.

If you want to get notified of the next blog post, join the newsletter.