Sample Video Frame

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.

The Code

The while-loop does the same thing as our fake code above; it just reverses the way it's written. You write the test at the top, put the code inside {..} just like if-statements, and JavaScript handles all the jumping and looping for you.

let count = 5;

while(count > 0) {
    console.log(`count down ${count}`);

// what value is count right here?
while(count < 10) {
    if(count % 2 == 0) {
        console.log(count, "EVEN");
    } else {
        console.log(count, "ODD");


You should study this, as I am increasing and decreasing the count using the -- and ++ operators. You may not know those yet, but they work like our pseudo code count = count - 1 above. Notice also that now I can easily put an if-statement inside the while-loop, and I actually could nest these infinitely if I wanted (to be a bad programmer).

What You Should See

$ node "code.js" 
count down 5
count down 4
count down 3
count down 2
count down 1

You should try to break this. There are many ways to break this code. The simplest is to just forget to increment (++) or decrement (--) the count variable.

You should also try putting while(true) as one of the loop conditions to see what happens.

Learn JavaScript Today

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

Still Not Sure? Try the next FREE Lesson!