Special tags and event handlers distinguish JavaScript from the document layout language.
As previously noted, JavaScript statements may exist just about anywhere within a document, and are interpreted as they are loaded.
Within the head or body of the document, client-side JavaScript statements must be enclosed within <script>....</script> tag pairs.
Put JavaScript statements in the head to ensure that they are available for all statements in the body:
<head>
<title>Introduction to JavaScript : Overview</title>
<script language="JavaScript">
function showLogo(btn) {
if (btn.value == "Amherst College") {
var winLogo = window.open(
"http://www.amherst.edu/about_amh/history/seal.html",
"College", "width=300,height=300,dependent")
winLogo.focus()
}
}
</script>
</head>
Put JavaScript statements in the body to ensure that they are executed in a particular sequence relative to the layout language:
<body>
....
Amherst College was founded
<script language="JavaScript">
var now = new Date var thisYear = now.getYear()
if (thisYear < 1900) {
thisYear += 1900
} document.write(thisYear - 1821)
</script>
years ago.
....
</body>
Amherst College was founded
years ago.
Event handlers in HTML look like ordinary tag/attribute pairs, and respond to user interaction with document elements such as buttons.
A useful approach for organizing JavaScript code is to store commonly accessed snipits into JavaScript source files (with a .js extension) that can be loaded into a document with a statement such as the following:
You may have noticed that a user can turn off JavaScript in browsers that understand it:
Since you can't control a user's settings, if they have turned JavaScript off you may wish to do some things differently or warn the user of limited functionality.
By putting document language between <noscript>....</noscript> tag pairs, a knowledgeable browser will only display them when JavaScript is turned off:
<script language="JavaScript">
document.write("Please turn off JavaScript to
demonstrate this feature.")
</script>
<noscript>
Please turn on JavaScript <i>for the rest of this presentation</i>. </noscript>
Navigator and Internet Explorer handle JavaScript errors differently:
As can be seen in the dialog above, Internet Explorer will "pop up" errors if you tell it to do so with the "Show scripting error alerts" checkbox.
Navigator instead provides a more general facility; errors will (sometimes) be announced at the bottom of the window, and by typing
javascript:
in Navigator's location field, a JavaScript Console will open displaying information about the error.
The console can also be used to type in one-line JavaScript statements to test them.
document.write("This statement is designed to generate an error"
Comments
JavaScript provides for comments, but using them has its disadvantages.
The simplest statements in JavaScript are comments, code that isn't executed but helps to explain code that is.
Comments are like those in C++ or Java:
/* Anything from slash-star to star-slash, even spanning multiple lines,
is a comment. */
// Anything from slash-slash to the end of a line is a comment.
Generally speaking it's a good idea to liberally comment your code so others can determine your intent.
With JavaScript, however, because your code must be downloaded over the Internet, don't overdo it!
Note that you can intermix JavaScript and HTML comments without confusing them.
This can be useful for really old browsers (e.g. Netscape Navigator 1.x) that don't recognize <script>...</script> pairs and try to execute what falls inbetween:
Note that JavaScript knows enough to ignore the beginning of the HTML comment tag up to end of the line, but needs to be told to ignore the closing tag.
You can also use JavaScript comments to inform the old-browser user of their impoverished state:
<script language="JavaScript">
// You need to have a JavaScript-capable browser to view this page.
</script>
// You need to have a JavaScript-capable browser to view this page.
Data Types
JavaScript has a small but full-featured set of data types.
The building blocks of JavaScript statements will be data such as numbers and strings.
JavaScript has relatively few data types, represented here by "literal" representations:
JavaScript Data Types
Data Type
Definition
Literal Examples
Null
A valueless, unitless, dimensionless quantity.
null
Boolean
A logical value.
true
false
Number
Either an integer or a floating-point number,
with C/C++/Java notations for scientific decimals,
octal integers, and hexadecimal integers.
5280
3.14159
2.54e-2
01224
0x14A0
String
A series of characters of arbitrary length, delimited by a matching pair of single or double quotation marks.
"Amherst College"
'The "real" thing'
JavaScript automatically converts between integer and floating-point decimal numbers as necessary for its internal storage.
This is very convenient for most purposes.
This is only an issue if you want to do integer math or if rounding errors are important.
Hexadecimal integer literals can have their X and A-F characters in either upper or lower case.
For string literals, JavaScript uses the HTML-standard ISO 8859-1 (Latin-1) character set, whose first 128 characters are the same as the ASCII character set.
In addition to "ordinary" characters, string literals can also include a number of special characters, delimited by a backslash, for example:
JavaScript String Special Character Codes
Definition
Character Code
Numeric Code
Examples
Horizontal Tab
\t
\011
\x09
document.write("field 1\tfield 2")
Newline
(Linefeed)
\n
\012
\x0A
document.write("line 1\nline 2")
Double Quote
\"
\042
\x22
document.write("A \"strange brew\".")
Single Quote
(Apostrophe)
\'
\047
\x27
document.write('It can\'t be done!')
Backslash
\\
\134
\x5C
document.write("The tab character: \\t")
Any Latin-1 character
Octal
representation, nnn <= 377
\nnn
document.write(
"\2512002 Amherst College")
Any Latin-1 character
Hexadecimal representation, nn <= FF
\xnn
document.write(
"\xA92002 Amherst College")
Any Unicode character
Hexadecimal representation, nnnn <= FFFF
\unnnn
document.write("\u03B1 \u03B2 \u03B3")
Because HTML uses the double quote for tag values, you'll mostly want to use single quotes to delimit your string literals, and a numeric code for a double quote in a string if it also falls within a tag.
Variables and Assignments
JavaScript variables are very flexible, and can represent all of the above data types.
JavaScript, of course, has variables that can hold any of the above data types.
Variables have names that can be any series of letters, numbers, and the underscore (except the first cannot be a number):
thisIsAVariable
this_is_a_variable_2
Variable names are case sensitive.
JavaScript variables will "spring into existence" the first time they are used in a statement.
Alternatively they can be declared in advance with the var keyword:
var someVariable, anotherVariable
Declaring a variable with the var keyword is recommended, as it helps identify the first use of a variable.
Depending on how they are declared, there are some differences in scope (areas of existence) that will be discussed later in the context of functions.
Whether the var keyword is used or not, variables will have an initial value of null, unless an assignment of some sort takes place.
Most commonly, variables will be initialized with a simple assignment operation:
pieceOfPi = 3.14 // a number
A1School = "Amherst College" // a string
Assignments can be combined with declarations for a compact, easily identifiable initialization:
var someVariable = aPreviousValue, anotherVariable = -7.2
As befits the simplicity of a scripting language, JavaScript variables are dynamically typed, i.e. they automatically take on the type of the data that is assigned to them:
pieceOfPi = "Apple" // now a string
A1School = true // now a boolean
Because of JavaScript's loose typing, it's important to be able to determine at any time what type of data a variable holds.
The typeof unary operator will take any variable (or literal) as an argument and output a string describing its contents: