Articles → JavaScript → Loops In Javascript

Loops In Javascript






Software Requirements




  1. Any browser runs on windows operating system supports JavaScript.
  2. Notepad or any text editor for writing code.

Prerequisite Knowledge




  1. Basic knowledge of JavaScript.
  2. Basic knowledge of HTML.
  3. Knowledge of any programming language is an added advantage.

Purpose Of Loops





Types Of Loops




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

For Loop






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


  1. Here variable_name is an identifier. i, j, k, count etc are all examples of identifiers.
  2. start_value is a value from which loop starts.
  3. end_value is a value up to which loop executes.
  4. increment_value is the value to which the loop increments.


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




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



While Loop






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




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



Do While Loop








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






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




  1. Code inside the o block gets executed.
  2. While 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

Click to Enlarge



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



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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250