4.4 While Loops

In the last video, we wrote this for the for loop to display all odd numbers between 0 and 5. And in this video, I'll show you how to implement the same logic using a while loop. Now, a key difference between a while loop and a for loop is that in for loops, the loop variable is part of the loop variable itself. But in while loops, you must declare that while variable externally. Let me show you this in detail. So we start by declaring a variable as i and setting it to 0. Notice that this i that we have here is different from the i that we have in this for loop, because this variable is only meaningful and accessible inside this for loop. This is called scope, and I'm going to talk about this later in the course, all I want you to know is that these two variables are completely different, even though their names are the same. Now we have our loop variable initialized to 0. Then we add a while statement, in parentheses, we need to add our condition. So what is the condition here? .... Let i be less than or equal to 5. So I'm going to add that here. Next, we need to add our statements. So what is the statement that we want to repeat, this is the statement. We want to display the odd numbers, so we'll add that here as well, and finally, at the end of this while block, we need to increment i. So this is a direct translation of this for loop into a while loop. So this is what happens when we run this code. Initially, I is equal to 0, now in the while loop, this condition is first evaluated, if this condition is true, the body of the while loop will be executed. Again, in the next iteration, the condition is evaluated again, if it is true, the instructions of the while block will be executed, otherwise the while block will end. That's it for this demonstration on the while loops. See you in the next video, where we will look at another type of loops in JavaScript.