Loops what are they and what can they do

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

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') {

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:


This is a very helpful explanation. Can someone add a practical or common use for this? Why would you want to perform an action for every letter in a string?

There is a very good example of this in our new Intro to Interviewing course! In one of the puzzles, you’ll create an object out of a string, and this object will serve as a kind of map, showing what letters are in the string and where they appear.

For example, the string 'boo' will turn into an object that looks like:

  b: [0],
  o: [1, 2]

This shows that 'boo' has a 'b' at index 0, and an o at indices 1 and 2. This object is made by looping through the string.

Once you finish the Fundamentals II course, you’ll be able to access Intro to Interviewing.