Sorry, my bad. You won’t use a “for loop” to iterate through an object. You are right, a “for…in” statement is designed for objects, there are other ways as well (Object.keys, for example).
When I said that the “for loop” is more flexible, I meant that a “for…of” statement will iterate through your array starting from the item with index 0 and will go all the way to the last item in the array.
But what if you want to start from the last item of an array and go backwards? You can’t use the “for…of” in this case because you can’t set conditions there. But you can easily do this with the “for loop”. For example, to iterate backwards through the array of vacation spots from the lesson:
let vacationSpots = ["Bali", "Paris", "Tulum"];
for(let i = vacationSpots.length - 1; i >= 0; i--){
console.log("I would love to visit " + vacationSpots[i]);
}
This will print following in the console:
I would love to visit Tulum
I would love to visit Paris
I would love to visit Bali
Or another example, you have an array of, let’s say ten items but you want to loop only through items with indices 3,4,5 and 6. Again, can’t use the “for…of” for this task.
const numbers = [1,2,3,4,5,6,7,8,9,10];
for(let i = 3; i < 7; i++){
console.log(numbers[i]);
}
In your console you will see:
4
5
6
7
Another example, you want to iterate only through values at odd indices:
const oddEven = ["0 - even", "1 - odd", "2 - even", "3 - odd", "4 - even", "5 - odd"];
for(let i = 1; i < oddEven.length; i +=2 ){
console.log(oddEven[i]);
}
The console will print:
1 - odd
3 - odd
5 - odd
To sum up, you can use the “for…of” statement when you just need to iterate through all items in an array in order, but if you need to set a specific condition, then it’s the “for loop”.