while statement

Home > Courses > JavaScript > Loops - while Loop

JavaScript while Loop

What will you learn in this page?

  1. What is the while loop meant for

  2. Syntax of while

  3. Basic while examples

  4. The do...while loop

  5. Nested loops

LoopsSelection Sort ExerciseLoopsCollatz Conjecture Exercise

Introduction

As we learnt in the previous chapter on the for loop, there are essentially two main categories of loops in JavaScript — for and while. We've already covered for quite extensively, and likewise what's left now is while.

In this chapter, we aim to unravel the purpose behind while in addition to considering an array of various examples of its usage. Without any single doubt, while forms a crucial part of modern-day programming. Many many algorithms are powered by the powerful nature of while.

So what is while? Let's see it...

Home > Courses > JavaScript > Loops - while Loop

JavaScript while Loop

What will you learn in this page?

  1. What is the while loop meant for

  2. Syntax of while

  3. Basic while examples

  4. The do...while loop

  5. Nested loops

LoopsSelection Sort ExerciseLoopsCollatz Conjecture Exercise

Introduction

As we learnt in the previous chapter on the for loop, there are essentially two main categories of loops in JavaScript — for and while. We've already covered for quite extensively, and likewise what's left now is while.

In this chapter, we aim to unravel the purpose behind while in addition to considering an array of various examples of its usage. Without any single doubt, while forms a crucial part of modern-day programming. Many many algorithms are powered by the powerful nature of while.

So what is while? Let's see it...

What is while meant for?

By design:

The while loop is meant to repeatedly execute a piece of code an unknown number of times.

For instance, if we want to print 'Hello' until the user enters -1 in an input prompt, what we need is the while loop.

Similarly, if we want to iterate over a queue, removing items one-by-one, until there is no item left, this could also be done using a while loop.

Technically speaking, anything that can be done, or is done, using while can also be done using for, and vice versa. It's just that the syntax of while sometimes suits the situation better and obviously asks for less setup than a for loop.

Let's now see the syntax of while.

Syntax of while

The while loop begins with the while keyword, followed by a pair of parentheses (()) encapsulating the condition of iteration, followed by the loop's body.

Here's a programmatic view of this syntax:

while (condition) statement;

The loop continues iterating as long as the given condition remains true. The moment it becomes false, the loop ends.

If you recall, this is identical to how the condition in a for loop works — that is, if it's true, the next iteration happens, or else the loop ends.

With the syntax also done, it's finally time to consider some quick examples.

Examples

Suppose we want to compute the sum a couple of positive numbers entered by the user.

The way the entry happens is via an input prompt for the first number, followed by another input prompt for the second number, and so on, until the value entered is -1. -1 signals the end of the whole stream of numbers to add.

Such a special value is often referred to as a sentinel. A loop that iterates up until the point a sentinel is seen is, likewise, referred to as a sentinel-controlled loop.

Anyways, this task can very easily be accomplished with the help of while as shown below:

var sum = 0;
var input = prompt('Enter a number, -1 to exit.');

while (input !== '-1') {
   sum += Number(input);
   input = prompt('Enter a number, -1 to exit.');
}

alert(`The sum is ${sum}.`);

Live Example

If we were to accomplish the same thing using for, we'd go like:

var sum = 0;
var input = prompt('Enter a number, -1 to exit.');

for (; input !== '-1'; ) {
   sum += Number(input);
   input = prompt('Enter a number, -1 to exit.');
}

alert(`The sum is ${sum}.`);

See how the syntax of for is a little bit less intuitive and a little more to type. In this case, while is definitely the better choice.

As another example, suppose we want to remove elements from the end of an array, using the pop() method, until it becomes empty. This also can be done nicely using a while loop.

Consider the following code:

var arr = [1, 3, 5];

while (arr.length !== 0) {
   console.log(arr.pop());
}

5 3 1

The condition arr.length !== 0 checks if the array has anything remaining in it. If there is something remaining, the condition evaluates to true, and hence the loop's body executes, thereby removing the last element from the array (via the arr.pop() call).

Note that arr.pop() effectively reduces the length of arr as the loop progresses and thus takes it closer and closer to the success of the condition arr.length !== 0. Without arr.pop(), we'd get an infinite loop.

Recall that an infinite loop is one that runs forever and causes the current program to simply crash!

Although the code above works perfectly, you'll often see one common convention used out there to check whether an array has elements remaining within it.

That is, for a given array arr, instead of using arr.length !== 0 to check whether there are any remaining elements in arr, the expression arr.length is used.

When it coerces to true, it simply means that the array's length is not 0 and hence there is still something remaining in it. This is effectively identical to arr.length !== 0.

Likewise, the code above can be rewritten as follows:

var arr = [1, 3, 5];

while (arr.length) {
   console.log(arr.pop());
}

5 3 1

The while loop here can be read as: "while the array has some length, keep removing its last element."

Once again, remember that if arr.length returns a positive number (which means that arr has some elements in it), it would coerce to the Boolean value true, and thus get the loop to be executed.

Last updated