JavaScript‎ > ‎

Loops


For Loop

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++) {
    document.write("The number is " + i);
    document.write("<br />");
}
</script>
</body>
</html>

While Loop

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5) {
    document.write("The number is " + i);
    document.write("<br />");
    i++;
}
</script>
</body>
</html>

Do-While Loop

<html>
<body>
<script type="text/javascript">
var i=0;
do {
    document.write("The number is " + i);
    document.write("<br />");
    i++;
}
while (i<=5);
</script>
</body>
</html>

For-Each Loop

<html>
<body>
<script type="text/javascript">
var person={fname:"John",lname:"Doe",age:25};
for (x in person) {
     document.write(person[x] + " ");
}
</script>
</body>
</html>



Note: The break and continue statements will work in JavaScript loops just like C/C++,Java, etc..

Comments