Que Logo

Chapter 8

Making a Statement


In This Chapter


Execute and Flow
Two common terms of programmer jargon are necessary in this chapter. When JavaScript reads and performs the actions specified in each statement of code, it is executing the program. Normally, JavaScript will execute each statement in sequence, in the order in which the statements are written. This is called the flow. By default, execution flow follows in sequence. Many of the statements described in this chapter are used to alter program flow-that is, to move execution to a specified region of code. In this way, you build the overall logic of the program. Doing this correctly is one of the challenges of programming, and it often takes some debugging to correct errors in your original logic.
In the first and second chapters of this section on JavaScript, you've explored most of the building blocks of a mature JavaScript program. There are variables that are assigned values, and objects that are made up of subvariables known as properties. Variables can be operated on for mathematical purposes, or be compared together, or in some other way evaluated, thereby making expressions. An expression is any one "clause" of JavaScript code, such as an assignment operator or a comparison operator. Finally, then, you have the statement. A statement brings expressions together, with certain keywords, to make the JavaScript equivalent of an English sentence; that is, using any or all of the building blocks discussed thus far to create program logic that is the whole purpose of a JavaScript in the first place. Statements define and control the flow of the program.
Think of statements as the bones of a JavaScript program. All of the statements in your code comprise the skeleton, which determines the overall shape of the program. Peek at the sidebar on "Execute and Flow" for more understanding of this skeleton. The JavaScript language provides a small but useful set of statements that you can use to direct program flow.

The if … else Statement


It's no coincidence, then, that statements are bookended by keywords that strongly resemble English language statements. One very common JavaScript statement is the If...else statement. This statement functions just as it sounds in English. The following would be an English usage version of an If...else statement:
"If I earn at least $500 this week, I can pay the electric bill, or else my lights will be shut off."
You can generate the exact same sentiment in JavaScript. You will need only two variables: income and lights. Presume that the variable income has been previously assigned some numeric value representing this week's earnings. The variable lights will be assigned on the condition of the income and will receive a Boolean value (true or false), since there are only two possible outcomes for the lights: remain on or shut off. Given all this, the JavaScript version of the above statement, using the JavaScript If...else construction, would look like this:

if (income >= 500) 
 { lights = true }
else
 { lights = false }


In this statement, JavaScript would first evaluate the expression (income >= 500). If this returns a true result, JavaScript executes the statements within the first set of brackets {}. If the expression is false, JavaScript skips ahead to the else clause and executes the statements within the set of brackets immediately below the else keyword. Note that you can include as many statements as you like within the brackets of a clause, but they must be separated by semicolons ( ; ), as in:

{ lights = true ;
  savings = income - bills }


