Cover | Table of Contents | Colophon
if statement, the while loop, and the && operator. The similarity ends with this syntactic resemblance, however. JavaScript is a loosely typed language, which means that variables do not need to have a type specified. Objects in JavaScript map property names to arbitrary property values. In this way, they are more like hash tables or associative arrays (in Perl) than they are like structs (in C) or objects
(in C++ or Java). The OO inheritance
mechanism of JavaScript is prototype-based like that of the little-known language Self. This is quite different from inheritance in C++ and Java. Like Perl, JavaScript is an interpreted language, and it draws inspiration from Perl in a number of areas, such as its regular-expression and array-handling features.<html>
<head><title>Factorials</title></head>
<body>
<h2>Table of Factorials</h2>
<script>
var fact = 1;
for(i = 1; i < 10; i++) {
fact = fact*i;
document.write(i + "! = " + fact + "<br>");
}
</script>
</body>
</html><script>
document.write("<h2>Table of Fibonacci Numbers</h2>");
for (i=0, j=1, k=0, fib =0; i<50; i++, fib=j+k, j=k, k=fib){
document.write("Fibonacci (" + i + ") = " + fib);
document.write("<br>");
}
</script>file: URL. Note that the code uses the document.write() method to display its HTML output so that you can see the results of its computations. This is an important technique for experimenting with JavaScript. As an alternative, you can also use the alert() method to display plain-text output in a dialog box:alert("Fibonacci (" + i + ") = " + fib);<html>, <head>, and <body> tags in your HTML file.javascript: URL pseudoprotocol to evaluate a JavaScript expression and return the result. A JavaScript URL consists of the javascript: protocol specifier followed by arbitrary JavaScript code (with statements separated from one another by semicolons). When the browser loads such a URL, it executes the JavaScript code. The value of the last expression in the URL is converted to a string, and this string is displayed by the web browser as its new document. For example, you might type the following JavaScript URLs into the while keyword, for example, must be typed "while," not "While" or "WHILE." Similarly, online, Online, OnLine, and ONLINE are four distinct variable names.onclick event handler attribute is sometimes specified as onClick in HTML, but it must be specified as onclick in JavaScript code (or in XHTML documents).;), just as they are in C, C++, and Java. The semicolon serves to separate statements from each other. In JavaScript, however, you may omit the semicolon if each of your statements is placed on a separate line. For example, the following code could be written without semicolons:a = 3; b = 4;
a = 3; b = 4;
return, break, and continue statements (which are described in ). For example, consider the following:return true;
return; true;
return true;
break outerloop;
break keyword, causing a syntax error when it tries to interpret the next line. For similar reasons, the ++ and −− postfix operators (see ) must always appear on the same line as the expressions to which they are applied.// and the end of a line is treated as a comment and is ignored by JavaScript. Any text between the characters /* and */ is also treated as a comment; these C-style comments may span multiple lines but may not be nested. The following lines of code are all legal JavaScript comments:// This is a single-line comment. /* This is also a comment */ // and here is another comment. /* * This is yet another comment. * It has multiple lines. */
12 // The number twelve 1.2 // The number one point two "hello world" // A string of text 'Hi' // Another string true // A Boolean value false // The other Boolean value /javascript/gi // A "regular expression" literal (for pattern matching) null // Absence of an object
{ x:1, y:2 } // An object initializer
[1,2,3,4,5] // An array initializer_), or a dollar sign ($). Subsequent characters can be a letter, a digit, an underscore, or a dollar sign. (Digits are not allowed as the first character so that JavaScript can easily distinguish identifiers from numbers.) These are all legal identifiers:i my_variable_name v13 _dummy $str
\u followed by four hexadecimal digits that specify a 16-bit character encoding. For example, the identifier π can also be written as \u03c0. Although this is an awkward syntax, it makes it possible to translate JavaScript programs that contain Unicode characters into a form that allows them to be manipulated with text editors and other tools that do not support the full Unicode character set.
break
|
do
|
if
|
switch
|
typeof
|
case
|
else
|
in
|
this
|
var
|
catch
|
false
|
0 3 10000000
0xff // 15*16 + 15 = 255 (base 10) 0xCAFE911
char, as C, C++, and Java do. To represent a single character, you simply use a string that has a length of 1.' or "). Double-quote characters may be contained within strings
delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes. String literals must be written on a single line; they may not be broken across two lines. If you need to include a newline character in a string literal, use the character sequence \n, which is documented in the next section. Here are examples of string literals:"" // The empty string: it has zero characters 'testing' "3.14" 'name="myform"' "Wouldn't you prefer O'Reilly's book?" "This string\nhas two lines" "π is the ratio of a circle's circumference to its diameter"
true and false. A value of type boolean represents a truth value; it says whether something is true or not.a == 4
a is equal to the number 4. If it is, the result of this comparison is the boolean value true. If a is not equal to 4, the result of the comparison is false.if/else statement in JavaScript performs one action if a boolean value is true and another action if the value is false. You usually combine a comparison that creates a boolean value directly with a statement that uses it. The result looks like this:if (a == 4) b = b + 1; else a = a + 1;
a equals 4. If so, it adds 1 to b; otherwise, it adds 1 to a.true and false, it is sometimes convenient to think of them as on (true) and off (false), or yes (true) and no (false).true converts to the number 1 and false converts to the number 0. If a boolean value is used in a string context, true converts to the string "true" and false converts to the string "false".true unless the number is 0 or NaN, which are converted to false. If a string is used where a boolean value is expected, it is converted to true except for the empty string, which is converted to false. null and the undefined value convert to false, and any non-null object, array, or function converts to true.Math.sin( ) function that computes the sine of an angle.function square(x) // The function is named square. It expects one argument, x.
{ // The body of the function begins here.
return x*x; // The function squares its argument and returns that value.
} // The function ends here.y = Math.sin(x); y = square(x); d = compute_distance(x1, y1, z1, x2, y2, z2); move( );
image has properties named width and height, you can refer to those properties like this:image.width image.height
document.myform.button
button property of an object
that is itself stored in the myform property of an object named document.. syntax to extract the function value from the object and then use the ( ) syntax to invoke that function. For example, to invoke the write( ) method of an object named document, you can use code like this:document.write("this is a test");image object mentioned previously with code like this:image["width"] image["height"]
var o = new Object( );
var now = new Date( );
var pattern = new RegExp("\\sjava\\s", "i");a and i is a nonnegative integer, a[i] is an element of the array. Array indexes begin with zero; thus, a[2] refers to the third element of the array a.document.images[1].width
width property of an object stored in the second element of an array stored in the images property of the document object.Array( ) constructor function. Once created, any number of indexed elements can easily be assigned to the array:var a = new Array( );
a[0] = 1.2;
a[1] = "JavaScript";
a[2] = true;
a[3] = { x:1, y:3 };Array( ) constructor. Thus, the previous array creation and initialization code can also be written:var a = new Array(1.2, "JavaScript", true, { x:1, y:3 });Array( ) constructor, it specifies the length of the array. Thus:var a = new Array(10);
null is a special value that indicates no value. null is usually considered a special value of object type—a value that represents no object. null is a unique value, distinct from all other values. When a variable holds the value null, you know that it does not contain a valid object, array, number, string, or boolean value.
null is used in a Boolean context, it converts to false. When used in a numeric context, it converts to 0. And when used in a string context, it converts to "null".undefined value. undefined is returned when you use either a variable that has been declared but never had a value assigned to it or an object property that does not exist. Note that this special undefined value is not the same as null.null and the undefined value are distinct, the == equality operator considers them equal to one another. Consider the following:my.prop == null
true if either the my.prop property does not exist or it does exist but contains the value null. Since both null and the undefined value indicate an absence of value, this equality is often what we want. However, if you truly must distinguish between a null value and an undefined value, use the === identity operator or the typeof operator (see for details).null, undefined is not a reserved word in JavaScript. The ECMAScript v3 standard specifies that there is always a global variable named undefined whose initial value is the undefined value. Thus, in a conforming implementation, you can treat undefined as a keyword, as long as you don't assign a value to the variable.undefined variable, you can simply declare your own:var undefined;
undefined value. The void operator (see ) provides another way to obtain the undefined value.undefined value is used in a Boolean context, it converts to false. When used in a numeric context, it converts to NaN. And when used in a string context, it converts to "undefined".new operator and the Date( ) constructor (the new operator is introduced in , and you'll learn more about object creation in ):var now = new Date( ); // Create an object holding the current date and time. // Create a Date object representing Christmas. // Note that months are zero-based, so December is month 11! var xmas = new Date(2006, 11, 25);
xmas.setFullYear(xmas.getFullYear( ) + 1); // Change the date to next Christmas.
var weekday = xmas.getDay( ); // It falls on a Tuesday in 2007.
document.write("Today is: " + now.toLocaleString( )); // Current date/time.RegExp( ) constructor. Like the Date object, the RegExp object is not one of the fundamental datatypes of JavaScript; it is simply a specialized kind of object provided by all conforming JavaScript implementations./^HTML/ /[1-9][0-9]*/ /\bjavascript\b/i