Articles → JavaScript → Loops In Javascript
Loops In Javascript
Software Requirements
- Any browser runs on windows operating system supports JavaScript.
- Notepad or any text editor for writing code.
Prerequisite Knowledge
- Basic knowledge of JavaScript.
- Basic knowledge of HTML.
- Knowledge of any programming language is an added advantage.
Purpose Of Loops
Types Of Loops
- For loop
- While loop
- Do while loop
- 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
}
- Here variable_name is an identifier. i, j, k, count etc are all examples of identifiers.
- start_value is a value from which loop starts.
- end_value is a value up to which loop executes.
- 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 i | Is condition i <= 10 satisfied | Action |
---|
1 | No | Execute the code block and Increment value of i |
2 | No | Execute the code block and Increment value of i |
3 | No | Execute the code block and Increment value of i |
4 | No | Execute the code block and Increment value of i |
5 | No | Execute the code block and Increment value of i |
6 | No | Execute the code block and Increment value of i |
7 | No | Execute the code block and Increment value of i |
8 | No | Execute the code block and Increment value of i |
9 | No | Execute the code block and Increment value of i |
10 | Yes | Exit 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 );
- Code inside the o block gets executed.
- While condition is checked. Condition fails.
- 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';
Click to Enlarge
for (x in obj) {
alert(x);
// alert(obj[x]); // this will prompt karan, India and .net
}