↑
Main Page
Variables
?
End-of-line semicolons are optional.
Java, C, and Perl require that every line end with a semi-
colon (
;
) to be syntactically correct; ECMAScript allows the developer to decide whether or not
to end a line with a semicolon. If the semicolon is not provided, ECMAScript considers the end
of the line as the end of the statement (similar to Visual Basic and VBScript), provided that this
doesn’t break the semantics of the code. Proper coding practice is to always include the semi-
colons because some browsers won’t run properly without them, but according to the letter of
the ECMAScript standard, both of the following lines are proper syntax:
var test1 = “red”
var test2 = “blue”;
?
Comments are the same as in Java, C, and Perl.
ECMAScript borrowed its comments from
these languages. There are two types of comments: single-line and multiline. The single-line
comments begin with two forward-slashes (
//
), whereas multiline comments begin with a
forward-slash and asterisk (
/*
) and end with an asterisk followed by a forward-slash (
*/
).
//this is a single-line comment
/* this is a multi-
line comment */
?
Braces indicate code blocks.
Another concept borrowed from Java is the code block. Code
blocks are used to indicate a series of statements that should be executed in sequence and are
indicated by enclosing the statements between an opening brace (
{
) and a closing brace (
}
).
For example:
if (test1 == “red”) {
test1 = “blue”;
alert(test1);
}
If you are interested in the specifics of ECMAScript’s grammar, The ECMAScript Language Specification
(ECMA-262) is available for download from ECMA’s Web site, at
www.ecma-international.org
.
Variables
As I mentioned, variables in ECMAScript are defined by using the
var
operator (short for
variable
), fol-
lowed by the variable name, such as:
var test = “hi”;
In this example, the variable
test
is declared and given an initialization value of
“hi”
(a string).
Because ECMAScript is loosely typed, the interpreter automatically creates a string value for
test
without any explicit type declaration. You can also define two or more variables using the same
var
statement:
var test = “hi”, test2 = “hola”;
12
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 12
Free JavaScript Editor
Ajax Editor
©
→