JScript Statements
A JScript program is a collection of statements. A JScript statement, which is equivalent to a complete sentence in a natural language, combines expressions that perform one complete task.
Using Statements
A statement consists of one or more expressions, keywords, or operators (symbols). Typically, a statement is contained within a single line, although two or more statements can appear on the same line if they are separated with semicolons. In addition, most statements can span multiple lines. The exceptions are:
The postfix increment and decrement operators must appear on the same line as their argument. For example, x++ and i--.
The continue and break keywords must appear on the same line as their label. For example, continue label1 and break label2.
The return and throw keywords must appear on the same line as their expression. For example, return (x+y), and throw "Error 42".
A custom attribute must appear on the same line as the declaration it is modifying, unless it is preceded by a modifier. For example, myattribute class myClass.
Although explicit termination of statements at the end of a line is not required, most of the JScript examples provided here are explicitly terminated for clarity. This is done with the semicolon (;), which is the JScript statement termination character. Here are two examples of JScript statements.
var aBird = "Robin"; // Assign the text "Robin" to the variable aBird.
var today = new Date(); // Assign today's date to the variable today.
A group of JScript statements surrounded by braces ({}) is called a block. Statements within a block can generally be treated as a single statement. This means you can use blocks in most places that JScript expects a lone statement. Notable exceptions include the headers of for and while loops. The following example illustrates a typical for loop:
var i : int = 0;
var x : double = 2;
var a = new Array(4);
for (i = 0; i < 4; i++) {
x *= x;
a[i] = x;
}
Notice that the individual statements within the block end with semicolons, but the block itself does not.
Generally, functions, conditionals, and classes use blocks. Notice that unlike C++ and most other languages, JScript does not consider a block to be a new scope; only functions, classes, static initializers, and catch blocks create a new scope.
In the following example, the first statement begins the definition of a function that consists of an if...else sequence of three statements. Following that block is a statement that is not enclosed in the braces of the function block. Therefore, the last statement is not part of the function definition.
function FeetToMiles(feet, cnvType) {
if (cnvType == "NM")
return( (feet / 6080) + " nautical miles");
else if (cnvType == "M")
return( (feet / 5280) + " statute miles");
else
return ("Invalid unit of measure");
}
var mradius = FeetToMiles(52800, "M");