March 7th, 2020
Glad to be back! Unfortunately, we had to postpone the series for a while, due to a lot of events I’m going through for these past few months, but I’m fresh and ready to continue our progress! So welcome back! This time we’ll be talking about loops! Oh and, before we begin, feel free to check out Day 5 if you haven’t!
Javascript in 15 Days : Review Day
So, what exactly are loops? Loops are basically a set of steps or a program, that is run for a specified number of iterations until a condition is met. In Javascript, there are 2 basic types of loops, a FOR loop, and a WHILE loop.
So, what is a for loop? Here, you can see a basic example of printing numbers from 1 to 10.
Here, the output should be like this.
So let me explain its syntax.
Here, a FOR loop consists of 4 things (components). First of all, initialization. This is usually where you assign a variable/variables that will later be used in the second part, the condition. If you want to initialize more than one variable, be sure to use a comma. Next up, condition. Here you set a condition in which the loop will stop its iteration. Be sure to correctly set up your condition, as the bad condition does have a tendency of creating an infinite loop. Next up, the increment/decrement. This is where you manipulate your initialized variable, so as to prevent the creation of an infinite loop. Finally, the statement. This is a block of code that will be executed every time the condition is met. To make it simple, here is the step-by-step flow of a FOR loop.
So above is the FOR loop. Now, onto our next topic, the WHILE loop.
Using our previous example, here is an example of the previous FOR loop being converted to a WHILE loop.
So, as you can see, a WHILE loop has a much similar syntax to that of a FOR loop. The only difference is that the initialization is outside the WHILE scope, the increment/decrement is inside the WHILE scope, and the condition is inside the parentheses right beside the “while” keyword. Pretty straightforward right?
Now, you might be asking, why are there 2 kinds of loops? Why not just use one? Aren’t they all the same?? I know, I know. I’m gonna explain real quick. Actually, in terms of use, you can convert a WHILE loop to a FOR loop and vice versa, but here’s food for thought on when to use FOR loop and WHILE loop. Usually, you would use the FOR loop if you know the exact number of iterations needed, as in the WHILE loop is usually used if you don’t know for sure how long it should iterate. For now, you may not really be sure when to use a FOR loop and when to use a WHILE loop, and that’s fine. The more you practice and encounter problems, the more you are certain on when to use each type of loops.
So, I’m afraid our current session ends here. I will be introducing the Math Object during our next session and if you need practice, be sure to DM me on Twitter or LinkedIn!