For loops allow you to execute code for each element in a collection or range.
For the love of loops
How to do it...
Take a look at the following steps and code:
- Let's imagine that we have an array of elements, and we want to do something with every item in the array:
let theBeatles = ["John", "Paul", "George", "Ringo"]
- We can use a for loop, which will extract each element of the array in turn, and will execute the given block of code for each element. The syntax of a for loop is as follows:
for <#each element#> in <#collection or range#> {
<#code to execute#>
}
- So, to print all the musicians in the Beatles, let's loop through our theBeatles array...