Difference between for, while, forEach, for-in and for-of

JavaScript/TypeScript

A lot of languages support several ways for loop logic. Typescript supports following ways for example.

  • while
  • for
  • for in
  • for of
  • forEach

Have you ever thought which way I should use in this case? Yes, I have! We can implement the same behavior in the different ways but I think it’s better to distinguish them depending on a case.

Sponsored links

while

The key point to use while is whether the condition can be controlled by the scope or not. I think beginners learn while and for loop at first. Condition(s) can be set in it. I use while when I want to loop without index and the target loop variable is not array. In C language, I often saw while loop when reading contents from a file especially when reading one line at a time.
Let’s consider the case when we want to break the while loop if the file reaches at the end of the file. It depends on the file when to break the while loop because he scope doesn’t know when the file stream reaches at the end of the file. It’s out of control.

Sponsored links

for

The key point to use for is whether index value is used in the scope or not. If I want to store line numbers where important information is written I use for instead while because we can specify the index variable in the same line.

const dataArray = ["foo", "foo-foo", "hoge"];
for(let index = 0; index < dataArray.length; index++){
    // do something
    const data = dataArray[index]; // We can get the data with index
}

Recently I used for loop to find special values until the count reached to certain value. It was something like this. We can of course use while loop but in this case we need to define index variable outside of the scope. It is not so good because scope should be minimized.

const numberOfValue = 3;
const result = []
for(let index = 1; result <= numberOfValue; index++){
    if(data[index].hasSpecialValue()) {
        result.push({
            data,
            index,
        });
    }
}

for in

If we don’t need to use the values of the array we should use for in. If we use for loop described above even though we don’t need to use the value the code becomes longer. This for in loop is less often used than others.

const dataArray = ["foo", "foo-foo", "hoge"];
for (const index in dataArray) {
    // do something
    // index is 0, 1, 2, ...
}

for of

If we need the value without index and want to use Promise function in it we should use for of. This is because forEach doesn’t support async/await callback. If you don’t know why you should check this post. You can access to the dataArray without index value. The code is shorter than for loop.

const dataArray = ["foo", "foo-foo", "hoge"];
for (const data of dataArray) {
    // do something
    // data is "foo", "foo-foo", "hoge"
}

forEach

In my opinion, basically we should use forEach for loop because it explicitly indicates that the process is done under the variable. In addition to that, we can define a variable name which perfectly matches to the meaning of the value. If index value is necessary we can define second callback argument which can be used as index. If we need Promise function in it we need to use for of which basically is the same role.

const dataArray = ["foo", "foo-foo", "hoge"];
dataArray.forEach((value, index) => {
    console.log(`index: ${index}, value: ${value}`);
});

Comparison

I wrote very simple program. Which one do you like? Since this example is too simple the difference is small but we should consider how to make our code shorter and more readable.

{
    console.log("--- while ---");
    const primeNumbers = [1, 2, 3, 5, 7];
    let count = 0;
    while (count < primeNumbers.length) {
        console.log(primeNumbers[count]);
        count++;
    }
}

{
    console.log("--- for ---");
    const primeNumbers = [1, 2, 3, 5, 7];
    for (let i = 0; i < primeNumbers.length; i++) {
        console.log(primeNumbers[i]);
    }
}

{
    console.log("--- for in ---");
    const primeNumbers = [1, 2, 3, 5, 7];
    for (const index in primeNumbers) {
        console.log(primeNumbers[index]);
    }
}

{
    console.log("--- for of ---");
    const primeNumbers = [1, 2, 3, 5, 7];
    for (const primeNumber of primeNumbers) {
        console.log(primeNumber);
    }
}

{
    console.log("--- forEach ---");
    [1, 2, 3, 5, 7]
        .forEach((primeNumber) => {
            console.log(primeNumber);
        });
}

Conclusion

The simple use case is following. Even though we can implement the same behavior in the different ways but each way has its own meaning. It’s better to have such a habit to think those differences even if it is small matter.

  • while – when the condition is out of control
  • for – when index value is necessary
  • for in – when index value is necessary but value itself is NOT necessary
  • for of – when index value is NOT necessary but value itself is necessary
  • forEach – when both index and value are necessary without Promise function

Complete source code can be found here

https://github.com/yuto-yuto/BlogPost/tree/master/src/WhenShouldWeUseForWhileForEach

Comments

Copied title and URL