for of .. vs for in .. vs for ..

Published on December 28, 2020 - Tagged: #javascript #tips

Follow me on twitter for more posts like this

Sometimes I forget what the best use of the various for loops are in JavaScript or typescript. This is a short one to remind myself when to use each one. Coming from C# where foreach .. in is the statement for iterables it’s important to remember the equivalent in JavaScript is for .. of.

for of ..

This is the statement you need to use for iterables. Iterables in JavaScript are things like Arrays, Sets, Maps, Strings. This is the equivalent of a foreach in C#.

const iterable = [1, 2, 3]

for (const value of iterable) {
// 1
// 2
// 3

This is probably what you want to use for iterating over an array or an array like collection.

for in ..

For in iterates over object properties. You can iterate over arrays with for in but you might be surprised by the output, you will also see any object properties and inherited properties. Another issue is that you cannot be guaranteed of the order the for in will iterate over the items.

var obj = { a: 1, b: 2, c: 3 }

for (const prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`)

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

normal for

The normal for loop. Not much to say here. It is what it is.

Remember to not use .length of a collection in the expression or it will be calculated on each loop. Do it outside the statement.

const iterable = [1, 2, 3]
const iterableLength = iterable.length

for (let i = 0; i < iterable.length; i++) {

// 1
// 2
// 3
Darragh ORiordan

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia building supporting happy teams that create high quality software for the web.

I also make tools for busy developers! Do you have a new M1 Mac to setup? Have you ever spent a week getting your dev environment just right?

My DevShell tooling will save you 30+ hours configuring your dev environment with all the best modern tools. Get it here