JS While Loop

JavaScript while Loops in Action

The first loop we will discuss is the while loop. A while loop executes a certain block of code as long as an expression evaluates to true.

Syntax of the while Loop

The snippet below demonstrates the syntax of the while loop:

while (condition) {
    // code that gets executed as long as the condition is true
}

The while loop will only be executed as long as the condition is true, so if the condition is false to begin with, the code inside will be skipped entirely.


Example 1: Printing Numbers

Here is a very simple example of a while loop printing the numbers 0 to 9 (excluding 10) to the console:

Basic while Loop

let i = 0;
while (i < 10) {
    console.log(i);
    i++;
}

Step-by-Step Explanation:

  1. Create a variable, i, and set its value to zero.
  2. Start the while loop and check the condition that the value of i is smaller than 10.
  3. Since the condition is true, the code logs i and increases i by 1.
  4. The condition gets evaluated again; 1 is still smaller than 10.
  5. Since the condition is true, the code logs i and increases i by 1.
  6. The logging and increasing continues until i becomes 10.
  7. 10 is not smaller than 10, so the loop ends.

Example 2: Searching in an Array

We can have a while loop that looks for a value in an array, like this:

Searching an Array

let someArray = ["Mike", "Antal", "Marc", "Emir", "Louiza", "Jacky"];
let notFound = true;

while (notFound && someArray.length > 0) { if (someArray[0] === "Louiza") { console.log("Found her!"); notFound = false; } else { someArray.shift(); } }

It checks whether the first value of the array is a certain value, and when it is not, it deletes that value from the array using the shift method. Remember this method? It removes the first element of the array. So, by the next iteration, the first value has changed and is checked again.

If it stumbles upon the value, it will log this to the console and change the Boolean notFound to false, because it has found it. That was the last iteration and the loop is done. It will output: Found her!

Why check someArray.length > 0?

Why do you think the && someArray.length > 0 is added in the while condition? If we were to leave it out, and the value we were looking for was not in the array, we would get stuck in an infinite loop. This is why we make sure that we also end things if our value is not present, so our code can continue.


Example 3: Generating the Fibonacci Sequence

We can also do more sophisticated things very easily with loops. Let's see how easy it is to fill an array with the Fibonacci sequence using a loop:

Fibonacci Sequence

let nr1 = 0;
let nr2 = 1;
let temp;
let fibonacciArray = [];

while (fibonacciArray.length < 25) { fibonacciArray.push(nr1); temp = nr1 + nr2; nr1 = nr2; nr2 = temp; }

console.log(fibonacciArray);

In the Fibonacci sequence, each value is the sum of the two previous values, starting with the values 0 and 1. We can do this in a while loop as stated above. We create two numbers and they change every iteration.

We have limited our number of iterations to the length of the fibonacciArray, because we don't want an infinite loop. In this case, the loop will be done as soon as the length of the array is no longer smaller than 25.

We need a temporary variable (temp) that stores the next value for nr2. And every iteration we push the value of the first number to the array. If we log the array, you can see the numbers getting rather high very quickly. Imagine having to generate these values one by one in your code!


Exercise

?

Why did we use someArray.length > 0 in the array search example?