JavaScript in 60 Seconds

While loop

What is a while loop?

A loop allows you to repeat an action based on some condition, similar to an if statement.

var result = 9; while (result > 0) { // is result greater than 0? // this code will run over and over again UNTIL the condition is no longer // true result = result - 1; // count down until we reach zero. }

Dangers with loops

Beware of loops where the condition never changes.

This is called an infinite loop. And it will usually make your browser tab crash. It will never stop running until the tab crashes.

var someCondition = true; // Infinite loop. This will crash your browser tab. while (someCondition) { // this code will run over and over again UNTIL the condition is no longer // true }

How to avoid infinite loops

To avoid infinite loops you have to ensure that the condition changes at some point:

var i = 0; while (i < 5) { // this will increment each time the loop runs, and then it'll stop running // when the condition 'i<5' is no longer true i = i + 1; // without this line it would still be an infinite loop. }