Essential JavaScript

While Loop

Loops are a way to run the same code multiple times. The most basic loop is the while loop:

while (/* this condition is true */) {
  // run this code
}

A while loop is just an if statement that keeps running as long as the condition is true. If you can write an if statement, you can write a while loop.

Example

Take a look at this example:

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

The code inside the loop will run repeatedly as long as i < 3.

Since i starts out at 0, the loop will execute at least once.

The loop adds 1 to the value of i. This means i will eventually equal 3 and the loop will stop.

Infinite looping

It is possible to create an infinite loop in JavaScript.

This is bad for you. If you create an infinite loop, your code will freeze.

This is the most basic infinite loop:

while (true) {
 // do nothing
}

Try running this in the console. JavaScript will just get stuck at this loop.

This website can recognize code that is stuck in a loop, so it will just stop your code and tell you it took too long to execute.

If you wrote this code on a web page, your page would freeze.

Here's another example that could be an accident:

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

This is an infinite loop because i will always be less than 3. There's nothing in the loop to change it.

Be careful and make sure there's always a way for your loop to end.

Iteration

Following a process repeatedly is called iteration.

Each time we execute the code in a loop, we call that run of the loop an iteration.

This is an important word for being able to talk about loops.


Learning Goals

Code Editor