jorgelopez

Posts: 26 Join date: 2009-01-18 Age: 23
 | Subject: Javascript Loops! Thu Jul 23, 2009 2:11 pm | |
| Javascript LoopsLoops are a must know in Javascript. Loops are important because it allows us to perform repetitive tasks without having to write a lot of code.
The most well-known and most used loop is the "for loop". The syntax for a "for loop" is:| Code: | for(var i = 0; i < 10; i++) { Here goes the code to be executed. } |
Another loop is the "while loop". The while loop will keep on running until the expression in the parenthesis is false. The syntax is:
| Code: | while(y < 100) { Here goes the code that should be run. } |
In the above example. The loop will keep on iterating until y is greater than 100. The expression will be false.
There's also the "for in loop". The "for in" loop is useful for iterating through arrays or the properties of an object. The syntax is:
| Code: | for(var item in myArray) { document.write(myArray[item]); } |
Here's a complete example code of this loop:
| Code: | <html> <head> <title>loops</title>
<script type="text/javascript">
var myArray = new Array(1,3,5,32, 6,2,9);
for(var item in myArray) { document.write(myArray[item]); }
</script
</head>
<body>
</body> </html> |
|
|