The JavaScript loops are
used to iterate the piece of code using for, while, do while
or for-in loops. It makes the code compact. It is mostly used in array.
Loops offer a quick and easy way to do
something repeatedly.
There are many different kinds of loops, but
they all essentially do the same thing: they repeat an action some number of
times (and it's actually possible that number could be zero). The various loop
mechanisms offer different ways to determine the start and end points of the
loop.
There are four types of loops in JavaScript.
1) for loop
2) while loop
3) do-while loop
4) for-in loop
Type
|
Description
|
|
for loop
|
A
for loop repeats until a specified condition evaluates to false. The JavaScript
for loop is similar to the Java and C for loop.
Syntax
|
|
while loop
|
A
while statement executes its statements as long as a specified condition
evaluates to true.
Syntax
|
|
do-while loop
|
The
do...while statement repeats until a specified condition evaluates to false.
syntex
|
|
for-in loop
|
The
for...in statement iterates a specified variable over all the enumerable
properties of an object. For each distinct property, JavaScript executes the
specified statements
|
For loop
The JavaScript for loop iterates
the elements for the fixed number of times. It should be used if number of
iteration is known. The syntax of for loop is given below.
Syntax
for (initialization; condition;
increment)
{
code to be executed
}
|
Example- for loop
<script>
for (i=1; i<=5; i++)
{
document.write(i +
"<br/>")
}
</script>
|
Output:
1
2
3
4
5
|
D0-while
The do...while loop is similar to the while loop except that the condition
check happens at the end of the loop. This means that the loop will always be
executed at least once, even if the condition is false.
Example - D0-while loop
var a = 0;
do {
a
+= 1;
console.log(a);
} while (a < 15);
|
while loop
The most basic loop in JavaScript is the
while loop which would be discussed in this chapter. The purpose of a while
loop is to execute a statement or code block repeatedly as long as an
expression is true. Once the expression becomes false, the loop terminates.
Example – while loop
var m = 0;
var a = 0;
while (m
< 3) {
m++;
a += m;
}
|
for-in loop
var friend
= { name:"Nitin", age: 25, degree: "MCA" };
for (var
item in friend) {
alert(friend[item]); // => "Nitin", then 25,
then "MCA"
}
|
break
statement
When
JavaScript encounters a break statement in a loop it immediately exits the loop
without executing any other statements in the loop. Control is immediately
transferred to the statement following the loop body.
var add =
0;
for (var i
= 1; i <= 1000; i++)
{
add += i;
if (i === 500) {
break; // immediately transfers control outside
the for block
}
}
alert("add
= " + add);
|