Basic While Loops in JavaScript:

If you need to repeat something again and again with just a small change each time, loops are your method. If you need to repeat certain actions until a certain condition has been met (say, a password has been entered) then loops can be your method.

A JavaScript while loop repeats a line (or lines) of code while a specified condition is true. Once the condition isn't true anymore, and the loop goes to start again, the fact that the condition isn't true will trigger the browser to move past the while loop and continue with any code that follows the loop.

Loops are powerful, and if not used correctly, can crash the browser. Think through your loop and try to make sure you have coded, in the JavaScript, how the user or browser will exit the loop.
Also use common sense --if you deliberately tell a loop to loop a large number of times, say 400x or more, you should often expect some problems...


Basic Syntax for a While Loop:

while (condition) {
    JavaScript lines of code (code block) for the browser to execute
}

Basic Example While Loop: - require user to enter something at a prompt

One of the many useful things you can do with a while loop is to force the user to enter something at a prompt:

var usersname = "";
while (usersname == "" || usersname == " " || usersname == null) {
    usersname = prompt("Please enter your name:");
}

//while usersname is still an empty string, a space, or null (from the user hitting Cancel), repeat the code within the loop.

Here is a working version of the above example - Basic While Loops - require name at prompt which alerts after the loop receives something for usersname.




Relevant w3schools notes, for reference: