📖 JavaScript Loops
Loops are designed to improve the handling of repetitive statements. Repetitive statements are statements that execute repeatedly for a given number of times or until a condition is met.
There are 3 types of recursive statements in JavaScript.
While Statements
Code is executed over and over again as long as a certain condition is true. When the condition becomes false, then the loop will end. Something must happen inside the loop to increment the counter and eventually stop the loop. This is often interchangeable with the do while statement.
/* Format */
initialize counter; // counters must be initialized before beginning the loop but can be done programmatically
while (conditional expression) { // evaluated on each 'loop', continues while condition is true
statements to repeat;
increment counter as needed; // some counters must be manually incremented
}
/* Example */
var x = 1;
while (x <= 10) {
document.write(x + " is my favorite number.
");
x++;
}
// The document.write statement and increment statements will be repeated as long as x is less than or equal to 10.
While loops can be used without a counter if the condition can change by other means. The code below checks user input for a number and returns the prompt if the input is not a number using the built-in JavaScript isNaN function.
var guess = prompt("What's your favorite number?");
guess = parseInt(guess);
while(isNaN(guess)){
guess = prompt("That's not a number! What's your favorite number?");
guess = parseInt(guess);
}
For Statements
Code is executed over and over again as long as a given condition is true. Similar to while statement, but always uses a counter, counter is initialized, evaluated and incremented within the constructor. Use when you know how many times you want to execute the code.
/* Format */
for (initialize variable; relational expression; increment variable) { // used to control loop
statements to repeat;
}
/* Example */
for (var x = 1; x <= 10; x++) {
document.write(x + " is my favorite number.
");
}
// The document.write statement will be repeated as long as x less than or equal to 10.
// After each iteration, x is incremented by 1.
Do...While Statements
Code is executed over and over again until a certain condition is false. Rules for the while statement apply to the do . . . while statement as well. Main difference between while and do . . . while is that the do . . . while statements will always be executed at least once.
/* Format */
do {
statements to repeat;
increment counter as needed;
} while (conditional expression);
/* Example */
do {
document.write(x + " is my favorite number.
");
x++;
} while (x <= 10);