While Loops
While Statement Loops
It is possible for a while
loop to stand without the do
. Including the do
guarantees that the statement inside the while
will process once. It is wise to take care with stand-alone while
loops, as they have a natural tendency to go infinite.
The while
loop executes its statements if the designated condition (i.e. n < 3
) reads as TRUE. If the condition reads FALSE, the statement within the loop stops executing and control passes on.
The condition is checked before the statement (i.e. n++; x += n;
) is executed, at which point, the condition is checked again.
If the condition returns FALSE, execution stops and control passes on before the statement is executed.
To execute multiple statements, use a block statement ({...}
) to group.
//While Loops
//Create a variable
var score = 0;
//Set a condition in parens
while(score < 10){
//Set an increment operation
score++;
//Print to the console
console.log("Score: ", score);
}
//Another example
var age = 0;
while(age < 100){
age+=10;
console.log("Age:", age);
}
if (age === 100){
console.log("I made it!");
}
//A challenge -create a while loop that prints 10-100 by 10s. AT 50
// print "Halfway there!"
var counter = 0;
while(counter < 100){
counter+=10;
if(counter === 50){
console.log("There's halfway");
} else {
console.log(counter);
}
}
Difference Between For and While Loops
// for loop
var cars = ['BMW', 'Volvo', 'Saab', 'Ford'];
var i = 0;
var text = '';
for (;cars[i];) {
text += cars[i] + '<br>';
i++;
}
// while loop
var cars = ['BMW', 'Volvo', 'Saab', 'Ford'];
var i = 0;
var text = '';
while (cars[i]) {
text += cars[i] + '<br>';
i++;
}
Last updated