1 of 15

While Loops In JavaScript

Because keeping count is hard

2 of 15

JavaScript Loops

We are going to start with While Loops. Those are basically the same as “until loops” in Scratch.

3 of 15

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?

4 of 15

JavaScript Loops

var count = 0;

while(count < 5){

println(“I love Girls Who Code!”);

count = count + 1;

}

This part defines the starting condition.

5 of 15

JavaScript Loops

var count = 0;

while(count < 5){

println(“I love Girls Who Code!”);

count = count + 1;

}

The rest is kind of like Scratch.

6 of 15

JavaScript Loops

var count = 0;

while(count < 5){

println(“I love Girls Who Code!”);

count = count + 1;

}

Look familiar?

7 of 15

JavaScript Loops

var count = 0;

while(count < 5){

println(“I love Girls Who Code!”);

count = count + 1;

}

8 of 15

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.

9 of 15

JavaScript Loops

var i= 0;

while(i < 5){

println(“GWC Rocks!”);

println(“Loops are Awesome!”);

}

println(“All done!”);

What happens here?

10 of 15

JavaScript Loops

var i= 0;

while(i < 10){

println(i);

i++;

}

What happens in this example?

11 of 15

JavaScript Loops

var i= 0;

while(i < 5){

println(i);

}

What happens in this example?

12 of 15

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”);

}

13 of 15

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;

}

}

14 of 15

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!

15 of 15

JavaScript Loops

Okay this is tricky, lets do some more examples in our worksheet.