Tutorial 5. For each loop
How to iterate over an array
To iterate over an array, type the item variable, a semicolon, and then the array variable or expression. This notation is similar to the for-of expression, except that there is no need to declare the item variable. The generated code is compatible with old browsers and does not depend on for-of support.
Let's build and run the project. We are going to see the elements of the array in the console.
apples oranges tomatoes carrots
How to iterate over an object
To iterate over an object's properties, type two variables instead of one, separated by a comma. The first variable will have the key of the current property, and the second will hold its value. As with iteration over arrays, do not declare any variables.
Two loops on one skewer look too heavy. Let's put each loop on a separate branch of a silhouette. First, we transform the flowchart into a silhouette. Then, we cut and paste the second loop in its silhouette branch. Let's give the branches meaningful names.
Iteration over an object is implemented with the Object.keys() method, which works everywhere.
We build and run the project. The console shows both property names and values.
apples - 40 oranges - 60 tomatoes - 50 carrots - 30
The For-loop icon supports iteration over plain objects only. You cannot use Maps and Sets in a For-loop icon. To iterate over a Map or a Set, use Map.forEach() and Set.forEach() methods respectively.
The traditional "for" loop
This construct will also output the content of the array to the console.
0 - apples 1 - oranges 2 - tomatoes 3 - carrots
As always, do not declare any variables here.