Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
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 is used when you know in advance how many times the script should run.
<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>
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.
The syntax for creating a function is:
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.