-
Title:
While Loops - JavaScript Basics
-
Description:
-
Hey James, wasn't it kind of annoying that you had to type out
-
the same if statement twice?
-
>> Yeah. I think I broke one of the cardinal rules of programming: don't
-
repeat yourself.
-
>> Mm-hm.
-
Yeah.
-
And with that in mind,
-
I think it's probably time that we should talk about loops.
-
>> So is that why we're looking at an animated GIF?
-
>> Okay. That's one reason.
-
The second is because that is an awesome GIF.
-
But really, I think the important part here is that a GIF repeats itself
-
automatically.
-
We don't have to tell a GIF to play itself again, it just does it.
-
And in fact, JavaScript gives us a few tools to do this as well.
-
And we're going to go ahead and start with a while loop.
-
>> A while loop lets us repeat a piece of code so
-
long as some condition evaluates to true.
-
Once it doesn't evaluate to true, we exit the while loop.
-
The syntax is while condition.
-
And then in curly braces, some sort of code here.
-
So for this one we have doSomething();.
-
>> Hey let's let's show an example.
-
>> Okay. While(cameron.job ==="course dev") should make courses.
-
>> I like that example.
-
Notice how this is similar to python, but it includes conditions in parentheses,
-
and actions and curly braces, just like with if statements.
-
Remember, if the condition evaluates to true,
-
we'll do the action, then ask ourselves again, is the condition true?
-
We'll continue following this loop.
-
Until the condition is no longer true, at which point will exit the loop.
-
Over here, so long as my job is course developer, I'll keep making courses.
-
The while loop will ask itself again, is Cameron still a course developer?
-
If so, make courses.
-
Until at some point,
-
when my job is no longer course developer, at which point will exit the loop.
-
>> How might that happen?
-
>> Hm.
-
Perhaps there's a limit on how many courses I can make.
-
10 courses maximum.
-
You know what?
-
Let's see what this looks like in code.
-
Outside of the loop,
-
I'll create an iterator called courses, which is going to start at 0.
-
This is going to keep track of how many courses I've made.
-
After making a course,
-
I'm going to add 1 to the number of courses that I've made.
-
Let's add an if statement to our loop that checks if the number of courses I've
-
made is 10.
-
And if so, changes my job to learning specialist.
-
Afterwards, the loop exits.
-
>> Interesting.
-
Let's check to see if that works.
-
Here's the make course function that console logs Made a course every time
-
it's run.
-
And lets console.log,(cameron.job) when we're finished running the loop.
-
So, when we run it,
-
we can see that it's printed made a course to the counsel log 10 times.
-
And then when it finished,
-
it printed out learning specialist, Cameron's new job.