JS While Loop


While loop will execute a code block if the statement is true.

var i=0;
var sum=0;
while (i < 10)
{
	sum += i;
	i++;
}
alert(sum); //55


Do while loop will execute the code block one time before check whether the statement is true. And then execute the code block till the statement is false.

var i=0;
var sum=0;
do
{
	sum += i;
	i++;
}
while (i < 10)


Use break to jump out of the loop:

var i=0;
var sum=0;
while (i < 10)
{
	sum += i;
	if (i == 4) break;
	i++;
}
alert(i); //4
alert(sum); //0+1+2+3+4=10


Use continue to skip 1 step of the loop:

var i=0;
var sum=0;
while (i < 10)
{
	i++;
	if (i == 4) continue;
	else
	sum += i;
}
alert(i); //10
alert(sum); //51

We must put i++ before the if statement, otherwise, if the i is not increased, the while loop will keep running forever till the browser collapse.

endmemo.com © 2020  Terms of Use | Home