The JavaScript Diaries: Part 3

By Lee Underwood

Let's look at one more script, using the increment operator ( ++ ). (This one is taken from JavaScript: The Definitive Guide.) This one looks simple but is a little more complex to describe. The main thing is to look at the work done by the increment operator:

<script type="text/javascript">
var count=0;
while (count<10) {
  document.write(count + "<br>");

This little script will write the numbers 0-9 on your screen, each on its own separate line.

  • The first line in the script declares the variable count and initializes it with a value of 0.
  • Then a while statement is executed on the second line.
    • Basically, a while statement evaluates an expression, which is contained within the parenthesis following the reserved word while. In this case the expression would be (count<10). If the expression is false (if the variable count is equal to or greater than 10), the script then moves on to the next section in the program (in this case it would end). If it is evaluated as true, a loop is begun which includes the statement within the brackets following the expression. The expression is then evaluated in a continual loop until it returns a value of false. At that time, the script moves on to the next section in the program.
  • In this script, the variable count is evaluated the first time as being 0, which is less than 10 (count < 10), making the while statement true.
  • The value of the variable is then printed to the document, a line break is entered on the page, and the value of the variable count is increased by one by the increment operator (count++).
  • This is done 10 times (0-9). On the 11th time, the variable will be equal to the number shown in the while expression. (The variable count will have been incremented to a value of 10.)
  • The statement is then evaluated as false because the variable count is now equal to 10. The script, in this case, is ended. Try it yourself and see what happens on your Web page.

That wraps it up for this installment. You might want to try analyzing some smaller, ready-made scripts on your own. Many can be found in the JavaScript section of Script Search and at JavaScript Source. Perhaps in the future we will take a look at some of these scripts and apply some of our what we've learned. Even if we can't make sense of the entire script right away, we can pick out sections that we are familiar with to obtain a better understanding.

This article originally appeared on WebReference.com.

Page 6 of 6

Previous Page
1 2 3 4 5 6

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date