Articles → JavaScript → Loops In Javascript

Loops In Javascript






Purpose Of Loops





Types Of Loops




  1. For loop
  2. While loop
  3. Do while loop
  4. For in loop

For Loop





Syntax Of For Loop


for (variable_name = start_value; variable_name <= end_value; variable_name = variable_name + increment_value) {
	//	Code of block to be executed
}




for (i = 1; i <= 10; i = i + 1) {
	//	Code of print numbers
}

Try It



Value of variable iIs condition i <= 10 satisfiedAction
1NoExecute the code block and increment the value of i
2NoExecute the code block and increment the value of i
3NoExecute the code block and increment the value of i
4NoExecute the code block and increment the value of i
5NoExecute the code block and increment the value of i
6NoExecute the code block and increment the value of i
7NoExecute the code block and increment the value of i
8NoExecute the code block and increment the value of i
9NoExecute the code block and increment the value of i
10YesExit loop



While Loop





Syntax Of While Loop


while (condition) {
	//    code to be executed
}




i = 1;
while (i <= 10) {
	// Code to execute
	i++;
}

Try It


Do-While Loop







Syntax Of Do-While Loop


do {
	//    code to be executed
}
while ( condition );






var i = 2;
do {
	//  Code to execute
}
while ( i == 1 );

Try It



  1. Code inside the do block gets executed
  2. While the condition is checked. Condition fails
  3. Loop exits

For-In Loop






for (variable_name in object) {
	//    code to be executed
}




var obj = new Object();
obj['name'] = 'karan';
obj['address'] = 'India';
obj['tech'] = '.net';




Picture showing a sample object in JavaScript with attributes




for (x in obj) {
	alert(x);
	// alert(obj[x]); // this will prompt karan, India and .net
}

Try It


Posted By  -  Karan Gupta
 
Posted On  -  Monday, July 16, 2012

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250