Transcript from the "while Loops" Lesson
>> So, in order to start work on our doggo fetching, we're going to talk about another type of loop. So this is loop on loops, you could say [LAUGH]. And as Cardi B says, sometimes we have to keep replaying and replaying and replaying something. And sometimes we don't want to, we want to not loop over a certain number of iterations.
[00:00:48] Until a certain condition that we give the loop, similar to a condition we give our if statements, right? Until that condition is no longer true. So as long as the condition that I give a while loop is true, the while loop is gonna keep replaying that chunk of code inside of its block, inside of its curly braces.
[00:01:10] So in this case, I have a while loop that is basically populating an array. I have an empty array that's called five random numbers, which is kind of a misnomer at the beginning because it has zero numbers in it. And then I have a while loop that's basically saying, okay, while or as long as the length of the five random numbers array is less than five, push a new random number into the array.
[00:01:41] So by the time this is done running, my five random numbers will no longer be a lie, and we actually will have five numbers in our array. So let's go to the console and prove it to ourselves. Okay so, if I create my five random numbers array, it's empty at the moment.
[00:02:04] And when I run my while loop, we're going to see something else happen to the array. And now if I asked for five random numbers, we can see that it actually did do what I asked. It pushed five different random numbers because it called math.random five times into the array.
[00:02:25] What do you think happens if I run it again, if I run my while loop again. Am I gonna push five more random numbers into the array?
>> I think so.
>> Yes, no, we have bets on both horses. So let's find out, let's run it, see what happens, five random numbers.
[00:02:48] It still only has those five numbers, why? Because while loops care about a condition, and the condition that I've given it here is isfiverandomnumbers.length<than five. If so, run the while loop, run this chunk of code, and when I ran it that second time, even before we ever did a new math.randomcall.
[00:03:14] The length of the array was already five, so not less than five. So we didn't actually execute the line of code in the while loop. So it's kind of, like a conditional loop you could think of it as. While can be dangerous, so if you like chaos and destruction and not being able to use your browser or computer in some cases.
[00:04:15] So, if you want to watch the world burn like Elmo, go for it but I do not recommend you copy and paste this line of code, I should have disabled the copy button [LAUGH].