Create a Website
HTML
Dreamweaver
CSS Tutorial
JavaScript
FREE Domain!
Any web hosting you subscribe with DotEasy will get you a FREE domain name registration.
PLUS you get:
  • FREE Website Builder
  • FREE Blog
  • FREE Forum
  • FREE Photo Album
  • FREE Email Accounts
Get your FREE domain name today!
Home > JavaScript Tutorial
SSD Web Hosting with FREE Domain

Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.

JavaScript Loops

Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript there are two different kind of loops:

The for loop

The for loop is used when you know in advance how many times the script should run.

The Code

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

The output is:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked.

How to Define a Function

The syntax for creating a function is:

The Code

function functionname(var1,var2,...,varX)
{
some code
}

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function.

Enjoy this tutorial?

1. Link to this page(copy/paste into your own website or blog):
2. Add this page to your favorite social bookmarks sites:
3. Add this page as your favorites. (Press Ctrl+D)