What are loops?
Loops let us repeat some code over and over until a condition is met. We use a loop when we have some logic which we need to happen repeatedly.
If you go out for a walk and want to reach your ten thousand steps for the day, then repeatedly you take steps until you reach ten thousand of them. This would be an example of repeating a sequence until you reach a condition.
Back in the programming world, you may come across the term to iterate over something such as an array. This is the same as using a loop. The three most common types of loops in javascript are the for loop, while loop and the do while loop.
For loops
A for loop is useful to run some code when we know how many times that we want the loop to run. We may want to run some code multiple times until we reach a specific value such as counting up to 10. If we did not use the loop we would have to repeatedly write out the code we want to run and this would break a key principle of writing code called don’t repeat yourself — sometimes shortened to DRY.
For loops have three parts to them:
The for keyword
The condition (this comprises of the initialization, condition and updater).
The code to execute when the loop runs
We start by using their keyword after which we add a set of parentheses.
Moving on to the condition section. To initialize the loop we create a variable commonly people call this i. This variable is then used as the counter for the loop. The variable can be initialized with a value depending on what you want to start counting from. If you want the loop to count up to a certain point (for example 10) and you want the counting to start from the value of 0 then you would initialize the variable iwith the value of zero.
Next, we create the condition itself. The condition is the stopping point. This is the point at which we want the variable i to stop counting and the loop to stop repeating. If we wanted to count up to but not include 10 we would say: i < 10.
Lastly, for the updater, we specify how the counter (the variable i) should change each time that the loop runs. If we want to count up to ten and therefore increase i by one each time that the loop runs we can use the increment operator (++) . The increment operator consists of two addition symbols and will increment a value by one. We add semi-colons between the initialization, condition and Updater The result of the for loop below would be all the values from 0 up to but not including 10 printed out to the console.
Finally, we add a set of curly braces inside which we place the code that we want to execute each time that the loop runs. The result of the loop below would be all the values from 0 up to and including 9 printed out to the console.
Please feel free to post any comments, questions or feedback!
I also have a Udemy course that covers this topic and more.
See you next time!
Top comments (0)