JavaScript 101 /loops
Arrays
Before we start with loops, let's quickly learn a bit more about arrays.
An important thing about arrays is that every element has an index. The index is the position of the element in the array. And, arrays are zero-indexed, meaning the first element is at index 0. If you would like to access the first element, you would use array[0].
Pseudocode
Pseudocode is a way to write down logic in a more human way. If you struggle with writing code directly, pseudocode can help you. It helps you think through the logic and structure of your program without worrying about syntax (how the code looks).
Loopin' time
Loops allow us to execute a block of code multiple times, which is especially useful when working with arrays. When something happens multiple times, loops help us avoid writing repetitive code. It's really easy to do something for every element in an array, for example.
For...of loop
The cleanest and shortest way to iterate over existing arrays.
No index available automatically.
For loop
You can set the boundaries yourself.
More complex syntax, more room for errors. Not as clean.
forEach loop
It is used to iterate over arrays. You can create a forEach either without or with an index.
It's a bit harder to read/remember.
For loop - for arrays
Want to loop through an array and have access to the index? Use a traditional for loop.
A final assignment for this chapter
Conclusion
Many other methods exist, some of them we will look at later. You don't need to know all of them. Some (perhaps with little experience) swear by them, but honestly, you can do everything with these two.
A small tip: Use a for loop if you need the index. Use a for...of loop if you only need the data.