Loops what are they and what can they do


#1

Heyy…Grasshopper can you explain what loops are. I don’t really understand them


#2

Hey @Ayiko_Andrew,

Happy to explain them — they can be a little tricky to grasp.

In their basis, loops will repeat a section of code several times. They are different types of loops that have different ways of controlling how many times a section of code repeats.

A for...of loop repeats the section of code based on the length of a string or array. So, for example, if a for...of loop is using the string ‘HelloWorld’ the section of code will repeat 10 times, since there are 10 letters in ‘HelloWorld’. A for...of loop looks like this:

for (var element of 'HelloWorld') {
    print(element)
}

From the example above, we can see a special feature of for...of loops: for each repeat of the code section, there is a variable (in this case called element) storing one of the letters from the string.

At the very beginning of the loop, element stores the first letter of the string. In the example above, that would be ‘H’. It then runs the section of code (called the block of code), while element is storing ‘H’. This means for the first iteration of the loop above, the letter ‘H’ would be printed out.

The computer then moves on to the next letter in the string, so that element is storing ‘e’; and runs the code in the block while element is holding ‘e’. This repeats for every letter sequentially until there are no more letters in the string — that is the point where the loop stops repeating.

Hope this helps a little!
H :slight_smile: