JAVASCRIPT LOOPS


In javascript loops are used to repeat a function till the given condition satisfies.

For loops in javascript

For loops execute till the condition satisfies.Once the end limit of loop is reached then for loop stops executing and compiler comes out of for loop,

    Syntax:

    for(condition){
    coding
    }
<!DOCTYPE html>
<html>
<head>
<title>
JAVASCRIPT
</title>
</head>
<body>
<p id="out">
</p>
<script>
var i;
var data="";
for(i=0;i<=7;i++){
data += "Your luck says" + i + <"br>";
}
document.getElementById
("out").innerHTML=data;
</script>
</body>
</html>

Output:

Here in above case loop starts from i=0 and continues till value of i is less than or equals 7.i++ is used to increment the value of i with every rotation of for loop.

While loops in javascript

While loop functions almost like for loop.We use both these loops depending on preference where which one can do work more efficiently.All the functions of for loop can be executed via while loop and vice versa.

    Syntax:

    while(condition){
    coding
    }

Example:

<!DOCTYPE html>
<html>
<head>
<title>
JAVASCRIPT
</title>
</head>
<body>
<p id="out">
</p>
<script>
var i=0;
var data="";
while(i<=7){
data +="<br>Your luck says" + i;
i++;
}
document.getElementById
("out").innerHTML=data;
</script>
</body>
</html>

Output: