Saturday, April 30, 2011

JavaScript While Loop - XIII


In JavaScript and most other languages, "loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.
The JavaScript While loop executes code while a condition is true.
For example, you could make your program display a the value of a counter while the count is less than or equal to say, 10.

Example While statement:

<script type="text/javascript">
<!--
var myBankBalance = 0;

while (myBankBalance <= 10) {
document.write("My bank balance is $" + myBankBalance + "
");
myBankBalance ++;
}
//-->
</script>
The resulting output:
Right now, my bank balance is $0
Right now, my bank balance is $1
Right now, my bank balance is $2
Right now, my bank balance is $3
Right now, my bank balance is $4
Right now, my bank balance is $5
Right now, my bank balance is $6
Right now, my bank balance is $7
Right now, my bank balance is $8
Right now, my bank balance is $9
Right now, my bank balance is $10

Exlanation of code

  1. We started by declaring a variable called "myBankBalance" and setting it to 0
  2. We then opened a while loop, inserting our condition between brackets. Our condition checks if the current value of the myBankBalance variable is less than or equal to 10.
  3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of myBankBalance, preceded by some text. This code is placed within curly braces.
  4. We then increment the value by 1.
  5. When the browser reaches the closing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. Of course, by now, the myBankBalance variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 10), it exits from the loop.

No comments:

Post a Comment