The For…in Loop in JavaScript

Omar Barguti
2 min readApr 20, 2021

Most developers coming from a C# or a Java background find the ‘for-in’ loop feature in JavaScript confusing. Perhaps the reason is that the ‘for-in’ loop is often confused by the ‘foreach’ loop in C# or Java. The truth is, the ‘for-in’ loop is very similar to the ‘foreach’ loop in C#. However, there are some fundamental differences.

The ‘for-in’ loop in JavaScript iterates over the indexes of an array.

Example below:
// JavaScript
var numArray = [1, 4, 3];
for(var n in numArray){
console.log(n);
}

Running the code in the JavaScript example above prints the values 0, 1, 2. These are clearly not the values populated in the number array, but the ‘index’ of the number within the array. In order to retrieve the values stored in the array above, we would have to reference the array at the current index:

for(var n in numArray){
console.log(numArray[n]);
}

Let’s consider the same example in C#:

// C#
var numArray = new[] {1, 4, 3 };
foreach (var n in numArray)
{
Console.WriteLine(n);
}

Running the code in the C# example above prints the values 1, 4, 3. These are the actual values stored in the array and not the indexes. Notice, referencing the array is not necessary in C#. The value in a specific iteration is immediately returned.

Perhaps the reason why the ‘for-in’ loop operates the way it does has to do with how arrays are structured in JavaScript. The array object is not truly an array. Its more like a “string, object” dictionary. The reason why array are stored like key-value pairs is to save space when allocating memory.

Example:

// JavaScript
var numArray = [1, 4, 3];
numArray["100"] = 100;
numArray["M"] = 1000000;
for(var n in numArray){
console.log(n);
}

The code above prints the values of the array indexes: 0, 1, 2, 100, ‘M’.

Iterating over Object Properties

Since all objects in JavaScript are stored as key-value pair dictionaries, it is possible to iterate over the various properties of an object:

// JavaScript
var employee = {
name: 'steve',
id: 123,
age: 30,
hobbies: 'chess'
};
for(var i in employee) {
console.log(i); // prints the key
console.log(employee[i]); // print the value
}

The code above loops over all the properties of the Employee object. The value of the variable ‘i’ is the ‘key’ of the property and the value can be looked up from the employee object directly.

Other Loops in JavaScript: For, While and Do-While
JavaScript support three other types of loops. The standard ‘For’ loop, which is used when the number of iterations is pre-determined. The ‘While’ loop, which is a pre-tested condition loop. Finally, the ‘Do-While’ loop, which is a post-test condition loop.

--

--

Omar Barguti

An enthusiastic architect and full-stack developer with many years working with enterprise software and cloud services in multiple domains.