Difference between classic for loop and for...of loop in JS?

Hi all. :grinning:

I’ve learned how to use the classic for loop and the for…of loop. And I was wondering about the difference between classic for loop and the for…of loop. :stuck_out_tongue:

For example with a classic for loop:

console.log("Counting from 0 to 9...");
// This prints "Counting from 0 to 9...".
for (var i = 0; i < 10; i = i + 1) {
    console.log(i); // This prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
}
// I am declared the classic for loop with var. I also declared the i variable as the looping element. By the way, it increment by 1 and reach from 0 to 9 until the test is false.

And the for…of loop:

var fruitList = [
    "Apple",
    "Banana",
    "Orange"
];
for (var element of fruitList) {
    console.log(element); // This prints Apple, then Banana and Orange.
}

Please answer. :yum:

Thank you!
Pummarin :smile:

for…of loop iterates over the elements of the indicated object

in the for loop instead you indicate the variable starting value, the stopping condition and how the value changes at each iteration

the for…in loop iterates over the properties names of the object

in the while loop you put just a condition, and the loop keeps going for as long as that condition is true

a do…while loop works like a while loop, with the difference that the loop is executed at least once, and only after the code is executed the first time the condition is checked

When you have an iterable object, you can use the for… of loop. The syntactic sugar doesn’t require you to explicitly state that an array, map, set, etc has a beginning index value of 0 and that you should increase by 1 each time to get the next value.

Here’s a reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of