4.5 Do...While Loops

Okay now, let's take a look at the third type of loop we have in JavaScript. This is a do-while loop. Do-while loops are very similar to while loops, but they are slightly different. It's easier to show you in the code. So I'm going to rewrite this logic using a do-while loop. Just like the while loops, we have to declare our loop variable externally, so we declare i and initialize it to 0. Now, if we save the changes, we get an error that means we've already declared i. Because I declared it here, so I can't redeclare it here. This is different from the i that we have in the for loop, again, this is about scope, and I'll talk about that later in the course So, to make this work, I'm going to temporarily comment out these few lines and rewrite this logic using a do while loop. So we add the do statement here, and then a block of code. In this block, we should have our instructions. So we're going to copy them to our while loop, and paste it here, and then finally at the end of this block, we add the while statement with our condition so i less than or equal to 5, followed by a semicolon. Now, you may be wondering what the difference is between a while loop and a do-while loop, do-while loops are always executed at least once even if this condition is false. Let me show you this in detail. So I'm going to comment out these few lines temporarily. And bring back our while loop. Also, we don't need this block right now, we'll comment it out, now if you save the changes, we get 1, 3, 5 on the console. However, if I change i to 9, we're not going to get anything, because the first time we try to execute this while loop, this condition evaluates to false. So these instructions are never executed We save all the changes and see there is nothing in the console. So, in while loops, this condition is evaluated in advance at the beginning of each iteration. On the other hand, in do-while loops, this condition is evaluated at the end. And this means that these statements are always executed at least once. Even if the condition is false. Let's try this: I'll comment out this while loop, and change i to 9, just like before. Save the changes, we get 9 on the console, why? Because in our do-while loop here, on line 15, we check if it's an odd number and display it on the console. Then we increment i by 1, so i is equal to 10. Then the condition is evaluated, so it is false and our loop will end. Now realistically, we're not going to use this do-while much in programming, there are situations you might want to use, but in practice, most of the time you'll use a for or while loop. That's it for this little demonstration on Do-While loops, let's meet again for a very next video