JavaScript Looping
Loops in JavaScript are used to execute the same block of code a specified number of times (iteration). Loops in JavaScript are:-
- for loop
- while loop
- do - while loop
- for - in loop
for loop
The for statement provides a useful way to iterate over a range of values. For loop first executes a statement called the initialization statement. Then the condition is checked before every execution of the code block. ‘for’ loop runs until the condition evaluates to false. Increment/decrement statement acts as a counter and it executes after the code block execution each time.
Syntax:
for (initialization;condition;increment/decrement)
{
code to be executed
}
Eg:
<script>
for(i=1;i<=5;i++)
{
document.write(i+" x 10 = "+i*10);
document.write("<br>");
}
</script>
Output:
1 x 10 = 10
2 x 10 = 20
3 x 10 = 30
4 x 10 = 40
5 x 10 = 50
while loop
The while loop continuously executes a block of code while a particular condition is satisfied. Its syntax is:-
while (condition)
{
code to be executed
}
Eg:
<script>
var i = 1;
while(i < 6)
{
document.write(i+" x 10 = "+i*10);
document.write("<br>");
i++;
}
</script>
Output:
1 x 10 = 10
2 x 10 = 20
3 x 10 = 30
4 x 10 = 40
5 x 10 = 50
do - while loop
'do - while loop' executes a specified block of code until the test condition evaluates to false. The condition is evaluated after executing the statement. So the block of code executes at least once.
Syntax:
do
{
code to be executed
}
while (condition);
Eg:
<script>
var i = 0;
do
{
document.write("Hello, How are you?");
document.write("<br>");
i++;
} while(i <= 1)
</script>
Output:
Hello, How are you?
Hello, How are you?
for - in loop
The 'for - in' loop iterates over all the enumerable properties of the object.
Syntax:
for(key in object)
{
code to be executed
}
Eg:
<script>
var student_data = {Student_ID:"1234",Course:"BCA", Year:"2021", Merit:"yes"};
for(items in student_data)
{
document.write(items + " : " +student_data[items]);
document.write("<br>");
}
</script>
Output:
Student_ID : 1234
Course : BCA
Year : 2021
Merit : yes