JS: Arrays
Theory: for...of loop
for refers to low-level loops. It requires a counter, rules for how and when the counter changes, and a stopping condition. It would be much more convenient to traverse items in a collection directly, without using a counter. Many programming languages solve this by introducing a special kind of loop. JavaScript also has one: for...of.
As you can see from the example, code that uses a for...of loop is much cleaner than code that uses a for loop. for...of knows how to loop through the elements and knows when they will end.
This loop is great for aggregation tasks:
for...of is more than just a loop for arrays. To fully understand how it works, you need to understand topics we haven't covered yet, including objects, packing/unpacking, and iterators. In simple terms, different data in JavaScript can pretend to be collections of elements. The simplest example is a string: for...of loops through the string character by character.
However, a string should not be confused with an array. While accessing string elements by index may be similar from the outside, a string is not an array.
Usage
In most tasks that use a loop, for...of is preferable. Sometimes, however, this is not enough, and manual override is required. In such cases, you can go back to using for. For example, when you don't want to go through every element of an array, but every other one:
Occasionally, you need to traverse an array in reverse order. for...of of is no use here, and you need for again:
Other tasks aren't really related to arrays at all. The latter include situations where you need to go through numbers in a certain range. In this case, there is no array you can go through using for...of.
Finally, there are situations where you need to change the original array during the traversal:
If look forward at how actual JavaScript code is written, you can see higher-order functions. In other words, in practice, one might say that loops are unnecessary with few exceptions. However, we can't just skip over working with loops because it's an important base. And higher-order functions require an understanding of topics that can't just be learned in one sitting.
Recommended programs
Completed
0 / 22