The formatting in both previous examples is purely a matter of taste. JavaScript doesn't care where you put breaks in the lines, as long as you include all of the correct syntax (the brackets, the semicolons, and so on). However, for the human reader, keeping a consistent and somewhat logical format to the code will make debugging far easier and less insanity-inducing in the future.
Now you see how a statement in JavaScript serves as the outline in which most assignments, expressions, and function calls (we haven't covered those just yet) occur. The if...else statement is merely one way to control the logic flow of a JavaScript program.

The while Statement


The while statement is another way to control program flow and execution. It functions the following way:

while (condition) 
 { statements }


In this example, the series of statements within the brackets are executed for as long as the condition specified holds true. The simplest example of a while statement is a simple loop. A loop results when a statement or series of statements are repeated some number of times until some condition changes. Therefore, the while statement is a classic loop. In this simple example, you will keep appending the string "repeat" to a variable named phrase, until the loop has executed 10 times:

count = 1
phrase= ""
while ( count <= 10 )
 { phrase += "repeat " ;
    count++ }


Let's consider a line-by-line analysis of the above code, which pulls together several concepts from previous chapters.
In line one, you assign the value 1 to the variable count. Because you will be using this as a counter, you must assign it an initial value. In this case, you would like count to begin with the value 1, so that is your initial assignment.
In line two, you want to be sure that the string variable phrase starts out empty. To do this, you can assign an "empty string" to it, as shown in the syntax phrase="". This will prepare the string for usage in the loop that follows.
In line three, you construct a while statement. The while loop is defined as proceeding as long as the value of count is less than or equal to 10.
In line four, you begin the statements that comprise the body of the while loop, thus an opening bracket precedes the first statement. In this line, you use an assignment operator to concatenate the string value "string" to the existing value of the variable phrase.
In line five, you increment the counter variable count by 1, using the unary increment operator.
The final result of the example will be that count will hold the value 11, and phrase will hold the string "repeat repeat repeat repeat repeat repeat repeat repeat repeat repeat". Notice that when count has reached 10, it will move through the loop one last time, adding the final "repeat" to phrase, and incrementing count to 11. Then, when the while condition is tested again, it will be false, and the loop will cease. JavaScript would then drop down to the next statement following the while condition's bracketed statements.

The for Statement


Watch Your Syntax
In programming, syntax refers to the "rules of grammar"--in other words, what words or symbols go where. For example, most statements begin with a keyword identifying the statement (such as for). They are followed by a set of parentheses in which special conditions are specified. All of this is syntax-the order of what goes where. If you accidentally violate a syntax rule, such as leaving out a parenthesis or semicolon, you will experience a syntax error. JavaScript will alert you of this when you try to execute the program (load the Web page), and then you'll have to fix it.
The for statement is another statement that creates a loop circumstance. It is much like the while statement, and in fact, in many programming situations, either statement could serve the same role, although their particular syntaxes differ. The real difference is that for statements are more specifically tailored to handle numerical loops. The while statement, although capable of the same (as illustrated in the previous example), is somewhat more flexible in its capability to function on conditions other than numerical loops.
Update That Loop
In any loop, it is presumed that the variable in the test condition is going to change. Otherwise, the loop will never execute if the condition is false, or will never stop executing if the condition is true (this is called an "endless loop"). In a counting loop, you change the counter variable with the "loop update expression." This expression is part of the statement definition, as in the for statement. In this example, you use the unary increment operator as your loop update expression, thus increasing the value of the loop counter count by 1 each pass through the loop.
The for statement is followed by an initial expression (which is often a variable assignment, but may be another statement), a test condition, a loop update expression, and finally, a block of statements to execute. An example would look frighteningly similar to:

phrase = ""
for (count = 1; count <= 10; count++)
 { phrase += "repeat "}


In line one, you assign an empty string to the variable phrase, as preparation.
In line two, define the for statement. The counter variable count is set to 1 to start with. Your test condition for the loop determines whether count is less than or equal to 10. The loop update expression uses the unary increment operator to bump the value of count up by 1.
In line three, you see the statement that makes up the loop itself. It will be executed as long as the test condition remains true. In this case, you use an assignment operator to concatenate the value "repeat" to the string variable phrase.
This example would produce the same results as the while loop: the variable count would hold the value 11, and the variable phrase would hold the string "repeat" in ten consecutive repetitions.
As stated, this is quite similar in logic to the previous while statement. The major differences are that the initial variable assignment for the loop counter and the expression that increments the loop counter are both included in the for statement definition heading (the expressions within the parentheses following the keyword for). This is why the for statement is more suited for these sorts of arithmetic loops, whereas the while statement is flexible enough for other sorts of loops, because it has fewer restrictions on the expressions that can affect the test condition.

The break and continue Statements: Bringing It All Together


Sometimes you will want to jump out of the execution of a loop (as in the while and for statements) in mid-loop. Here is a classic scenario that might demand this sort of "eject from loop" capability. Suppose that you want a facility in your Web page that will total the gross profit of all the purchases made from your site that day. However, you are running a promotion-every 10th purchase receives the order for free! Therefore, when calculating the total gross for the day, we must make exceptions for every 10th order.
The loop will work the following way: Look at each purchase made, and then add its price to a running total until you've reached the end of the purchases. Simple loop. Now for the exception: check each purchase to see if it is a whole integer multiple of 10 (which would mean it was a 10th purchase). If it is, do not add its price to the grand running total. This example will use the continue statement, which is used to drop out of a series of statements within a loop, and return to the top of the loop.
The example code contains three simple variables:
In addition, we have one object, named price. Price has the properties 1, 2, 3, and so on. Each property represents one item purchased and holds the value of its price. For example, price.1 might equal 9.95, price.2 might equal 14.95, and so on.
Notice: Count Those Parentheses
In the continue statement example, take note of the line containing the if keyword. Note how it is followed by double parentheses. This is because you have two sets of "nested" parenthetical expressions. Nesting occurs when you have one parenthetical expression within another parenthetical expression. For example: the if comparison must be in one set of parentheses, as in if ( comparison ). However, the comparison itself is enclosed in parentheses, as in ( count % 10 ), to prevent any possible misinterpretation by JavaScript. It's very important to keep track of your open and closed parentheses, and that every pair matches up; otherwise, you're likely to get syntax errors. And going back through your program to look for missing parentheses is less than fun.
Also, recall that you can refer to objects and properties in the format object[property], as in price[1], which is how you will describe them within the loop code itself.
Here is the code, following which you'll consider what took place.

total = 0
for (count = 0; count <= orders; count++)
 { if (( count % 10 ) == 0 )
     { continue } ;
    total += price[count] }


Several concepts are going on in the previous example, all of which are covered at some point in this book.
In the first line (total = 0), you initialize the summation variable total to zero.
Next, you declare the parameters of the for loop. You begin count at 0 on the presumption that the properties of the object price also began numbering from 0. Be sure to keep an eye out for such things in your own program. You set the for loop condition to remain true while count is less than or equal to the total number of orders. Finally, you set the loop updater to increment count by one. Note that count does not increment the first pass through the loop, and thus remains at 0 until the second pass.
Below the for declaration, you have the set of brackets within which the loop statements are enclosed. In this case, your loop statement is an if statement. Recall that the if statement is followed by its own bracketed statements, which is why there are two sets of brackets in the example. If you follow them closely, you will see that they make sense.
The if statement checks to see whether the current order in question was a 10th purchase. It does this by using the "modulo" arithmetic operator. Consider: you could divide the current value of count by 10. If the current order were a 10th purchase (an even multiple of 10), then this division should yield a remainder of 0. The modulo operator can be used to return the remainder of a division. Therefore, the expression count%10 will return the value 0 on every 10th purchase.
The brackets immediately below the if clause determine what to do if the condition is true; that is, if this is a 10th purchase. Note that your if-true statement is continue. This will cause JavaScript to ignore the remainder of the statements in the brackets of the for statement, and return to the top of the for loop. This will not re-initialize count to zero; it will just continue on with the loop as normal.
Because the previous if statement will ignore the remainder of the loop statement on this pass when the condition is true, you do not need an else statement. If the condition is false-that is, count represents any purchase other than a 10th one-execution will necessarily drop to the final statement in the for loop, which adds the value of the current property of the object price to the running total.
The break statement is similar to the continue statement in usage, although it behaves in one notably different way. Rather than causing the loop to skip ahead to its next trip through, the break statement immediately drops out of the loop entirely. That is, it aborts the loop on the spot and moves on to the next statement in the JavaScript program following the loop. If you were to replace continue in the previous example with break, then once you reached the first 10th purchase in the loop--which would be purchase number 10--the whole loop would end. Clearly, that's not what you want in this example, but in other cases, it might be.

Object-Related Statements


Two statements are designed specifically for the purpose of dealing with objects. Recall once again that an object is a variable that contains a set of subvariables known as properties. Your prototypical object example was the sweater object, which contained the properties material, color, size, and price.
The following statements work with a given object, to help you navigate and/or manipulate its properties. As always, this will make more sense once you look at examples.

The for … in Statement


The for...in statement is a specialized loop, similar to the for statement, but with the purpose of looping through the properties of a particular object. Imagine again your sweater object. Perhaps a customer has chosen to order a sweater, and in other portions of your Web page, he has selected each property that interests him-maybe cotton, black, and XL. Of course, the price property is determined by you, the retailer, as a result of the sort of sweater he chose.
So, now there is a sweater object with four properties, each assigned a value. Imagine now that you are outputting an invoice to the screen for the customer to verify. Now you need to state the values of each of sweater's properties. Doing so requires moving through each property in sweater and printing its value. Sounds like a loop! It is a loop! And, since it is a loop within an object, you need a for...in statement. Quel coincidence!
The loop parameters in the for...in statement are much simpler than the for statement. There is no need to initialize a counter, test for a condition, or update the counter (such as by incrementing it). The for...in loop works only one way: from the first property to the last in the given object. Therefore, the for...in statement looks like this:

for ( counter in objectname )
 { statements }


The counter is any variable name you want to supply as a counter. Objectname is the name of the object whose properties you are interested in. Let's take an easy example. Loop through the properties of the object sweater and add the value of each to a string. Later, that string may be used for some other purpose, such as output to the screen. Your counter will be named count, your object is sweater, and your string will be named descrip (as in "purchase description").

descrip = ""
for ( count in sweater )
 { descrip += sweater[count] + " "}


Voilà! In this example, you first assign the variable descrip to an empty string. Then you define the for...in statement. One statement follows within the loop. It simply concatenates the value of each property of sweater to the current contents of the variable descrip. Note that you are, in fact, adding the expression sweater[count] + " " to the variable descrip. This is simply to include a blank space between each value, so that the string value is more readable if and when it is output later.
At the conclusion of this JavaScript program, the variable descrip might contain a string value such as "cotton black XL 24.95". The exact order of the values in the string depends on the order of the properties in the object sweater, when they were originally created.

The with Statement


Yet again, you are concerned with only one object. The purpose of the with statement is to tell JavaScript which object you are currently concerned with. Then, any references to variables in the bracketed statements that follow are assumed to be properties of the object.
The with statement, in practice, looks like this:

with ( objectname )
 { statements }


Again assume your sweater object. Now, imagine that you are going to assign values to its properties. You don't need to use the with statement; after all, you could assign values in the format sweater.color = black. However, you can also use the with statement the following way:

with ( sweater )
 { material = cotton ;
    color = black ;
     size = XL }


Granted, the with statement doesn't exactly rival sliced bread, or those nifty sandwich makers, as far as inventions of the century go, but besides saving on keystrokes, it also helps improve the formatting and readability of the JavaScript program. Those are always positive qualities when it comes to debugging.

The Comment Statement


Comments Comments Everywhere
<SB>This is the second appearance of comments, as far as this book goes. Previously, you saw comments when we were talking about HTML code. If you recall, the big pep talk was about including the entire JavaScript program within HTML comment tags. That was to prevent non-JavaScript browsers from displaying the code on-screen.
The comments you are considering now are meant to prevent the JavaScript browser from attempting to execute in-code reminders for humans. Comments are used to explain to you, the human, what is going on in the code. Therefore, you don't want JavaScript to attempt to execute them--they'll only wind up producing errors.
If you found the with statement to be short on excitement, this one is even duller. The comment statement is simply a way to insert your own comments into the JavaScript program, for future reference. JavaScript itself completely ignores them. This isn't to denigrate the utility of comments. Including comments in your program is an extremely useful way to remind yourself what the heck is going on, if you must return to the code at a later date. Programming is one of those things where, when you are steeped in the development of a program, everything you do makes sense to you; however, if you return to the program two months later to make some changes or corrections, you'll have absolutely no idea what your code means anymore. This, then, requires you to carefully reread the code to understand it again.
Therefore, including much English commentary in code is a good thing; it's just not an exciting thing.
There are two ways to denote comments in your JavaScript program, depending on whether they fit on one line or span multiple lines. For one-liners, simply precede the commentary with a double-slash: // commentary here.
For multiline comments, surround the text with a /* and a */ at the beginning and end, respectively. Here are two examples of well-commented code:

count = 0 
// this counter will be used to track the number of sweaters ordered
for ( count=1; count <= orders ; count++ )
/* the following loop will go through each order and process them accordingly.
First, we'll check to see if the size is in stock. Then, we'll check for the color
in stock. 
Lastly, we'll see if the purchaser's name is on our blacklist, in which case we
will secretly jack up the price by adding unreasonable shipping and handling costs */

The var Statement


The var statement is more often a matter of style than necessity. In theory, you should precede variable assignments with the word var. That is,

counter = 0

should theoretically be written as

var counter = 0

As you may have noticed, you've not been doing this throughout your examples, and I keep using the words "in theory." That's because you don't actually have to use it. JavaScript knows when you are assigning a variable, but some purists consider it good form to include the var word for program readability.
Having said that, it is necessary in one case to write out var; however, you haven't encountered that scenario yet. You will, when functions are discussed, which just happens to be the next chapter.

The Least You Need To Know


Previous Chapter Next Chapter



Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.