Back

Technologies:

javascript
Tolerim
a month ago

What is the difference between for...of and for...in loops, and why can they be substituted for each other in certain cases?

As a senior JavaScript developer, I am inquisitive to understand the differences between for...in and for...of loops in JavaScript. Recently, I faced an issue while working on a coding exercise that required me to list all odd and even numbers of an array consisting of integers from 1-10 inclusive, which led me to switch up the two loops. When I implemented a for...in loop, I was able to list all odd numbers. However, when I tried to list all even numbers using the same loop, the code didn’t work correctly, as it displayed only some even numbers.

After that, I realized my mistake and switched to a for...of loop, which helped me to iterate through each element of the array. While I was able to find a solution, I am curious to understand how it works under the hood. Below is the function where I made the initial mistake.

``````let numbers = [1,2,3,4,5,6,7,8,9,10]
function displayOddNumbers() {
for (num in numbers) {
num % 2 != 0 ? console.log(num) : console.log();
};
};
``````
The code worked correctly, but I used a for...in loop instead of a for...of loop. For the next exercise, I was supposed to display all even numbers from the same array. I used the same for...in loop, which displayed some even numbers instead of all of them. The code I used is shown below.

``````function displayEvenNumbers() {
for (num in numbers) {
num % 2 == 0 ? console.log(num) : console.log();
};
};
``````
In this case, I needed to list all even numbers from the same array, but this code only displayed some even numbers. When I analyzed it, I realized that the for...in loop didn't work correctly because it iterates over keys instead of values. That’s why I changed my code to:

``````function displayEvenNumbers() {
for (num in numbers) {
num % 2 != 0 ? console.log(numbers[num]) : console.log();
};
};
``````
After switching to a for...of loop or using the correct index, I was able to display all even numbers effectively.