Cover | Table of Contents
/* and
*/ is a comment, and is ignored by JavaScript.
Also, any text between // and the end of the
current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment. /* * This is a multi-line, C-style comment. * Here is the second line. */ /* Another comment. */ // This too.
_ and
$ characters. The first character of an identifier
must not be a digit, however. The following are legal identifiers:
i my_variable_name v13 $str
/* and
*/ is a comment, and is ignored by JavaScript.
Also, any text between // and the end of the
current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment. /* * This is a multi-line, C-style comment. * Here is the second line. */ /* Another comment. */ // This too.
_ and
$ characters. The first character of an identifier
must not be a digit, however. The following are legal identifiers:
i my_variable_name v13 $str
break do if switch typeof case else in this var catch false instanceof throw void continue finally new true while default for null try with delete function return
var statement:
var i = 1+2+3; var x = 3, message = 'hello world';
1 3.14 0001 6.02e23
0x:
0xFF // The number 255 in hexadecimal
NaN, which
represents a value that is not-a-number. Use the global function
isNaN( ) to test for this value.
Math.sin(
), Math.pow( ), and
Math.random( ).
true and
false. These values represent truth or falsehood,
on or off, yes or no, or anything else that can be represented with
one bit of information.
'testing' "3.14" 'name="myform"' "Wouldn't you prefer O'Reilly's book?"
\) appears within a
string literal, it changes, or escapes, the meaning of the character
that follows it. The following table lists these special escape
sequences:
|
Escape
|
Represents
|
|---|---|
\b |
Backspace |
1+2 total/n sum(o.x, a[3])++
|
P
|
A
|
Operator
|
Operation performed
|
|---|---|---|---|
|
15
|
L
|
.
|
Access an object property
|
|
L
|
[ ] |
Access an array element
| |
|
L
|
( ) |
Invoke a function
| |
|
R
|
new |
Create new object
| |
|
14
|
R
|
++ |
Pre-or-post increment (unary)
|
|
R
|
-- |
Pre-or-post decrement (unary)
| |
|
R
|
- |
Unary minus (negation)
| |
|
R
|
+ |
Unary plus (no-op)
| |
|
R
|
~ |
Bitwise complement (unary)
| |
|
R
|
! |
Logical complement (unary)
| |
|
R
|
delete |
Undefine a property (unary) (JS 1.2)
| |
|
R
|
typeof |
Return data type (unary) (JS 1.1)
| |
|
R
|
void |
Return undefined value (unary) (JS 1.1)
| |
|
13
|
L
|
*, /, % |
Multiplication, division, remainder
|
|
12
|
L
|
+, - |
Add, subtract
|
|
L
|
+ |
Concatenate strings
| |
|
11
|
L
|
<< |
Integer shift left
|
|
L
|
>> |
Shift right, sign-extension
| |
|
L
|
>>> |
Shift right, zero extension
| |
|
10
|
L
|
<, <= |
Less than, less than or equal
|
|
L
|
>, >= |
Greater than, greater than or equal
| |
|
L
|
instanceof |
Check object type (JS 1.5)
| |
|
L
|
in |
Check whether property exists (JS 1.5)
| |
|
9
|
L
|
== |
Test for equality
|
|
L
|
!= |
Test for inequality
| |
|
L
|
=== |
Test for identity (JS 1.3)
| |
|
L
|
!== |
Test for non-identity (JS 1.3)
| |
|
8
|
L
|
& |
Integer bitwise AND
|
|
7
|
L
|
^ |
Integer bitwise XOR
|
|
6
|
L
|
| |
Integer bitwise OR
|
|
5
|
L
|
&& |
Logical AND
|
|
4
|
L
|
|| |
Logical OR
|
|
3
|
R
|
?: |
Conditional operator (3 operands)
|
|
2
|
R
|
= |
Assignment
|
|
R
|
*=, +=, -=,
etc.
|
Assignment with operation
| |
|
1
|
L
|
,
|
Multiple evaluation |
s = "hello world"; x = Math.sqrt(4); x++;
while loop consists of a single
statement. If you want the loop to execute more than one statement,
use a compound statement. This is a common technique with
if, for, and other statements
described later.
break and continue statements:
label : statement
breakbreak statement terminates execution of the
innermost enclosing loop, or, in JavaScript 1.2 and later, the named
loop:
break ;
break label ;
casecase is not a true statement. Instead it is a
keyword used to label statements within a JavaScript 1.2 or later
switch statement:
case constant-expression : statements [ break ; ]
switch statement, a
group of statements labeled by case should usually
end with a break statement.
continuecontinue statement restarts the innermost
enclosing loop, or, in JavaScript 1.2 and later, restarts the named
loop:
continue ;
continue label ;
defaultcase, default is not a
true statement, but instead a label that may appear within a
JavaScript 1.2 or later switch statement:
default:
statements
[ break ; ]
do/whiledo/while loop repeatedly executes a statement
while an expression is true. It is like the
while loop, except that the loop condition appears
(and is tested) at the bottom of the loop. This means that the body
of the loop is executed at least once:
new operator and it uses the
this keyword to refer to and initialize the newly
created object. For example, here is a constructor to create objects
of a new class named Point.
function Point(x,y) { // Constructor for Point
this.x = x; // Initialize X coordinate
this.y = y; // Initialize Y coordinate
}
prototype. This property refers to a special
prototype object for the class of objects created by the constructor.
Any properties you define on this prototype object are inherited by
all objects created with the constructor function. The prototype
object is commonly used to make methods available to all instances of
a class. Defining a method named toString allows
instances of your class to be converted to strings. For example:
// Define function literals and assign them
// to properties of the prototype object.
Point.prototype.distanceTo = function(that) {
var dx = this.x - that.x;
var dy = this.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
Point.prototype.toString = function () {
return '(' + this.x + ',' + this.y + ')';
}
// Define a commonly used Point constant Point.ORIGIN = new Point(0,0);
// Call constructor to create a new Point object var p = new Point(3,4); // Invoke a method of the object, using a static // property as the argument. var d = p.distanceTo(Point.ORIGIN); // Adding the object to a string implicitly // invokes toString(). var msg = "Distance to " + p + " is " + d;
/)
characters, optionally followed by one or more of the modifier
characters g (global search), i
(case-insensitive search), and m (multi-line mode;
a JavaScript 1.5 feature). In addition to this literal syntax,
RegExp objects can be created with the
RegExp( ) constructor, which accepts the pattern
and modifier characters as string arguments, without the slash
characters.
\) that have special meanings. The simplest of
these escape sequences provide alternative ways of representing
literal characters:
|
Character
|
Meaning
|
|---|---|
\n, \r, \t |
Match literal newline, carriage return, tab
|
\\, \/,
\*,\+, \?,
etc.
|
Match a punctuation character literally, ignoring or escaping its
special meaning
|
\xnn |
The character with hexadecimal encoding nn.
|
\uxxxx |
The Unicode character with hexadecimal encoding
xxxx.
|
|
Character
|
Meaning
|
|---|---|
[...] |
Match any one character between brackets
|
[^...] |
Match any one character not between brackets
|
|
.
|
Match any character other than newline
|
\w, \W |
Match any word/non-word character
|
\s, \S |
Match any whitespace/non-whitespace |
switch statement, regular
expressions, and a number of other features. Almost compliant with
ECMA v1, but has some incompatibilities. Implemented by Netscape 4.
switch statement or regular
expression support. Conformant implementations are JavaScript 1.3 and
JScript 3.0.
<script> tag and a
</script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
src
attribute of the <script> tag to specify the
URL of an external script to be loaded and executed. Files of
JavaScript code typically have a .js extension.
Note that the </script> tag is still
required when this attribute is used:
<script src="library.js"></script>
language attribute to
specify what language a script is written in. This attribute defaults
to "JavaScript"
in all browsers, so you do not usually have to set it. You can also
use attribute values such as
"JavaScript1.3" and
"JavaScript1.5" to specify the
version of JavaScript your code uses. Browsers that do not support
the specified version of the language simply ignore the script.
<script> tag and a
</script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
src
attribute of the <script> tag to specify the
URL of an external script to be loaded and executed. Files of
JavaScript code typically have a .js extension.
Note that the </script> tag is still
required when this attribute is used:
<script src="library.js"></script>
language attribute to
specify what language a script is written in. This attribute defaults
to "JavaScript"
in all browsers, so you do not usually have to set it. You can also
use attribute values such as
"JavaScript1.3" and
"JavaScript1.5" to specify the
version of JavaScript your code uses. Browsers that do not support
the specified version of the language simply ignore the script.
language
attribute of the <script> tag. Instead, the
official way to specify the language a script is written in is with
the type attribute. For JavaScript, set this
attribute to the MIME type
"text/javascript":
<script src="functions.js"
language="JavaScript1.5"
type="text/javascript"></script>
onclick attribute specifies an event handler that
displays an alert (a dialog box) when the user clicks the button:
<input type="button" value="Press Me"
onclick="alert('Hello World!');">
window and refers back to the Window object
itself:
window // The global Window object window.document // The document property of the window document // Or omit the object prefix
document, which refers to the Document object that
describes the document displayed by the browser window. The Document
object is described in a section of its own following these
window-related subsections.
alert( ) lets you display a message to the user,
confirm( ) lets you ask the user a yes-or-no
question, and prompt( ) lets you ask the user to
enter a single line of text. For example:
alert("Welcome to my home page!");
if (confirm("Do you want to play?")) {
var n = prompt("Enter your name");
}
status property. The text you set on this
property appears in the status area until you or the browser
overwrites it with some new value. You can also set
defaultStatus to specify text to appear by default
when the browser is not displaying any other information in the
status line. Here is an HTML hyperlink that uses JavaScript in an
event handler to set the status text to something other than the URL
of the link:
document property that
refers to a Document object. The Document object is arguably more
important than the Window object itself: while the Window represents
the browser window, the Document object represents the HTML document
that is displayed in that window. The Document object has various
properties that refer to other objects which allow access to and
modification of document content. The way that document content is
accessed and modified is called the document object model, or DOM,
and there are several DOMs in existence:
title,
URL, and lastModified provide
information about the document as a whole. See the reference section
for further details on these and all Document properties and methods.
Other properties are arrays that refer to specific types of document
content:
forms[ ]images[ ]applets[ ]links[ ]anchors[ ]name attribute of the HTML
<a> tag) in the document.
document.forms[0], and the third image is
document.images[2]. Another way to refer to
document forms, images, and applets is to give them names with the
HTML name attribute:
<form name="address">...</form>
document.forms["address"] // A named form document.address // The same thing
elements[ ] array that contains objects
representing the elements of the form, in the order they appear in
the form. See Input, Select, and Textarea in the reference section
for details on these form elements.
elements[ ] array of a Form works much like
the forms[ ] array of a Document: it holds form
elements in the order they appear in the form, but it also allows
them to be referred to by name. Consider this HTML excerpt:
forms[ ], images[ ], and other
array properties of the Document object, it defines methods that
allow scripts to access and manipulate any document element, not just
special-purpose elements like forms and images.
Return to JavaScript Pocket Reference