16: While Loops

You can do quite a lot of programming once you have a way to test variables and a way to jump to different parts of your program. The if-statement combines jumps with tests to skip over blocks of code. We call this "branching", as in following different branches of a tree. The next thing you can do is "looping" where you repeat a block of code until a test is true or false.

The first loop you'll learn is a while-loop, and it will repeat a block of code as long as a test if true. If you wanted to simulate a while-loop with just jumps and if-statements you might write this:

count = 20
log("count=", count)
count = count - 1
if(count > 0) goto line 2

I'm again using the "fake" concept of goto so you can understand what the computer is really doing. This isn't real JavaScript but "psuedo code" to demonstrate the concept. As you can see all I do is the following:

Learn JavaScript Today

Register today for the Beginner Basics course and get the new releases by just paying the difference. There's also special discounts for existing customers when new courses are released.


Still Not Sure? Check out more curriculum!