While Loops In JavaScript
Because keeping count is hard
JavaScript Loops
We are going to start with While Loops. Those are basically the same as “until loops” in Scratch.
JavaScript Loops
var count = 0;
while(count < 5){
println(“I love Girls Who Code!”);
count = count + 1;
}
This is a while loop to print "Girls Who Code Rocks" 5 times. But how does it work?
JavaScript Loops
var count = 0;
while(count < 5){
println(“I love Girls Who Code!”);
count = count + 1;
}
This part defines the starting condition.
JavaScript Loops
var count = 0;
while(count < 5){
println(“I love Girls Who Code!”);
count = count + 1;
}
The rest is kind of like Scratch.
JavaScript Loops
var count = 0;
while(count < 5){
println(“I love Girls Who Code!”);
count = count + 1;
}
Look familiar?
JavaScript Loops
var count = 0;
while(count < 5){
println(“I love Girls Who Code!”);
count = count + 1;
}
JavaScript Loops
var count = 0;
while(count < 5){
println(“I love Girls Who Code!”);
count = count + 1;
}
Everything between these brackets is part of the loop.
JavaScript Loops
var i= 0;
while(i < 5){
println(“GWC Rocks!”);
println(“Loops are Awesome!”);
}
println(“All done!”);
What happens here?
JavaScript Loops
var i= 0;
while(i < 10){
println(i);
i++;
}
What happens in this example?
JavaScript Loops
var i= 0;
while(i < 5){
println(i);
}
What happens in this example?
JavaScript Loops
They are kind of similar to for loops:
var count = 0;
while(count < 5){
println(“hello world”);
count = count + 1;
}
for(var i = 0; i < 5; i++){
println(“hello world”);
}
JavaScript Loops
However, they are more flexible, you could use them to keep track of pretty much anything, like a game that goes up to a certain score:
while(score < 100){
if(answer === “correct”){
score = score + 1;
}
else{
score = 0;
}
}
JavaScript Loops
Anytime you know you need to repeat, but you don’t know how many times you need to repeat, use a while loop!
JavaScript Loops
Okay this is tricky, lets do some more examples in our worksheet.