Articles → JavaScript → Loops In Javascript
Loops In Javascript
Purpose Of Loops
Types Of Loops
- For loop
- While loop
- Do while loop
- 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 i | Is condition i <= 10 satisfied | Action |
---|
1 | No | Execute the code block and increment the value of i |
2 | No | Execute the code block and increment the value of i |
3 | No | Execute the code block and increment the value of i |
4 | No | Execute the code block and increment the value of i |
5 | No | Execute the code block and increment the value of i |
6 | No | Execute the code block and increment the value of i |
7 | No | Execute the code block and increment the value of i |
8 | No | Execute the code block and increment the value of i |
9 | No | Execute the code block and increment the value of i |
10 | Yes | Exit 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
- Code inside the do block gets executed
- While the 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';
for (x in obj) {
alert(x);
// alert(obj[x]); // this will prompt karan, India and .net
}
Try It