Welcome back everyone and happy day 50! It’s so good to be able to say that I’ve successfully stuck to blogging as I code for this long, and as we are always learning there will always be something to learn!
So let’s start on a new topic now, looking at While Loops and Do Loops. Cheers as always to FreeCodeCamp for the lessons.
Iterate JS with While Loops
When we create a while loop, we are saying that “while” the conditions of the argument is true, the loop will continue and stop when the conditions are false. Let’s take a look at one in action:
Here, we can see that while the variable i is smaller than 5 (that’s the condition, which will remain so while it is true), the statement inside the curly brackets will .push() (or add) the value of i into the square brackets of ourArray one loop at a time. Beginning at 0 (the starting value of i), i increments (++) by 1 per loop (i=i+1) until it reaches 4 before becoming false. When it reaches a value of 5 it is no longer smaller than five (i<5), and will therefore become false. So, the while loop will end we can expect the finished array called ourArray to have values [0,1,2,3,4].
Iterate JS with For Loops
The next loop is called a for loop. This is the most common type of loop and it runs “for” a set number of times. The for loop (and future loops) are declared with three optional expressions:
for ([initialization]; [condition]; [final-expression])
Note: It’s very important to see that each expression is separated by semicolons, and the loop won’t work without them.
The initialization (American spelling) typically defines and sets up the loop variable, and is executed once at the beginning.
The condition is the part of the loop which if true will execute the loop and is evaluated at the beginning of each cycle of the loop, when it becomes false, the loop will end. If the condition is false to begin with, the loop will not work.
The final-expression is executed at the end of each loop iteration, and is used to increment or decrement your loop counter.
So here we have our initialization of i = 0, then we have our condition which says i is less than 5, and while that is true, i will increment by 1 per loop, as seen in the final-expression. During this, in the statement, we .push() (or add) the value of i onto the end of ourArray.
Like the while loop example above, we are going to have the same result here using the for loop and end with an array containing [0,1,2,3,4].
Iterate Odd Numbers with a For Loop
We don’t always have to iterate for loops by single numbers each time, we can also change a little part of the final-expression so that the value of i increments/decrements by an even number. This is done like-so:
Note: Notice the final-expression is incrementing now by 2 (i += 2). This += operator is saying that i = i + 2.
If we wanted the loop to count up each new value in odd numbers, we’d change our initialization expression to say i =1, therefore the values would increment up from 1 as i now equals 1, when we combine that with the final-expression of i+=2, this increments in odd numbers as 1 + 2 = 3 and so on.
Let’s say we want to create an array with values that begin at 1 and end at 9, where our condition says that i is less than or equal to 9 (i <= 9):
This will execute and line 6 will give out [ 1, 3, 5, 7, 9 ].
Counting Backwards with a For Loop
Under the right conditions, we can count backwards, or decrement our value in even or odd numbers of our choosing (set in the final-expression) per loop. Let’s take a look at an example of that:
Here we are beginning at 9 in the initialization, and then in the condition we say for the loop to work and remain true, i is greater than or equal to 1, and in the final-expression we say that i decrements by 2 per loop, as i = i - 2.
As we can guess, the first loop is i = 9, i = 9 - 2 which equals 7. Then the next loop begins: i = 7 - 2… We eventually reach i = 1, and afterwards the loop condition is false, so the loop ends with an array of [9,7,5,3,1].
Iterate through an Array with a For Loop
How about using a for Loop on an array? Let’s take a look at one case where we want to console.log each separate element of the array into the console (imagine the array is a box of eggs, each element of the array is each egg, and we take each egg out and lay them one by one on the table (the console) per every loop).
So, the for loop here states in it’s initialization that the value of i equals 0 and because arrays use zero-based indexing, in the example above, array = 10. Each loop that is true while i is less than the .length() (or number of characters, in this case, elements) of the array in the condition (and stops when i equal to the length, which is 5), it will increment i by 1 per loop (seen in the final-expression).
The last iteration in the loop is when i becomes equal to the length, which is the same as i === 4 (index), that’s the index with a value of 6 in the array.
Let’s break that down a bit further: the last index in the array is equal to length -1 which is the same as 5 elements (the array length) - 1 = index number ), which will output 6 (a.k.a array) in the console.
For each loop that iterates, we have a statement that says “print out into the console each element of the array”, not the array itself, like we did before. This will give us each individual array index value in the console, like-so:
If we wanted to take all the elements in an array and add them together we would go about it like this:
So we have 5 elements in the array called myArr. We define a variable called total to equal 0 and we also define a variable called i into the global scope as null.
Next, in our initialization of the for loop, we initialize the loop with the expression that i is equal to the length of the array - 1, that’s the same as saying 5(elements) - 1 = myArr. So therefore the first loop iteration condition begins with i === 4.
For the condition, the loop executes as long as i is greater than or equal to 0.
For each loop that holds that condition as true, we decrement (--) the value of i by 1 per loop, in doing so we unintentionally work backwards through the array from myArr to myArr.
As these loops are happening each time, our statement is taking the total (which starts as 0) and adds it with the array’s element value, and carries that sum over to the next loop. This means
loop 1: (total(0)+myArr(6) = 6),
loop 2: (total(now 6)+myArr(5) = 11),
and so on until i is no longer greater than or equal to 0 (the condition becomes false), when the last statement is carried out:
total(now 18 at this point) + myArr(2) = 20.
If we were to console.log() the final result, we can do so by assigning the statement to a variable such as final. And write console.log(final); which gives 20.
Nesting For Loops
Lastly, If we have a multi-dimensional array, or an array within an array, then we can apply the same logic as above to work through an array and it’s nested arrays:
So here we have an array called arr, and there is one top-level array containing three nested arrays inside, containing six sub-elements of arr. We also have a following top-level for loop with a nested for loop inside it.
In the one statement, we console.log() (or print out into the console) the top-level for loop first, then its nested for loop after, in that order. Note how the nested for loop’s expressions are working based off of the top-level for loop.
The first top-level for loop prints out the three array sets, because i begins at 0 (top-level for loop initialization) and then increments by 1 per loop (top-level for loop’s final-expression), until it reaches the length of arr (the boundaries of the condition) which is 3, and next the nested for loop takes those 3 sets from the top-level for loop, and individually prints out all the sub-elements of arr, the values (1–6) into the console, as long as the nested for loop condition holds true that j is less than the length of arr[i] (6 total elements) which itself is an array.
Remember: On the top-level array there are 3 elements, and the nested array there are 6.