Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

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:

  1. Set a variable to 20.
  2. Log its current value.
  3. Decrement it by 1.
  4. If it's still greater than 0, go back to line 2.

The problem with this is it's very convoluted and confusing to read. To find out the test condition you have to scan until you find the correct if-statement, which means it's hard to put many inside the looping part. To solve this, programmers came up with the while-loop, which we'll see next.

Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.