While Loop in JavaScript - Do While Loop

Loops

Suppose you are asked to write a program to print 10000 numbers. Will you write 10000 lines to perform the same task again and again?? Well, you will but I won't. The solution to this is LOOP. There are different kinds of loops to perform identical tasks all the way for you.

  • While Loop
  • For loop

We will be covering both of them and their derivatives in this and next tutorial.

While Loop

While as a names says is a loop that will be executed while the condition is true.


while (condition){
  statement1;
  statement2;
  }

Now coming to our problem of printing 10000 numbers, lets take a variable and intialize it with 1. Then we will print it, increment it and do same steps for next 9999 times.


var number = 1;
while(number<10000){
	console.log(number);
	number++;	//Never forget to change the condition else you will land in infinite loop.
}

Coming to the infinite loop

This is the infinite loop -->

Note - This may lead to freezing of your browser's window


while(true){
	console.log("To Infinity");
}

Do while Loop

do while loop works exactly as the while loop but the instructions/statements will be executed atleast once. The execution will happen in the do block and then the control will and then control will check while loop condition. If true then these statements will be repeated again. Hence the code will be executed at least once.


do{
   statement1;
   statement2;
}
while (condition);

Breaking the Loop

Sometimes it is required to break out of the loop as soon the the results are obtained or the task is completed. No extra efforts are required in case we studied the previous switch tutorial. Coming out of loops is as easy as coming out of switch statements by using break keyword.


while(searching){
	if(results found){
		break;
	}
}


var temp = 1;
while(temp<10){
	console.log("Less than 10");
	if(temp===4){
		console.log("Temp is 5");
		break;
	}
	temp++;
}

Assignment

  • Try converting the above code with do while

Solution


var number = 1;
do{
	console.log(number);
	number++;	
}
while(number<10000);


Next > < Prev
Scroll to Top