100% found this document useful (1 vote)
428 views2,229 pages

Sams - Pure JavaScript, Second Edition

Sams - Pure JavaScript, Second Edition

Uploaded by

Frantsisko
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
428 views2,229 pages

Sams - Pure JavaScript, Second Edition

Sams - Pure JavaScript, Second Edition

Uploaded by

Frantsisko
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2229

00 0672321419 FM 7/24/01 11:46 AM Page i

PURE
JavaScript
Second Edition

R. Allen Wyke
Jason D. Gilliam
Charlton Ting
Sean Michaels

201 West 103rd Street, Indianapolis, Indiana 46290


00 0672321419 FM 7/24/01 11:46 AM Page ii

Pure JavaScript, Second Edition ACQUISITIONS EDITOR


Shelley Johnston
Copyright  2002 by Sams Publishing Markanday

All rights reserved. No part of this book shall be reproduced, stored in a DEVELOPMENT EDITOR
retrieval system, or transmitted by any means, electronic, mechanical, Jonathan Steever
photocopying, recording, or otherwise, without written permission from
MANAGING EDITOR
the publisher. No patent liability is assumed with respect to the use of the
Charlotte Clapp
information contained herein. Although every precaution has been taken in
the preparation of this book, the publisher and author assume no responsi- PROJECT EDITOR
bility for errors or omissions. Nor is any liability assumed for damages Elizabeth Finney
resulting from the use of the information contained herein.
COPY EDITOR
International Standard Book Number: 0-672-32141-6 Rhonda Tinch-Mize
Library of Congress Catalog Card Number: 00-111512 INDEXER
Printed in the United States of America Sandra Henselmeier
First Printing: August 2001 PROOFREADERS
04 03 02 01 4 3 2 1 Antonio Reitz
Rebecca Martin
Trademarks Debra Sexton
All terms mentioned in this book that are known to be trademarks or ser- TECHNICAL EDITOR
vice marks have been appropriately capitalized. Sams Publishing cannot Andrew Watt
attest to the accuracy of this information. Use of a term in this book
should not be regarded as affecting the validity of any trademark or ser- TEAM COORDINATOR
vice mark. Amy Patton

Warning and Disclaimer MEDIA DEVELOPER


Dan Scherf
Every effort has been made to make this book as complete and as accurate
as possible, but no warranty or fitness is implied. The information pro- INTERIOR DESIGNER
vided is on an “as is” basis. The author(s) and the publisher shall have Karen Ruggles
neither liability nor responsibility to any person or entity with respect to
COVER DESIGNER
any loss or damages arising from the information contained in this book
Aren Howell
or from the use of the CD or programs accompanying it.
PAGE LAYOUT
Ayanna Lacey
00 0672321419 FM 7/24/01 11:46 AM Page iii

Overview
Introduction 1

PART I A PROGRAMMER'S OVERVIEW OF JAVASCRIPT


1 What Is JavaScript to a Programmer? 5
2 Details of the Language 31

PART II PROGRAMMING IN JAVASCRIPT


3 Programming Techniques 85
4 Client-Side Scripting 107
5 JavaScript on the Server-Side 157
6 Windows Scripting 179

PART III JAVASCRIPT REFERENCE


7 Core Language 193
8 Client-Side 563
9 Server-Side 1175
INDEX CD:2025

CD-ROM
10 DOM Core CD:1403
11 DOM HTML CD:1479
12 DOM Events CD:1731
13 DOM CSS CD:1767
14 JScript RunTime CD:1823
15 Windows Script Host CD:1927
00 0672321419 FM 7/24/01 11:46 AM Page iv

Contents
INTRODUCTION 1

PART I A PROGRAMMER'S OVERVIEW OF JAVASCRIPT


1 WHAT IS JAVASCRIPT TO A PROGRAMMER? 5
Welcome to JavaScript ............................................................................6
Object-Based Technology........................................................................7
Object-Oriented Programming ................................................................8
Object Orientation of JavaScript ......................................................10
Object Access ..................................................................................16
Modular Programming ....................................................................17
Security ..................................................................................................18
What Security Measures Are in Place? ............................................18
Data Tainting ....................................................................................20
Signed Scripts ..................................................................................21
Advantages of JavaScript ......................................................................23
Platform Independence ....................................................................24
Client-Side and Server-Side Versatility............................................24
When to Use JavaScript ........................................................................25
Web Page Enhancements..................................................................26
Interactive E-Mail ............................................................................26
Web-Based Applications ..................................................................27
Windows Scripting ..........................................................................27
JavaScript Resources ............................................................................28
General Information ........................................................................28
Reference ..........................................................................................29
Newsgroups ......................................................................................30
Moving On ............................................................................................30

2 DETAILS OF THE LANGUAGE ............................................................31


Things to Know about JavaScript Syntax..............................................31
The Semicolon..................................................................................31
Using the <script> Tag....................................................................32
Comments ........................................................................................33
Data Types and Variables ......................................................................33
Numbers............................................................................................34
Strings ..............................................................................................35
Other Data Types ..............................................................................36
What to Know About Variables........................................................36
Arrays ..............................................................................................39
Operators................................................................................................45
00 0672321419 FM 7/24/01 11:46 AM Page v

Arithmetic ........................................................................................45
String ................................................................................................49
Assignment ......................................................................................50
Logical ..............................................................................................54
Comparison ......................................................................................55
Conditional ......................................................................................58
Bitwise ..............................................................................................59
Precedence ........................................................................................61
Loops and Conditionals ........................................................................62
Conditionals......................................................................................62
Loops ................................................................................................65
Functions................................................................................................76
Syntax ..............................................................................................77
Call By Value Versus Call By Reference ........................................77
Returning Values ..............................................................................79
Functions as Objects ........................................................................80
Moving On ............................................................................................81

PART II PROGRAMMING IN JAVASCRIPT


3 PROGRAMMING TECHNIQUES 85
Pattern Matching....................................................................................85
Defining the RegExp Object ..............................................................86
Defining Patterns ..............................................................................86
Testing for Pattern Matches..............................................................88
Events and Event Handlers....................................................................89
Events ..............................................................................................90
Event Handlers ................................................................................92
Timers ..............................................................................................95
Exceptions..............................................................................................97
throw ................................................................................................97
try...catch......................................................................................97
Runtime Errors ................................................................................99
finally ..........................................................................................100
Debugging............................................................................................101
Microsoft Script Debugger ............................................................102
The alert() Method ......................................................................103
Moving On ..........................................................................................106

4 CLIENT-SIDE SCRIPTING 107


Supporting Browsers and Their Issues ................................................108
Netscape Navigator ........................................................................110
Internet Explorer ............................................................................111
Opera ..............................................................................................114
HotJava ..........................................................................................115
00 0672321419 FM 7/24/01 11:46 AM Page vi

vi

Extended Browser Functionality ........................................................115


Built-In Functions for Control........................................................116
LiveConnect....................................................................................120
Form Processing ..................................................................................124
The Forms Array ............................................................................125
Accessing and Writing Information ..............................................128
Form Example ................................................................................131
Cookie Handling ..................................................................................136
Reading Cookies ............................................................................138
Writing Cookies..............................................................................139
Windows in Action ..............................................................................139
The Parent/Child Relationship ......................................................139
Creating Windows ..........................................................................141
Limitations......................................................................................142
Window Example ..........................................................................142
Dynamic Documents............................................................................145
The Old Way ..................................................................................146
The New Way ................................................................................148
Cross Browser DHTML ................................................................151
XML-Based User Interface Language (XUL) ....................................154
What Is XUL? ................................................................................154
File Structure and Syntax ..............................................................155
XUL and JavaScript ......................................................................155
XUL Example ................................................................................155
Moving On ..........................................................................................156

5 JAVASCRIPT ON THE SERVER-SIDE 157


How Does Server-Side Differ from
Client-Side? ......................................................................................158
Server-Side Environments ..............................................................158
Programming Differences ..............................................................158
Netscape’s Server-Side JavaScript ......................................................159
Server Support ................................................................................160
Compiling Your Scripts ..................................................................160
The Server Side JavaScript Application Manager..........................161
Microsoft’s ASP Environment ............................................................167
Server Support ................................................................................168
Using the JScript Language............................................................168
Checking Your Environment ..........................................................169
Uses of Server-Side JavaScript............................................................169
Within Enterprise Server ................................................................170
Within IIS ......................................................................................176
Moving On ..........................................................................................178
00 0672321419 FM 7/24/01 11:46 AM Page vii

vii

6 WINDOWS SCRIPTING 179


Windows Script Host ..........................................................................179
Architecture ....................................................................................180
Object Model ..................................................................................181
Benefits and Limitations ................................................................182
Windows Script Components ..............................................................182
Objects ............................................................................................182
Methods of Executing Scripts ........................................................184
Remote Scripting ................................................................................187
How to Use Remote Scripting........................................................187
Remote Scripting Example ............................................................188
Moving On ..........................................................................................189

PART III JAVASCRIPT REFERENCE


7 CORE LANGUAGE 193
@_alpha..........................................................................................193
@_jscript ........................................................................................194
@_jscript_build ..............................................................................194
@_jscript_version ..........................................................................195
@_mac............................................................................................196
@_mc680x0....................................................................................197
@_PowerPC ..................................................................................197
@_win16 ........................................................................................198
@_win32 ........................................................................................198
@_x86 ............................................................................................199
@cc_on ..........................................................................................200
@if ..................................................................................................200
@set ................................................................................................201
- (Subtraction) ................................................................................202
- (Unary Negation) ........................................................................203
-- (Decrement) ................................................................................204
! (Logical NOT)..............................................................................205
!= (Not Equal) ................................................................................206
!== (Non-Identity) ..........................................................................207
% (Modulus) ..................................................................................208
%= (Modulus Assignment) ............................................................209
& (Bitwise AND)............................................................................210
&& (Logical AND) ........................................................................211
&= (Bitwise AND Assignment) ....................................................212
* (Multiplication)............................................................................213
*= (Multiplication Assignment) ....................................................213
, (Comma) ......................................................................................214
/ (Division)......................................................................................215
/* / (Multi-line Comment) ..............................................................216
00 0672321419 FM 7/24/01 11:46 AM Page viii

viii

// (Comment) ..................................................................................216
/= (Division Assignment) ..............................................................217
?: (Conditional) ..............................................................................218
^ (Bitwise Exclusive OR) ..............................................................219
^= (Bitwise Exclusive OR Assignment) ........................................220
| (Bitwise OR) ................................................................................221
|| (Logical OR) ................................................................................222
|= (Bitwise OR Assignment) ..........................................................223
~ (Bitwise NOT) ............................................................................224
+ (Addition) ....................................................................................225
++ (Increment)................................................................................226
+= (Addition Assignment)..............................................................227
< (Less Than)..................................................................................228
<< (Shift Left) ................................................................................229
<<= (Shift Left Assignment) ..........................................................230
<= (Less Than or Equal) ................................................................231
= (Assignment) ..............................................................................232
-= (Subtraction Assignment) ..........................................................232
== (Equal) ......................................................................................233
=== (Identity) ................................................................................234
> (Greater Than) ............................................................................235
>= (Greater Than or Equal)............................................................236
>> (Shift Right with Sign) ............................................................237
>>= (Shift Right with Sign Assignment) ......................................238
>>> (Shift Right Zero Fill) ............................................................239
>>>= (Shift Right Zero Fill Assignment) ......................................240
abstract............................................................................................241
ActiveXObject ................................................................................241
Arguments ......................................................................................243
Arguments.callee ............................................................................244
Arguments.caller ............................................................................246
Arguments.length ..........................................................................247
Array ..............................................................................................249
Array.concat( ) ................................................................................251
Array.constructor ............................................................................253
Array.index ....................................................................................253
Array.input......................................................................................254
Array.join() ....................................................................................254
Array.lastIndex ..............................................................................255
Array.length ....................................................................................256
Array.pop() ....................................................................................257
Array.prototype ..............................................................................258
Array.push()....................................................................................259
Array.reverse() ................................................................................260
Array.shift() ....................................................................................261
00 0672321419 FM 7/24/01 11:46 AM Page ix

ix

Array.slice() ....................................................................................262
Array.sort() ....................................................................................263
Array.splice() ..................................................................................265
Array.toSource() ............................................................................267
Array.toString() ..............................................................................268
Array.unshift() ................................................................................269
Array.unwatch() ..............................................................................270
Array.valueOf() ..............................................................................271
Array.watch() ..................................................................................271
Automation ....................................................................................272
boolean............................................................................................272
Boolean ..........................................................................................273
Boolean.constructor........................................................................275
Boolean.prototype ..........................................................................275
Boolean.toSource() ........................................................................276
Boolean.toString() ..........................................................................277
Boolean.unwatch()..........................................................................278
Boolean.valueOf() ..........................................................................279
Boolean.watch()..............................................................................279
break ..............................................................................................280
byte ................................................................................................281
case ................................................................................................282
char ................................................................................................282
class ................................................................................................282
const................................................................................................283
continue ..........................................................................................283
Date ................................................................................................285
Date.constructor..............................................................................289
Date.getDate() ................................................................................289
Date.getDay() ................................................................................290
Date.getFullYear() ..........................................................................291
Date.getHours() ..............................................................................292
Date.getMilliseconds() ..................................................................292
Date.getMinutes() ..........................................................................293
Date.getMonth() ............................................................................294
Date.getSeconds() ..........................................................................295
Date.getTime()................................................................................296
Date.getTimezoneOffset() ..............................................................297
Date.getUTCDate() ........................................................................298
Date.getUTCDay() ........................................................................298
Date.getUTCFullYear() ..................................................................300
Date.getUTCHours() ......................................................................300
Date.getUTCMilliseconds() ..........................................................301
Date.getUTCMinutes() ..................................................................301
Date.getUTCMonth() ....................................................................302
00 0672321419 FM 7/24/01 11:46 AM Page x

Date.getUTCSeconds() ..................................................................304
Date.getVarDate() ..........................................................................304
Date.getYear() ................................................................................305
Date.parse() ....................................................................................306
Date.prototype ................................................................................307
Date.setDate() ................................................................................308
Date.setFullYear() ..........................................................................309
Date.setHours() ..............................................................................310
Date.setMilliseconds()....................................................................310
Date.setMinutes() ..........................................................................311
Date.setMonth()..............................................................................312
Date.setSeconds() ..........................................................................313
Date.setTime() ................................................................................314
Date.setUTCDate() ........................................................................314
Date.setUTCFullYear() ..................................................................315
Date.setUTCHours() ......................................................................316
Date.setUTCMilliseconds()............................................................317
Date.setUTCMinutes() ..................................................................318
Date.setUTCMonth()......................................................................318
Date.setUTCSeconds() ..................................................................319
Date.setYear() ................................................................................320
Date.toGMTString() ......................................................................321
Date.toLocaleString() ....................................................................322
Date.toSource() ..............................................................................322
Date.toString() ................................................................................323
Date.toUTCString() ........................................................................324
Date.unwatch() ..............................................................................325
Date.UTC() ....................................................................................326
Date.valueOf() ................................................................................327
Date.watch ......................................................................................328
debugger ........................................................................................328
decodeURI() ..................................................................................329
decodeURIComponent() ................................................................330
default ............................................................................................331
delete ..............................................................................................331
do ....................................................................................................332
do...while ........................................................................................332
double ............................................................................................333
else ..................................................................................................334
encodeURI() ..................................................................................334
encodeURIComponent() ................................................................335
enum ..............................................................................................336
Enumerator ....................................................................................336
Enumerator.atEnd() ........................................................................337
Enumerator.item() ..........................................................................338
00 0672321419 FM 7/24/01 11:46 AM Page xi

xi

Enumerator.moveFirst()..................................................................339
Enumerator.moveNext() ................................................................340
Error................................................................................................341
Error.description ............................................................................342
Error.message ................................................................................343
Error.name ......................................................................................343
Error.number ..................................................................................344
escape() ..........................................................................................345
eval() ..............................................................................................346
export ..............................................................................................347
extends ............................................................................................348
false ................................................................................................349
final ................................................................................................349
float ................................................................................................349
for....................................................................................................350
for...in..............................................................................................351
function ..........................................................................................352
Function() ......................................................................................352
Function.apply() ............................................................................353
Function.arguments ........................................................................354
Function.arity..................................................................................355
Function.call() ................................................................................356
Function.callee................................................................................357
Function.caller ................................................................................358
Function.constructor ......................................................................359
Function.length ..............................................................................360
Function.prototype..........................................................................360
Function.toSource() ........................................................................361
Function.toString() ........................................................................362
Function.valueOf()..........................................................................363
GetObject........................................................................................364
Global ............................................................................................365
Global.decodeURI() ......................................................................366
Global.decodeURIComponent() ....................................................367
Global.encodeURI() ......................................................................368
Global.encodeURIComponent() ....................................................369
Global.escape() ..............................................................................370
Global.eval() ..................................................................................371
Global.Infinity ................................................................................373
Global.isFinite()..............................................................................374
Global.isNaN() ..............................................................................375
Global.NaN ....................................................................................376
Global.Number() ............................................................................376
Global.parseFloat() ........................................................................377
Global.parseInt() ............................................................................378
00 0672321419 FM 7/24/01 11:46 AM Page xii

xii

Global.String()................................................................................379
Global.unescape() ..........................................................................380
Global.undefined ............................................................................380
goto ................................................................................................381
if......................................................................................................381
if...else ............................................................................................382
implements......................................................................................383
import..............................................................................................383
in ....................................................................................................384
Infinity ............................................................................................385
instanceof........................................................................................386
int ....................................................................................................387
interface ..........................................................................................387
isFinite()..........................................................................................387
isNaN() ..........................................................................................388
java..................................................................................................389
javaArray ........................................................................................390
javaArray.length..............................................................................391
javaArray.toString ..........................................................................392
javaClass ........................................................................................392
javaObject ......................................................................................393
javaPackage ....................................................................................394
JSException ....................................................................................395
JSException.getWrappedException() ............................................396
JSObject..........................................................................................396
JSObject.call() ................................................................................398
JSObject.equals()............................................................................399
JSObject.eval()................................................................................400
JSObject.getMember()....................................................................401
JSObject.getSlot() ..........................................................................403
JSObject.getWindow()....................................................................403
JSObject.removeMember() ............................................................404
JSObject.setMember() ....................................................................405
JSObject.setSlot() ..........................................................................405
JSObject.toString() ........................................................................406
label ................................................................................................406
long ................................................................................................407
Math() ............................................................................................408
Math.abs() ......................................................................................409
Math.acos() ....................................................................................410
Math.asin()......................................................................................411
Math.atan() ....................................................................................412
Math.atan2() ..................................................................................413
Math.ceil() ......................................................................................414
Math.cos() ......................................................................................415
00 0672321419 FM 7/24/01 11:46 AM Page xiii

xiii

Math.E ............................................................................................416
Math.exp() ......................................................................................417
Math.floor() ....................................................................................418
Math.LN10 ....................................................................................419
Math.LN2 ......................................................................................420
Math.log() ......................................................................................420
Math.LOG10E ................................................................................421
Math.LOG2E ..................................................................................422
Math.max() ....................................................................................423
Math.min()......................................................................................424
Math.PI ..........................................................................................425
Math.pow() ....................................................................................426
Math.random()................................................................................427
Math.round() ..................................................................................428
Math.sin() ......................................................................................429
Math.sqrt() ......................................................................................430
Math.SQRT1_2 ..............................................................................431
Math.SQRT2 ..................................................................................432
Math.tan() ......................................................................................432
Math.toSource()..............................................................................433
Math.toString() ..............................................................................434
Math.unwatch() ..............................................................................435
Math.watch() ..................................................................................435
NaN ................................................................................................436
native ..............................................................................................436
netscape ..........................................................................................437
new..................................................................................................437
null ..................................................................................................438
Number() ........................................................................................438
Number() ........................................................................................439
Number.constructor ........................................................................440
Number.MAX_VALUE ..................................................................441
Number.MIN_VALUE ..................................................................442
Number.NaN ..................................................................................443
Number.NEGATIVE_INFINITY ..................................................443
Number.POSITIVE_INFINITY ....................................................444
Number.prototype ..........................................................................445
Number.toExponential() ................................................................446
Number.toFixed() ..........................................................................447
Number.toLocaleString()................................................................447
Number.toPrecision()......................................................................448
Number.toSource() ........................................................................448
Number.toString() ..........................................................................449
Number.unwatch() ..........................................................................449
Number.valueOf() ..........................................................................450
00 0672321419 FM 7/24/01 11:46 AM Page xiv

xiv

Number.watch() ..............................................................................451
Object() ..........................................................................................452
Object.constructor ..........................................................................453
Object.eval() ..................................................................................454
Object.prototype ............................................................................455
Object.toSource()............................................................................455
Object.toString() ............................................................................456
Object.unwatch() ............................................................................457
Object.valueOf() ............................................................................458
Object.watch() ................................................................................458
package ..........................................................................................459
Packages ........................................................................................460
Packages.className ......................................................................461
Packages.java..................................................................................461
Packages.netscape ..........................................................................462
Packages.sun ..................................................................................463
parseFloat() ....................................................................................464
parseInt() ........................................................................................465
private ............................................................................................465
protected ........................................................................................466
public ..............................................................................................466
RegExp() ........................................................................................466
RegExp,$* ......................................................................................469
RegExp.$& ....................................................................................470
RegExp,$_ ......................................................................................470
RegExp.$` ......................................................................................471
RegExp.$’ ......................................................................................472
RegExp.$+ ......................................................................................473
RegExp.$1,$2,..$9 ..........................................................................474
RegExp.constructor()......................................................................475
RegExp.compile() ..........................................................................476
RegExp.exec() ................................................................................477
RegExp.global ................................................................................478
RegExp.ignoreCase ........................................................................479
RegExp.input ..................................................................................480
RegExp.lastIndex............................................................................481
RegExp.lastMatch ..........................................................................481
RegExp.lastParen............................................................................482
RegExp.leftContext ........................................................................483
RegExp.multiline............................................................................484
RegExp.prototype ..........................................................................485
RegExp.rightContext ......................................................................486
RegExp.source ................................................................................487
RegExp.test() ..................................................................................487
RegExp.toSource() ........................................................................488
00 0672321419 FM 7/24/01 11:46 AM Page xv

xv

RegExp.toString() ..........................................................................489
RegExp.unwatch() ..........................................................................490
RegExp.valueOf() ..........................................................................491
RegExp.watch() ..............................................................................492
return ..............................................................................................493
ScriptEngine ..................................................................................494
ScriptEngineBuildVersion ..............................................................494
ScriptEngineMajorVersion ............................................................495
ScriptEngineMinorVersion ............................................................495
short ................................................................................................496
static................................................................................................496
String (Function) ............................................................................497
String (Object) ................................................................................497
String.anchor()................................................................................501
String.big()......................................................................................502
String.blink() ..................................................................................503
String.bold()....................................................................................503
String.charAt()................................................................................504
String.charCodeAt() ......................................................................505
String.concat() ................................................................................507
String.constructor ..........................................................................507
String.fixed() ..................................................................................508
String.fontcolor() ............................................................................509
String.fontsize() ..............................................................................509
String.fromCharCode() ..................................................................510
String.indexOf()..............................................................................511
String.italics() ................................................................................512
String.lastIndexOf() ........................................................................513
String.length ..................................................................................514
String.link() ....................................................................................515
String.localeCompare() ..................................................................515
String.match() ................................................................................516
String.prototype ..............................................................................517
String.replace() ..............................................................................519
String.search() ................................................................................520
String.slice() ..................................................................................521
String.small() ..................................................................................522
String.split()....................................................................................522
String.strike()..................................................................................524
String.sub() ....................................................................................525
String.substr() ................................................................................526
String.substring() ............................................................................527
String.sup() ....................................................................................528
String.toLocaleLowerCase() ..........................................................528
String.toLocaleUpperCase() ..........................................................529
00 0672321419 FM 7/24/01 11:46 AM Page xvi

xvi

String.toLowerCase()......................................................................530
String.toSource() ............................................................................531
String.toString()..............................................................................532
String.toUpperCase()......................................................................533
String.unwatch() ............................................................................533
String.valueOf() ..............................................................................534
String.watch() ................................................................................535
sun ..................................................................................................536
super................................................................................................537
switch..............................................................................................537
synchronized ..................................................................................539
this ..................................................................................................539
throw ..............................................................................................541
throws ............................................................................................543
transient ..........................................................................................543
true ..................................................................................................544
try...catch...finally ..........................................................................544
typeof ..............................................................................................546
undefined ........................................................................................548
unescape() ......................................................................................548
var ..................................................................................................549
VBArray ........................................................................................551
VBArray.dimensions()....................................................................552
VBArray.getItem()..........................................................................553
VBArray.lbound() ..........................................................................555
VBArray.toArray()..........................................................................556
VBArray.ubound() ..........................................................................557
void ................................................................................................559
volatile ............................................................................................559
while ..............................................................................................560
with ................................................................................................561

8 CLIENT-SIDE 563
Anchor ............................................................................................564
Anchor.name ..................................................................................566
Anchor.text ....................................................................................567
Anchor.unwatch() ..........................................................................568
Anchor.watch() ..............................................................................569
Anchor.x ........................................................................................570
Anchor.y ........................................................................................571
Applet ............................................................................................572
Area ................................................................................................573
Area.handleEvent() ........................................................................576
Area.hash ........................................................................................578
Area.host ........................................................................................580
00 0672321419 FM 7/24/01 11:46 AM Page xvii

xvii

Area.hostname ................................................................................582
Area.href ........................................................................................583
Area.onDblClick ............................................................................584
Area.onMouseOut ..........................................................................585
Area.onMouseOver ........................................................................586
Area.pathname................................................................................587
Area.port ........................................................................................588
Area.protocol ..................................................................................589
Area.search ....................................................................................590
Area.target ......................................................................................591
Area.unwatch() ..............................................................................594
Area.watch() ..................................................................................596
Button ............................................................................................597
Button.blur() ..................................................................................599
Button.click()..................................................................................600
Button.focus() ................................................................................601
Button.form ....................................................................................602
Button.handleEvent()......................................................................603
Button.name....................................................................................605
Button.onBlur ................................................................................606
Button.onClick................................................................................606
Button.onFocus ..............................................................................607
Button.onMouseDown....................................................................608
Button.onMouseUp ........................................................................608
Button.type ....................................................................................609
Button.unwatch() ............................................................................610
Button.value....................................................................................612
Button.watch() ................................................................................613
Checkbox ........................................................................................614
Checkbox.blur()..............................................................................617
Checkbox.checked..........................................................................618
Checkbox.click() ............................................................................620
Checkbox.defaultChecked ..............................................................621
Checkbox.focus()............................................................................622
Checkbox.form ..............................................................................623
Checkbox.handleEvent() ................................................................624
Checkbox.name ..............................................................................626
Checkbox.onBlur............................................................................627
Checkbox.onClick ..........................................................................628
Checkbox.onFocus ........................................................................630
Checkbox.type ................................................................................631
Checkbox.unwatch() ......................................................................632
Checkbox.value ..............................................................................634
Checkbox.watch() ..........................................................................635
Document........................................................................................636
00 0672321419 FM 7/24/01 11:46 AM Page xviii

xviii

document.alinkColor ......................................................................637
document.all ..................................................................................638
document.all.item() ........................................................................639
document.all.tags() ........................................................................640
document.anchors ..........................................................................641
document.anchors.length ................................................................642
document.applets ............................................................................643
document.applets.length ................................................................644
document.bgColor ..........................................................................645
document.captureEvents() ..............................................................646
document.classes ............................................................................648
document.close() ............................................................................651
document.contextual() ....................................................................652
document.cookie ............................................................................652
document.domain ..........................................................................653
document.embeds ..........................................................................654
document.embeds.length ................................................................655
document.fgColor ..........................................................................655
document.formName ......................................................................656
document.forms ..............................................................................657
document.forms.length ..................................................................658
document.getSelection() ................................................................659
document.handleEvent() ................................................................660
document.ids ..................................................................................661
document.images ............................................................................664
document.images.length ................................................................665
document.lastModified ..................................................................666
document.layers..............................................................................667
document.layers.length ..................................................................668
document.linkColor ........................................................................669
document.links................................................................................670
document.links.length ....................................................................671
document.onClick ..........................................................................672
document.onDblClick ....................................................................673
document.onKeyDown ..................................................................674
document.onKeyPress ....................................................................675
document.onKeyUp ........................................................................676
document.onLoad ..........................................................................677
document.onMouseDown ..............................................................677
document.onMouseUp....................................................................678
document.onUnLoad ......................................................................679
document.open() ............................................................................680
document.plugins............................................................................681
document.plugins.length ................................................................682
document.referrer ..........................................................................682
00 0672321419 FM 7/24/01 11:46 AM Page xix

xix

document.releaseEvents() ..............................................................683
document.routeEvent() ..................................................................685
document.tags ................................................................................687
document.title ................................................................................690
document.unwatch() ......................................................................690
document.URL ..............................................................................692
document.vlinkColor ......................................................................692
document.watch() ..........................................................................693
document.write() ............................................................................694
document.writeln() ........................................................................695
Embed ............................................................................................697
Event ..............................................................................................698
event.data ........................................................................................701
event.height ....................................................................................702
event.layerX....................................................................................703
event.layerY....................................................................................704
event.modifiers ..............................................................................705
event.pageX ....................................................................................707
event.pageY ....................................................................................708
event.screenX..................................................................................709
event.screenY..................................................................................711
event.target......................................................................................712
event.type........................................................................................713
event.unwatch() ..............................................................................715
event.watch() ..................................................................................716
event.which ....................................................................................718
event.width......................................................................................718
Event.ABORT ................................................................................720
Event.BLUR ..................................................................................721
Event.CHANGE ............................................................................722
Event.CLICK..................................................................................723
Event.DBLCLICK..........................................................................724
Event.DRAGDROP ........................................................................725
Event.ERROR ................................................................................726
Event.FOCUS ................................................................................728
Event.KEYDOWN ........................................................................729
Event.KEYPRESS..........................................................................730
Event.KEYUP ................................................................................731
Event.LOAD ..................................................................................732
Event.MOUSEDOWN....................................................................733
Event.MOUSEMOVE ....................................................................734
Event.MOUSEOUT........................................................................735
Event.MOUSEOVER ....................................................................736
Event.MOUSEUP ..........................................................................737
Event.MOVE ..................................................................................738
00 0672321419 FM 7/24/01 11:46 AM Page xx

xx

Event.RESET..................................................................................739
Event.RESIZE ................................................................................741
Event.SELECT ..............................................................................742
Event.SUBMIT ..............................................................................743
Event.UNLOAD ............................................................................744
FileUpload ......................................................................................745
FileUpload.blur() ............................................................................747
FileUpload.focus()..........................................................................748
FileUpload.form ............................................................................749
FileUpload.handleEvent() ..............................................................750
FileUpload.name ............................................................................752
FileUpload.onBlur ..........................................................................753
FileUpload.onChange ....................................................................754
FileUpload.onFocus........................................................................755
FileUpload.select() ........................................................................756
FileUpload.type ..............................................................................757
FileUpload.unwatch() ....................................................................758
FileUpload.value ............................................................................759
FileUpload.watch() ........................................................................760
Form................................................................................................761
Form.action ....................................................................................763
Form.elements ................................................................................764
Form.elements.length ....................................................................765
Form.encoding................................................................................766
Form.handleEvent() ........................................................................767
Form.length ....................................................................................768
Form.method ..................................................................................769
Form.name......................................................................................770
Form.onReset..................................................................................771
Form.onSubmit ..............................................................................772
Form.reset() ....................................................................................773
Form.submit() ................................................................................774
Form.target......................................................................................775
Form.unwatch() ..............................................................................776
Form.watch() ..................................................................................777
Frame ..............................................................................................778
Frame.blur() ..................................................................................779
Frame.clearInterval() ......................................................................780
Frame.clearTimeout() ....................................................................781
Frame.document ............................................................................781
Frame.focus()..................................................................................782
Frame.frames ..................................................................................782
Frame.length ..................................................................................783
Frame.name ....................................................................................784
Frame.onBlur..................................................................................784
00 0672321419 FM 7/24/01 11:46 AM Page xxi

xxi

Frame.onFocus ..............................................................................785
Frame.onMove................................................................................786
Frame.onResize ..............................................................................786
Frame.parent ..................................................................................787
Frame.print() ..................................................................................787
Frame.self ......................................................................................788
Frame.setInterval()..........................................................................788
Frame.setTimeout() ........................................................................789
Frame.top........................................................................................790
Frame.unwatch() ............................................................................790
Frame.watch() ................................................................................791
Frame.window ................................................................................792
Hidden ............................................................................................793
Hidden.form....................................................................................794
Hidden.name ..................................................................................795
Hidden.type ....................................................................................795
Hidden.unwatch() ..........................................................................796
Hidden.value ..................................................................................797
Hidden.watch() ..............................................................................798
History ............................................................................................799
History.back() ................................................................................800
History.current ................................................................................800
History.forward() ............................................................................801
History.go() ....................................................................................802
History.length ................................................................................802
History.next ....................................................................................803
History.previous..............................................................................804
History.unwatch() ..........................................................................805
History.watch() ..............................................................................806
Image ..............................................................................................807
Image.border ..................................................................................809
Image.complete ..............................................................................810
Image.handleEvent() ......................................................................811
Image.height ..................................................................................811
Image.hspace ..................................................................................812
Image.lowsrc ..................................................................................813
Image.name ....................................................................................814
Image.onAbort................................................................................814
Image.onError ................................................................................815
Image.onKeyDown ........................................................................815
Image.onKeyPress ..........................................................................816
Image.onKeyUp..............................................................................816
Image.onLoad ................................................................................816
Image.src ........................................................................................817
Image.unwatch() ............................................................................818
00 0672321419 FM 7/24/01 11:46 AM Page xxii

xxii

Image.vspace ..................................................................................819
Image.watch() ................................................................................819
Image.width ....................................................................................820
Layer ..............................................................................................821
Layer.above ....................................................................................823
Layer.background ..........................................................................824
Layer.below ....................................................................................825
Layer.bgColor ................................................................................826
Layer.captureEvents() ....................................................................827
Layer.clip.bottom............................................................................828
Layer.clip.height ............................................................................829
Layer.clip.left..................................................................................830
Layer.clip.right................................................................................831
Layer.clip.top ..................................................................................832
Layer.clip.width ..............................................................................833
Layer.document ..............................................................................834
Layer.handleEvent() ......................................................................835
Layer.left ........................................................................................837
Layer.load() ....................................................................................838
Layer.moveAbove() ........................................................................838
Layer.moveBelow() ........................................................................839
Layer.moveBy() ..............................................................................840
Layer.moveTo() ..............................................................................841
Layer.moveToAbsolute() ................................................................842
Layer.name ....................................................................................843
Layer.onBlur ..................................................................................844
Layer.onFocus ................................................................................845
Layer.onLoad..................................................................................846
Layer.onMouseOut ........................................................................847
Layer.onMouseOver ......................................................................848
Layer.pageX....................................................................................849
Layer.pageY....................................................................................850
Layer.parentLayer ..........................................................................851
Layer.releaseEvents() ....................................................................852
Layer.resizeBy() ............................................................................853
Layer.resizeTo() ..............................................................................854
Layer.routeEvent() ..........................................................................855
Layer.siblingAbove ........................................................................856
Layer.siblingBelow ........................................................................857
Layer.src ........................................................................................858
Layer.top ........................................................................................859
Layer.unwatch()..............................................................................860
Layer.visibility................................................................................861
Layer.watch()..................................................................................862
Layer.zIndex ..................................................................................864
00 0672321419 FM 7/24/01 11:46 AM Page xxiii

xxiii

Link ................................................................................................864
Link.handleEvent() ........................................................................866
Link.hash ........................................................................................867
Link.host ........................................................................................868
Link.hostname ................................................................................869
Link.href ........................................................................................870
Link.onClick ..................................................................................871
Link.onDblClick ............................................................................871
Link.onKeyDown ..........................................................................872
Link.onKeyPress ............................................................................873
Link.onKeyUp ................................................................................874
Link.onMouseDown ......................................................................874
Link.onMouseOut ..........................................................................875
Link.onMouseOver ........................................................................876
Link.onMouseUp............................................................................877
Link.pathname ................................................................................877
Link.port ........................................................................................878
Link.protocol ..................................................................................879
Link.search ....................................................................................880
Link.target ......................................................................................881
Link.text..........................................................................................882
Link.unwatch() ..............................................................................883
Link.watch() ..................................................................................884
Location ..........................................................................................885
Location.hash..................................................................................886
Location.host ..................................................................................887
Location.hostname..........................................................................889
Location.href ..................................................................................890
Location.pathname ........................................................................891
Location.port ..................................................................................892
Location.protocol............................................................................893
Location.reload() ............................................................................894
Location.replace() ..........................................................................895
Location.search ..............................................................................895
Location.unwatch() ........................................................................896
Location.watch() ............................................................................898
MimeType ......................................................................................899
MimeType.description ....................................................................900
MimeType.enabledPlugin ..............................................................901
MimeType.suffixes ........................................................................901
MimeType.type ..............................................................................902
MimeType.unwatch()......................................................................903
MimeType.watch()..........................................................................903
navigator ........................................................................................904
navigator.appCodeName ................................................................905
00 0672321419 FM 7/24/01 11:46 AM Page xxiv

xxiv

navigator.appName ........................................................................906
navigator.appVersion ......................................................................906
navigator.javaEnabled() ..................................................................907
navigator.language ..........................................................................908
navigator.mimeTypes......................................................................908
navigator.platform ..........................................................................909
navigator.plugins ............................................................................910
navigator.plugins.refresh()..............................................................911
navigator.preference() ....................................................................911
navigator.taintEnabled()..................................................................912
navigator.userAgent ........................................................................913
navigator.unwatch() ........................................................................914
navigator.watch() ............................................................................914
Option ............................................................................................914
Option.defaultSelected ..................................................................916
Option.selected ..............................................................................917
Option.text ......................................................................................918
Option.unwatch()............................................................................919
Option.value ..................................................................................920
Option.watch()................................................................................921
Password ........................................................................................922
Password.blur() ..............................................................................923
Password.defaultValue....................................................................924
Password.focus() ............................................................................925
Password.form ................................................................................925
Password.handleEvent() ................................................................926
Password.name ..............................................................................927
Password.onBlur ............................................................................928
Password.onFocus ..........................................................................929
Password.select() ............................................................................930
Password.type ................................................................................930
Password.unwatch()........................................................................931
Password.value ..............................................................................932
Password.watch()............................................................................933
Plugin..............................................................................................934
Plugin.description ..........................................................................935
Plugin.filename ..............................................................................935
Plugin.length ..................................................................................936
Plugin.name ....................................................................................937
Plugin.unwatch() ............................................................................937
Plugin.watch() ................................................................................938
Radio ..............................................................................................938
Radio.blur() ....................................................................................939
Radio.checked ................................................................................940
Radio.click() ..................................................................................941
00 0672321419 FM 7/24/01 11:46 AM Page xxv

xxv

Radio.defaultChecked ....................................................................942
Radio.focus() ..................................................................................943
Radio.form......................................................................................944
Radio.handleEvent() ......................................................................944
Radio.name ....................................................................................946
Radio.onBlur ..................................................................................946
Radio.onClick ................................................................................947
Radio.onFocus() ............................................................................948
Radio.type ......................................................................................949
Radio.unwatch() ............................................................................949
Radio.value ....................................................................................950
Radio.watch() ................................................................................951
Reset ..............................................................................................952
Reset.blur() ....................................................................................953
Reset.click()....................................................................................954
Reset.focus() ..................................................................................955
Reset.form ......................................................................................956
Reset.handleEvent()........................................................................957
Reset.name......................................................................................958
Reset.onBlur ..................................................................................959
Reset.onClick..................................................................................960
Reset.onFocus ................................................................................961
Reset.type ......................................................................................962
Reset.unwatch() ..............................................................................962
Reset.value......................................................................................964
Reset.watch() ..................................................................................965
screen ..............................................................................................967
screen.availHeight ..........................................................................968
screen.availLeft ..............................................................................969
screen.availTop ..............................................................................969
screen.availWidth............................................................................970
screen.colorDepth ..........................................................................971
screen.height ..................................................................................971
Screen.pixelDepth ..........................................................................972
screen.unwatch() ............................................................................972
screen.watch() ................................................................................973
screen.width....................................................................................974
Select ..............................................................................................974
Select.blur() ....................................................................................976
Select.focus() ..................................................................................978
Select.form......................................................................................979
Select.handleEvent() ......................................................................980
Select.length ..................................................................................982
Select.name ....................................................................................983
Select.onBlur ..................................................................................984
00 0672321419 FM 7/24/01 11:46 AM Page xxvi

xxvi

Select.onChange ............................................................................985
Select.onFocus................................................................................986
Select.options..................................................................................987
Select.options.length ......................................................................989
Select.options.selectedIndex ..........................................................989
Select.options.value ........................................................................990
Select.selectedIndex ......................................................................991
Select.type ......................................................................................991
Select.unwatch() ............................................................................992
Select.watch() ................................................................................993
Style ................................................................................................994
Style.align ......................................................................................997
Style.backgroundColor ..................................................................998
Style.backgroundImage ..................................................................999
Style.borderBottomWidth ............................................................1000
Style.borderColor ........................................................................1001
Style.borderLeftWidth ..................................................................1001
Style.borderRightWidth................................................................1002
Style.borderStyle ..........................................................................1003
Style.borderTopWidth ..................................................................1004
Style.borderWidths() ....................................................................1004
Style.clear ....................................................................................1006
Style.color ....................................................................................1007
Style.display ................................................................................1007
Style.fontFamily ..........................................................................1008
Style.fontSize................................................................................1009
Style.fontStyle ..............................................................................1010
Style.fontWeight ..........................................................................1011
Style.lineHeight ............................................................................1012
Style.listStyleType ........................................................................1013
Style.marginBottom......................................................................1014
Style.marginLeft ..........................................................................1015
Style.marginRight ........................................................................1016
Style.margins() ............................................................................1016
Style.marginTop............................................................................1018
Style.paddingBottom ....................................................................1018
Style.paddingLeft ........................................................................1019
Style.paddingRight ......................................................................1020
Style.paddings()............................................................................1021
Style.paddingTop ..........................................................................1022
Style.textAlign..............................................................................1023
Style.textDecoration ....................................................................1024
Style.textIndent ............................................................................1024
Style.textTransform ......................................................................1025
Style.unwatch() ............................................................................1026
00 0672321419 FM 7/24/01 11:46 AM Page xxvii

xxvii

Style.watch() ................................................................................1027
Style.whiteSpace ..........................................................................1028
Style.width....................................................................................1028
Submit ..........................................................................................1029
Submit.blur() ................................................................................1031
Submit.click() ..............................................................................1032
Submit.focus() ..............................................................................1034
Submit.form..................................................................................1034
Submit.handleEvent() ..................................................................1036
Submit.name ................................................................................1037
Submit.onBlur ..............................................................................1038
Submit.onClick ............................................................................1039
Submit.onFocus ............................................................................1040
Submit.type ..................................................................................1041
Submit.unwatch() ........................................................................1042
Submit.value ................................................................................1043
Submit.watch() ............................................................................1044
taint() ............................................................................................1045
Text ..............................................................................................1046
Text.blur() ....................................................................................1048
Text.defaultValue ..........................................................................1049
Text.focus() ..................................................................................1050
Text.form ......................................................................................1051
Text.handleEvent()........................................................................1052
Text.name......................................................................................1053
Text.onBlur ..................................................................................1054
Text.onChange ..............................................................................1055
Text.onFocus ................................................................................1056
Text.onSelect ................................................................................1057
Text.select() ..................................................................................1058
Text.type ......................................................................................1059
Text.unwatch() ..............................................................................1060
Text.value......................................................................................1061
Text.watch() ..................................................................................1062
Textarea ........................................................................................1063
Textarea.blur() ..............................................................................1065
Textarea.defaultValue ..................................................................1066
Textarea.focus() ............................................................................1067
Textarea.form................................................................................1068
Textarea.handleEvent() ................................................................1070
Textarea.name ..............................................................................1071
Textarea.onBlur ............................................................................1072
Textarea.onChange ......................................................................1073
Textarea.onFocus ..........................................................................1074
Textarea.onKeyDown ..................................................................1075
00 0672321419 FM 7/24/01 11:46 AM Page xxviii

xxviii

Textarea.onKeyPress ....................................................................1076
Textarea.onKeyUp ........................................................................1077
Textarea.onSelect..........................................................................1078
Textarea.select()............................................................................1079
Textarea.type ................................................................................1080
Textarea.unwatch() ......................................................................1081
Textarea.value ..............................................................................1082
Textarea.watch() ..........................................................................1083
untaint() ........................................................................................1084
Window ........................................................................................1085
window.alert() ..............................................................................1090
window.atob() ..............................................................................1091
window.back() ..............................................................................1092
window.blur()................................................................................1092
window.btoa() ..............................................................................1094
window.captureEvents() ..............................................................1094
window.clearInterval()..................................................................1096
window.clearTimeout() ................................................................1098
window.close()..............................................................................1099
window.closed ..............................................................................1100
window.confirm() ........................................................................1102
window.crypto ..............................................................................1103
window.crypto.random() ..............................................................1104
window.crypto.signText() ............................................................1104
window.defaultStatus....................................................................1105
window.disableExternalCapture() ................................................1106
window.document ........................................................................1107
window.enableExternalCapture() ................................................1110
window.find()................................................................................1111
window.focus() ............................................................................1112
window.forward() ........................................................................1113
window.frames..............................................................................1114
window.frames.length ..................................................................1115
window.handleEvent() ..................................................................1115
window.history..............................................................................1116
window.home() ............................................................................1118
window.innerHeight......................................................................1118
window.innerWidth ......................................................................1120
window.length ..............................................................................1121
window.location............................................................................1122
window.locationbar ......................................................................1122
window.locationbar.visible ..........................................................1123
window.menubar ..........................................................................1123
window.menubar.visible ..............................................................1124
window.moveBy() ........................................................................1125
00 0672321419 FM 7/24/01 11:46 AM Page xxix

xxix

window.moveTo() ........................................................................1126
window.name ................................................................................1127
window.offscreenBuffering ..........................................................1129
window.onBlur..............................................................................1129
window.onDragDrop ....................................................................1130
window.onError ............................................................................1130
window.onFocus ..........................................................................1131
window.onLoad ............................................................................1132
window.onMove ..........................................................................1132
window.onResize ..........................................................................1133
window.onUnload ........................................................................1133
window.open() ..............................................................................1134
window.opener..............................................................................1137
window.outerHeight......................................................................1139
window.outerWidth ......................................................................1140
window.pageXOffset ....................................................................1142
window.pageYOffset ....................................................................1143
window.parent ..............................................................................1144
window.personalbar ......................................................................1144
window.personalbar.visible ..........................................................1145
window.print() ..............................................................................1146
window.prompt() ..........................................................................1147
window.releaseEvents() ................................................................1148
window.resizeBy() ........................................................................1150
window.resizeTo() ........................................................................1151
window.routeEvent() ....................................................................1152
window.screenX............................................................................1154
window.screenY............................................................................1155
window.scroll() ............................................................................1156
window.scrollbars ........................................................................1157
window.scrollbars.visible ............................................................1158
window.scrollBy() ........................................................................1158
window.scrollTo() ........................................................................1160
window.self ..................................................................................1161
window.setHotKeys() ..................................................................1162
window.setInterval() ....................................................................1162
window.setResizable() ..................................................................1164
window.setTimeout() ....................................................................1164
window.setZOptions() ..................................................................1165
window.status................................................................................1166
window.statusbar ..........................................................................1167
window.statusbar.visible ..............................................................1167
window.stop() ..............................................................................1168
window.toolbar ............................................................................1169
window.toolbar.visible..................................................................1169
00 0672321419 FM 7/24/01 11:46 AM Page xxx

xxx

window.top....................................................................................1170
window.unwatch() ........................................................................1171
window.watch() ............................................................................1172
window.window............................................................................1173

9 SERVER-SIDE 1175
addClient() ....................................................................................1176
addResponseHeader() ..................................................................1176
Application ..................................................................................1177
Application.Application_OnEnd ..................................................1178
Application.Application_OnStart ................................................1179
Application.Contents ....................................................................1179
Application.Contents.Remove() ..................................................1180
Application.Contents.RemoveAll() ..............................................1180
Application.Lock() ......................................................................1181
Application.StaticObjects ............................................................1182
Application.Unlock()....................................................................1182
ASPError ......................................................................................1183
ASPError.ASPCode......................................................................1184
ASPError.ASPDescription............................................................1184
ASPError.Category ......................................................................1185
ASPError.Column ........................................................................1185
ASPError.Description ..................................................................1185
ASPError.File ..............................................................................1186
ASPError.Line ..............................................................................1186
ASPError.Number ........................................................................1187
ASPError.Source ..........................................................................1187
blob() (Function) ..........................................................................1188
blob (Object) ................................................................................1189
blob.blobImage() ..........................................................................1190
blob.blobLink() ............................................................................1191
callC() ..........................................................................................1192
client ............................................................................................1193
client.destroy()..............................................................................1195
client.expiration() ........................................................................1196
client.property ..............................................................................1196
client.unwatch() ............................................................................1197
client.watch() ................................................................................1198
Connection....................................................................................1199
Connection.beginTransaction() ....................................................1201
Connection.commitTransaction() ................................................1202
Connection.connected()................................................................1203
Connection.cursor() ......................................................................1204
Connection.execute() ....................................................................1205
Connection.majorErrorCode()......................................................1205
00 0672321419 FM 7/24/01 11:46 AM Page xxxi

xxxi

Connection.majorErrorMessage() ................................................1206
Connection.minorErrorCode()......................................................1207
Connection.minorErrorMessage() ................................................1208
Connection.prototype ..................................................................1209
Connection.release() ....................................................................1210
Connection.rollbackTransaction() ................................................1211
Connection.SQLTable() ................................................................1212
Connection.storedProc() ..............................................................1213
Connection.toString() ..................................................................1215
Connection.unwatch() ..................................................................1216
Connection.watch() ......................................................................1218
Cursor ..........................................................................................1219
Cursor.close()................................................................................1221
Cursor.columnName ....................................................................1222
Cursor.columnName() ..................................................................1222
Cursor.columns() ..........................................................................1224
Cursor.deleteRow() ......................................................................1225
Cursor.insertRow() ......................................................................1226
Cursor.next() ................................................................................1227
Cursor.prototype ..........................................................................1228
Cursor.unwatch() ..........................................................................1229
Cursor.updateRow()......................................................................1231
Cursor.watch() ..............................................................................1232
database ........................................................................................1233
database.beginTransaction() ........................................................1235
database.commitTransaction()......................................................1236
database.connect() ........................................................................1237
database.connected() ....................................................................1239
database.cursor() ..........................................................................1240
database.disconnect()....................................................................1241
database.execute() ........................................................................1242
database.majorErrorCode() ..........................................................1242
database.majorErrorMessage() ....................................................1243
database.minorErrorCode() ..........................................................1244
database.minorErrorMessage() ....................................................1245
database.prototype ........................................................................1246
database.rollbackTransaction() ....................................................1247
database.SQLTable() ....................................................................1248
database.storedProc()....................................................................1249
database.storedProcArgs() ............................................................1250
database.toString()........................................................................1251
database.unwatch() ......................................................................1253
database.watch() ..........................................................................1254
DbPool ..........................................................................................1255
DbPool.connect()..........................................................................1258
00 0672321419 FM 7/24/01 11:46 AM Page xxxii

xxxii

DbPool.connected() ......................................................................1260
DbPool.connection() ....................................................................1261
DbPool.DbPool() ..........................................................................1262
DbPool.disconnect() ....................................................................1263
DbPool.majorErrorCode() ............................................................1264
DbPool.majorErrorMessage() ......................................................1264
DbPool.minorErrorCode()............................................................1265
DbPool.minorErrorMessage() ......................................................1266
DbPool.prototype..........................................................................1267
DbPool.storedProcArgs() ............................................................1268
DbPool.toString() ........................................................................1269
DBPool.unwatch() ........................................................................1270
DBPool.watch() ............................................................................1272
debug()..........................................................................................1273
deleteResponseHeader() ..............................................................1274
File() ............................................................................................1274
File.byteToString() ......................................................................1277
File.clearError() ............................................................................1278
File.close() ....................................................................................1279
File.constructor ............................................................................1279
File.eof() ......................................................................................1280
File.error() ....................................................................................1281
File.exists() ..................................................................................1282
File.flush() ....................................................................................1283
File.getLength() ............................................................................1284
File.getPosition() ..........................................................................1284
File.open() ....................................................................................1285
File.prototype................................................................................1286
File.read() ....................................................................................1288
File.readByte()..............................................................................1288
File.readln() ..................................................................................1289
File.setPosition() ..........................................................................1290
File.stringToByte() ......................................................................1291
File.unwatch() ..............................................................................1292
File.watch() ..................................................................................1294
File.write() ....................................................................................1295
File.writeByte() ............................................................................1296
File.writeln() ................................................................................1297
flush()............................................................................................1298
getOptionValue() ..........................................................................1299
getOptionValueCount() ................................................................1300
Lock() ..........................................................................................1300
Lock.constructor ..........................................................................1301
Lock.isValid() ..............................................................................1302
Lock.lock() ..................................................................................1303
00 0672321419 FM 7/24/01 11:46 AM Page xxxiii

xxxiii

Lock.prototype..............................................................................1303
Lock.unlock() ..............................................................................1305
Lock.unwatch() ............................................................................1305
Lock.watch() ................................................................................1307
ObjectContext ..............................................................................1308
ObjectContext.OnTransactionAbort ............................................1309
ObjectContext.OnTransactionCommit ........................................1310
ObjectContext.SetAbort() ............................................................1310
ObjectContext.SetComplete() ......................................................1311
project ..........................................................................................1312
project.lock() ................................................................................1313
project.unlock() ............................................................................1313
project.unwatch()..........................................................................1314
project.watch()..............................................................................1315
redirect() ......................................................................................1316
registerCFunction() ......................................................................1317
Request ........................................................................................1318
Request.BinaryRead() ..................................................................1318
Request.ClientCertificate..............................................................1319
Request.Cookies ..........................................................................1321
Request.Form................................................................................1321
Request.Form.Form.Count ..........................................................1322
Request.QueryString ....................................................................1323
Request.QueryString.Count..........................................................1323
Request.ServerVariables ..............................................................1324
Request.TotalBytes ......................................................................1326
request ..........................................................................................1327
request.agent ................................................................................1328
request.formKey ..........................................................................1328
request.imageX ............................................................................1329
request.imageY ............................................................................1330
request.ip ......................................................................................1331
request.method..............................................................................1331
request.protocol ............................................................................1332
request.unwatch() ........................................................................1333
request.watch() ............................................................................1334
Response ......................................................................................1334
Response.AddHeader() ................................................................1335
Response.AppendToLog() ............................................................1336
Response.BinaryWrite() ..............................................................1336
Response.Buffer ..........................................................................1337
Response.CacheControl................................................................1337
Response.Charset..........................................................................1338
Response.Clear() ..........................................................................1338
Response.ContentType ................................................................1339
00 0672321419 FM 7/24/01 11:46 AM Page xxxiv

xxxiv

Response.Cookies ........................................................................1339
Response.End() ............................................................................1340
Response.Expires..........................................................................1340
Response.ExpiresAbsolute ..........................................................1341
Response.Flush() ..........................................................................1341
Response.IsClientConnected ........................................................1342
Response.PICS ............................................................................1342
Response.Redirect()......................................................................1343
Response.Status ............................................................................1343
Response.Write() ..........................................................................1344
Resultset........................................................................................1344
Resultset.close()............................................................................1346
Resultset.columnName() ..............................................................1347
Resultset.columns() ......................................................................1348
Resultset.next() ............................................................................1349
Resultset.prototype ......................................................................1350
Resultset.unwatch() ......................................................................1351
Resultset.watch() ..........................................................................1353
ScriptingContext ..........................................................................1354
SendMail ......................................................................................1354
SendMail.Bcc ..............................................................................1357
SendMail.Body ............................................................................1357
SendMail.Cc ................................................................................1358
SendMail.constructor....................................................................1358
SendMail.errorCode() ..................................................................1359
SendMail.errorMessage() ............................................................1360
SendMail.Errorsto ........................................................................1361
SendMail.From ............................................................................1361
SendMail.Organization ................................................................1362
SendMail.prototype ......................................................................1362
SendMail.Replyto ........................................................................1363
SendMail.send()............................................................................1364
SendMail.Smtpserver ..................................................................1365
SendMail.Subject..........................................................................1365
SendMail.To ................................................................................1366
SendMail.unwatch() ....................................................................1366
SendMail.watch() ........................................................................1367
Server............................................................................................1368
Server.CreateObject() ..................................................................1369
Server.Execute()............................................................................1369
Server.GetLastError() ..................................................................1370
Server.HTMLEncode() ................................................................1370
Server.MapPath() ..........................................................................1371
Server.ScriptTimeout ....................................................................1371
Server.Transfer() ..........................................................................1372
00 0672321419 FM 7/24/01 11:46 AM Page xxxv

xxxv

Server.URLEncode() ....................................................................1372
server ............................................................................................1373
server.host ....................................................................................1374
server.hostname ............................................................................1374
server.lock() ..................................................................................1375
server.port ....................................................................................1375
server.protocol ..............................................................................1376
server.unlock() ..............................................................................1376
server.unwatch()............................................................................1377
server.watch()................................................................................1378
Session ..........................................................................................1378
Session.Abandon()........................................................................1379
Session.CodePage ........................................................................1380
Session.Contents ..........................................................................1381
Session.Contents.Remove()..........................................................1381
Session.Contents.RemoveAll() ....................................................1382
Session.LCID................................................................................1383
Session.SessionID ........................................................................1383
Session.Session_OnEnd ..............................................................1384
Session.Session_OnStart ..............................................................1384
Session.StaticObjects....................................................................1385
Session.Timeout............................................................................1385
ssjs_generateClientID() ................................................................1385
ssjs_getCGIVariable() ..................................................................1386
ssjs_getClientID() ........................................................................1387
Stproc............................................................................................1388
Stproc.close()................................................................................1389
Stproc.outParamCount() ..............................................................1390
Stproc.outParameters() ................................................................1391
Stproc.prototype ..........................................................................1392
Stproc.resultSet() ..........................................................................1393
Stproc.returnValue() ....................................................................1395
Stproc.unwatch() ..........................................................................1395
Stproc.watch() ..............................................................................1397
write() ..........................................................................................1398

INDEX CD:2025

CD-ROM ONLY CHAPTERS


10 DOM CORE (CD-ROM) 1403
Attr ........................................................................................CD:1403
Attr.Name ..............................................................................CD:1404
Attr.specified ..........................................................................CD:1404
Attr.value................................................................................CD:1405
Attr.ownerElement ................................................................CD:1406
00 0672321419 FM 7/24/01 11:46 AM Page xxxvi

xxxvi

CDATASection ......................................................................CD:1406
CharacterData ........................................................................CD:1407
CharacterData.data ................................................................CD:1408
CharacterData.length ............................................................CD:1408
CharacterData.substringData() ..............................................CD:1409
CharacterData.appendData()..................................................CD:1409
CharacterData.insertData() ....................................................CD:1410
CharacterData.deleteData()....................................................CD:1411
CharacterData.replaceData()..................................................CD:1411
Comment................................................................................CD:1412
Document ..............................................................................CD:1412
Document.createAttribute() ..................................................CD:1414
Document.createAttributeNS() ..............................................CD:1414
Document.createCDATASection() ........................................CD:1415
Document.createComment()..................................................CD:1416
Document.createDocumentFragment()..................................CD:1416
Document.createElement() ....................................................CD:1417
Document.createElementNS() ..............................................CD:1417
Document.createEntityReference()........................................CD:1418
Document.createProcessingInstruction() ..............................CD:1419
Document.createTextNode() ..................................................CD:1419
Document.doctype ................................................................CD:1420
Document.documentElement ................................................CD:1421
Document.getElementById() ................................................CD:1421
Document.getElementsByTagName() ..................................CD:1422
Document.getElementsByTagNameNS() ..............................CD:1422
Document.implementation ....................................................CD:1423
Document.importNode()........................................................CD:1424
DocumentFragment................................................................CD:1424
DocumentType ......................................................................CD:1425
DocumentType.entities ..........................................................CD:1426
DocumentType.internalSubset ..............................................CD:1426
DocumentType.name ............................................................CD:1427
DocumentType.notations ......................................................CD:1427
DocumentType.publicId ........................................................CD:1428
DocumentType.systemId ......................................................CD:1429
DOMException ......................................................................CD:1429
DOMException.code ............................................................CD:1430
DOMImplementation ............................................................CD:1431
DOMImplementation.createDocument() ..............................CD:1432
DOMImplementation.createDocumentType() ......................CD:1433
DOMImplementation.hasFeature()........................................CD:1433
Element ..................................................................................CD:1434
Element.getAttribute() ..........................................................CD:1435
Element.getAttributeNode() ..................................................CD:1436
00 0672321419 FM 7/24/01 11:46 AM Page xxxvii

xxxvii

Element.getAttributeNodeNS() ............................................CD:1436
Element.getAttributeNS() ......................................................CD:1437
Element.getElementsByTagName() ......................................CD:1438
Element.getElementsByTagNameNS()..................................CD:1438
Element.hasAttribute() ..........................................................CD:1439
Element.hasAttributeNS()......................................................CD:1439
Element.removeAttribute() ....................................................CD:1440
Element.removeAttributeNode()............................................CD:1440
Element.removeAttributeNS() ..............................................CD:1441
Element.setAttribute()............................................................CD:1442
Element.setAttributeNode() ..................................................CD:1442
Element.setAttributeNodeNS() ..............................................CD:1443
Element.setAttributeNS() ......................................................CD:1444
Element.tagName ..................................................................CD:1444
Entity......................................................................................CD:1445
Entity.notationName ..............................................................CD:1445
Entity.publicId........................................................................CD:1446
Entity.systemId ......................................................................CD:1446
EntityReference......................................................................CD:1447
NamedNodeMap ....................................................................CD:1447
NamedNodeMap.getNamedItem() ........................................CD:1448
NamedNodeMap.getNamedItemNS() ..................................CD:1449
NamedNodeMap.item() ........................................................CD:1449
NamedNodeMap.length ........................................................CD:1450
NamedNodeMap.removeNamedItem()..................................CD:1451
NamedNodeMap.removeNamedItemNS() ............................CD:1451
NamedNodeMap.setNamedItem() ........................................CD:1452
NamedNodeMap.setNamedItemNS()....................................CD:1453
Node ......................................................................................CD:1453
Node.attributes ......................................................................CD:1456
Node.appendChild() ..............................................................CD:1457
Node.childNodes....................................................................CD:1457
Node.cloneNode()..................................................................CD:1458
Node.firstChild ......................................................................CD:1458
Node.hasAttributes() ..............................................................CD:1459
Node.hasChildNodes() ..........................................................CD:1460
Node.insertBefore() ..............................................................CD:1460
Node.isSupported() ................................................................CD:1461
Node.lastChild ......................................................................CD:1462
Node.localName ....................................................................CD:1462
Node.namespaceURI ............................................................CD:1463
Node.nextSibling ..................................................................CD:1463
Node.nodeName ....................................................................CD:1464
Node.nodeType ......................................................................CD:1465
Node.nodeValue ....................................................................CD:1465
00 0672321419 FM 7/24/01 11:46 AM Page xxxviii

xxxviii

Node.normalize() ..................................................................CD:1466
Node.ownerDocument ..........................................................CD:1466
Node.parentNode ..................................................................CD:1467
Node.prefix ............................................................................CD:1468
Node.previousSibling ............................................................CD:1468
Node.removeChild() ..............................................................CD:1469
Node.replaceChild() ..............................................................CD:1469
Notation..................................................................................CD:1470
Notation.publicId ..................................................................CD:1471
Notation.systemId ..................................................................CD:1471
ProcessingInstruction ............................................................CD:1472
ProcessingInstruction.data ....................................................CD:1472
ProcessingInstruction.target ..................................................CD:1473
Text ........................................................................................CD:1474
Text.splitText() ......................................................................CD:1474

11 DOM HTML (CD-ROM) 1479


HTMLAnchorElement ..........................................................CD:1480
HTMLAnchorElement.accessKey ........................................CD:1481
HTMLAnchorElement.blur() ................................................CD:1482
HTMLAnchorElement.charset ..............................................CD:1482
HTMLAnchorElement.coords ..............................................CD:1483
HTMLAnchorElement.focus() ..............................................CD:1484
HTMLAnchorElement.href ..................................................CD:1484
HTMLAnchorElement.hrefLang ..........................................CD:1485
HTMLAnchorElement.name ................................................CD:1485
HTMLAnchorElement.rel......................................................CD:1486
HTMLAnchorElement.rev ....................................................CD:1486
HTMLAnchorElement.shape ................................................CD:1487
HTMLAnchorElement.tabIndex ............................................CD:1488
HTMLAnchorElement.target ................................................CD:1488
HTMLAnchorElement.type ..................................................CD:1489
HTMLAppletElement ............................................................CD:1489
HTMLAppletElement.align ..................................................CD:1490
HTMLAppletElement.alt ......................................................CD:1491
HTMLAppletElement.archive ..............................................CD:1492
HTMLAppletElement.code ..................................................CD:1492
HTMLAppletElement.codeBase............................................CD:1493
HTMLAppletElement.height ................................................CD:1493
HTMLAppletElement.hspace ................................................CD:1494
HTMLAppletElement.name ..................................................CD:1495
HTMLAppletElement.object ................................................CD:1495
HTMLAppletElement.vspace ................................................CD:1496
HTMLAppletElement.width..................................................CD:1496
HTMLAreaElement ..............................................................CD:1497
00 0672321419 FM 7/24/01 11:46 AM Page xxxix

xxxix

HTMLAreaElement.accessKey ............................................CD:1498
HTMLAreaElement.alt ..........................................................CD:1498
HTMLAreaElement.coords ..................................................CD:1499
HTMLAreaElement.href........................................................CD:1500
HTMLAreaElement.noHref ..................................................CD:1500
HTMLAreaElement.shape ....................................................CD:1501
HTMLAreaElement.tabIndex ................................................CD:1501
HTMLAreaElement.target ....................................................CD:1502
HTMLBaseElement ..............................................................CD:1503
HTMLBaseElement.href........................................................CD:1503
HTMLBaseElement.target ....................................................CD:1504
HTMLBaseFontElement........................................................CD:1505
HTMLBaseFontElement.color ..............................................CD:1505
HTMLBaseFontElement.face ................................................CD:1506
HTMLBaseFontElement.size ................................................CD:1507
HTMLBodyElement ..............................................................CD:1507
HTMLBodyElement.aLink....................................................CD:1508
HTMLBodyElement.background ..........................................CD:1509
HTMLBodyElement.bgColor ................................................CD:1509
HTMLBodyElement.link ......................................................CD:1510
HTMLBodyElement.text ......................................................CD:1511
HTMLBodyElement.vLink....................................................CD:1511
HTMLBRElement..................................................................CD:1512
HTMLBRElement.clear ........................................................CD:1512
HTMLButtonElement ............................................................CD:1513
HTMLButtonElement.accessKey ..........................................CD:1514
HTMLButtonElement.disabled..............................................CD:1514
HTMLButtonElement.form ..................................................CD:1515
HTMLButtonElement.name ..................................................CD:1516
HTMLButtonElement.tabIndex ............................................CD:1516
HTMLButtonElement.type ....................................................CD:1517
HTMLButtonElement.value ..................................................CD:1517
HTMLCollection....................................................................CD:1518
HTMLCollection.item() ........................................................CD:1519
HTMLCollection.length ........................................................CD:1520
HTMLCollection.namedItem()..............................................CD:1520
HTMLDirectoryElement........................................................CD:1521
HTMLDirectoryElement.compact ........................................CD:1522
HTMLDivElement ................................................................CD:1522
HTMLDivElement.align ........................................................CD:1523
HTMLDListElement..............................................................CD:1524
HTMLDListElement.compact ..............................................CD:1524
HTMLDocument....................................................................CD:1525
HTMLDocument.anchors ......................................................CD:1526
HTMLDocument.applets ......................................................CD:1527
00 0672321419 FM 7/24/01 11:46 AM Page xl

xl

HTMLDocument.body ..........................................................CD:1528
HTMLDocument.close()........................................................CD:1528
HTMLDocument.cookie........................................................CD:1529
HTMLDocument.domain ......................................................CD:1530
HTMLDocument.forms ........................................................CD:1530
HTMLDocument.getElementsByName()..............................CD:1531
HTMLDocument.images ......................................................CD:1532
HTMLDocument.links ..........................................................CD:1533
HTMLDocument.open() ........................................................CD:1533
HTMLDocument.referrer ......................................................CD:1534
HTMLDocument.title ............................................................CD:1535
HTMLDocument.URL ..........................................................CD:1535
HTMLDocument.write()........................................................CD:1536
HTMLDocument.writeln() ....................................................CD:1537
HTMLDOMImplementation..................................................CD:1537
HTMLDOMImplementation.createHTMLDocument() ........CD:1538
HTMLElement ......................................................................CD:1539
HTMLElement.className ....................................................CD:1540
HTMLElement.dir ................................................................CD:1540
HTMLElement.id ..................................................................CD:1541
HTMLElement.lang ..............................................................CD:1541
HTMLElement.title................................................................CD:1542
HTMLFieldSetElement..........................................................CD:1543
HTMLFieldSetElement.form ................................................CD:1543
HTMLFontElement................................................................CD:1544
HTMLFontElement.color ......................................................CD:1545
HTMLFontElement.face ........................................................CD:1545
HTMLFontElement.size ........................................................CD:1546
HTMLFormElement ..............................................................CD:1546
HTMLFormElement.acceptCharset ......................................CD:1547
HTMLFormElement.action ..................................................CD:1548
HTMLFormElement.elements ..............................................CD:1549
HTMLFormElement.enctype ................................................CD:1549
HTMLFormElement.length ..................................................CD:1550
HTMLFormElement.method ................................................CD:1551
HTMLFormElement.name ....................................................CD:1551
HTMLFormElement.reset() ..................................................CD:1552
HTMLFormElement.submit()................................................CD:1553
HTMLFormElement.target ....................................................CD:1553
HTMLFrameElement ............................................................CD:1554
HTMLFrameElement.contentDocument ..............................CD:1555
HTMLFrameElement.frameBorder ......................................CD:1555
HTMLFrameElement.longDesc ............................................CD:1556
HTMLFrameElement.marginHeight ....................................CD:1557
HTMLFrameElement.marginWidth ......................................CD:1557
00 0672321419 FM 7/24/01 11:46 AM Page xli

xli

HTMLFrameElement.name ..................................................CD:1558
HTMLFrameElement.noResize ............................................CD:1558
HTMLFrameElement.scrolling..............................................CD:1559
HTMLFrameElement.src ......................................................CD:1560
HTMLFrameSetElement........................................................CD:1560
HTMLFrameSetElement.cols ................................................CD:1561
HTMLFrameSetElement.rows ..............................................CD:1562
HTMLHeadElement ..............................................................CD:1562
HTMLHeadElement.profile ..................................................CD:1563
HTMLHeadingElement ........................................................CD:1564
HTMLHeadingElement.align ................................................CD:1564
HTMLHRElement ................................................................CD:1565
HTMLHRElement.align ........................................................CD:1566
HTMLHRElement.noShade ..................................................CD:1566
HTMLHRElement.size ..........................................................CD:1567
HTMLHRElement.width ......................................................CD:1567
HTMLHtmlElement ..............................................................CD:1568
HTMLHtmlElement.version ..................................................CD:1569
HTMLIFrameElement ..........................................................CD:1569
HTMLIFrameElement.align ..................................................CD:1570
HTMLIFrameElement.contentDocument..............................CD:1571
HTMLIFrameElement.frameBorder......................................CD:1571
HTMLIFrameElement.height ................................................CD:1572
HTMLIFrameElement.longDesc ..........................................CD:1573
HTMLIFrameElement.marginHeight ....................................CD:1573
HTMLIFrameElement.marginWidth ....................................CD:1574
HTMLIFrameElement.name..................................................CD:1574
HTMLIFrameElement.scrolling ............................................CD:1575
HTMLIFrameElement.src......................................................CD:1576
HTMLIFrameElement.width ................................................CD:1576
HTMLImageElement ............................................................CD:1577
HTMLImageElement.align....................................................CD:1578
HTMLImageElement.alt........................................................CD:1578
HTMLImageElement.border ................................................CD:1579
HTMLImageElement.height..................................................CD:1580
HTMLImageElement.hspace ................................................CD:1580
HTMLImageElement.isMap..................................................CD:1581
HTMLImageElement.longDesc ............................................CD:1581
HTMLImageElement.lowSrc ................................................CD:1582
HTMLImageElement.src ......................................................CD:1583
HTMLImageElement.useMap ..............................................CD:1583
HTMLImageElement.vspace ................................................CD:1584
HTMLImageElement.width ..................................................CD:1584
HTMLInputElement ..............................................................CD:1585
HTMLInputElement.accept ..................................................CD:1587
00 0672321419 FM 7/24/01 11:46 AM Page xlii

xlii

HTMLInputElement.accessKey ............................................CD:1587
HTMLInputElement.align ....................................................CD:1588
HTMLInputElement.alt ........................................................CD:1588
HTMLInputElement.blur() ....................................................CD:1589
HTMLInputElement.checked ................................................CD:1589
HTMLInputElement.click() ..................................................CD:1590
HTMLInputElement.defaultChecked ....................................CD:1591
HTMLInputElement.defaultValue ........................................CD:1591
HTMLInputElement.disabled ................................................CD:1592
HTMLInputElement.focus() ..................................................CD:1593
HTMLInputElement.form......................................................CD:1593
HTMLInputElement.maxLength ..........................................CD:1594
HTMLInputElement.name ....................................................CD:1594
HTMLInputElement.readOnly ..............................................CD:1595
HTMLInputElement.select()..................................................CD:1596
HTMLInputElement.size ......................................................CD:1596
HTMLInputElement.src ........................................................CD:1597
HTMLInputElement.tabIndex ..............................................CD:1597
HTMLInputElement.type ......................................................CD:1598
HTMLInputElement.useMap ................................................CD:1599
HTMLInputElement.value ....................................................CD:1599
HTMLIsIndexElement ..........................................................CD:1600
HTMLIsIndexElement.form ..................................................CD:1601
HTMLIsIndexElement.prompt ..............................................CD:1601
HTMLLabelElement..............................................................CD:1602
HTMLLabelElement.accessKey ............................................CD:1603
HTMLLabelElement.form ....................................................CD:1603
HTMLLabelElement.htmlFor ................................................CD:1604
HTMLLegendElement ..........................................................CD:1604
HTMLLegendElement.accessKey ........................................CD:1605
HTMLLegendElement.align ..................................................CD:1606
HTMLLegendElement.form ..................................................CD:1606
HTMLLIElement ..................................................................CD:1607
HTMLLIElement.type ..........................................................CD:1608
HTMLLIElement.value..........................................................CD:1608
HTMLLinkElement ..............................................................CD:1609
HTMLLinkElement.charset ..................................................CD:1610
HTMLLinkElement.disabled ................................................CD:1610
HTMLLinkElement.href........................................................CD:1611
HTMLLinkElement.hreflang ................................................CD:1612
HTMLLinkElement.media ....................................................CD:1612
HTMLLinkElement.rel ..........................................................CD:1613
HTMLLinkElement.rev ........................................................CD:1613
HTMLLinkElement.target ....................................................CD:1614
HTMLLinkElement.type ......................................................CD:1615
00 0672321419 FM 7/24/01 11:46 AM Page xliii

xliii

HTMLMapElement................................................................CD:1615
HTMLMapElement.areas ......................................................CD:1616
HTMLMapElement.name......................................................CD:1616
HTMLMenuElement..............................................................CD:1617
HTMLMenuElement.compact ..............................................CD:1618
HTMLMetaElement ..............................................................CD:1618
HTMLMetaElement.content..................................................CD:1619
HTMLMetaElement.httpEquiv ..............................................CD:1620
HTMLMetaElement.name ....................................................CD:1620
HTMLMetaElement.scheme..................................................CD:1621
HTMLModElement ..............................................................CD:1622
HTMLModElement.cite ........................................................CD:1622
HTMLModElement.dateTime ..............................................CD:1623
HTMLObjectElement ............................................................CD:1624
HTMLObjectElement.align ..................................................CD:1625
HTMLObjectElement.archive................................................CD:1625
HTMLObjectElement.border ................................................CD:1626
HTMLObjectElement.code....................................................CD:1627
HTMLObjectElement.codeBase............................................CD:1627
HTMLObjectElement.codeType............................................CD:1628
HTMLObjectElement.contentDocument ..............................CD:1628
HTMLObjectElement.data ....................................................CD:1629
HTMLObjectElement.declare................................................CD:1630
HTMLObjectElement.form ..................................................CD:1630
HTMLObjectElement.height ................................................CD:1631
HTMLObjectElement.hspace ................................................CD:1631
HTMLObjectElement.name ..................................................CD:1632
HTMLObjectElement.standby ..............................................CD:1633
HTMLObjectElement.tabIndex ............................................CD:1633
HTMLObjectElement.type ....................................................CD:1634
HTMLObjectElement.useMap ..............................................CD:1634
HTMLObjectElement.vspace ................................................CD:1635
HTMLObjectElement.width ..................................................CD:1636
HTMLOListElement..............................................................CD:1636
HTMLOListElement.compact ..............................................CD:1637
HTMLOListElement.start......................................................CD:1637
HTMLOListElement.type......................................................CD:1638
HTMLOptGroupElement ......................................................CD:1639
HTMLOptGroupElement.disabled ........................................CD:1639
HTMLOptGroupElement.label..............................................CD:1640
HTMLOptionElement............................................................CD:1641
HTMLOptionElement.defaultSelected ..................................CD:1642
HTMLOptionElement.disabled ............................................CD:1642
HTMLOptionElement.form ..................................................CD:1643
HTMLOptionElement.index ..................................................CD:1644
00 0672321419 FM 7/24/01 11:46 AM Page xliv

xliv

HTMLOptionElement.label ..................................................CD:1645
HTMLOptionElement.selected..............................................CD:1645
HTMLOptionElement.text ....................................................CD:1646
HTMLOptionElement.value ..................................................CD:1647
HTMLParagraphElement ......................................................CD:1647
HTMLParagraphElement.align..............................................CD:1648
HTMLParamElement ............................................................CD:1649
HTMLParamElement.name ..................................................CD:1649
HTMLParamElement.type ....................................................CD:1650
HTMLParamElement.value ..................................................CD:1651
HTMLParamElement.valueType ..........................................CD:1651
HTMLPreElement..................................................................CD:1652
HTMLPreElement.width ......................................................CD:1653
HTMLQuoteElement ............................................................CD:1653
HTMLQuoteElement.cite ......................................................CD:1654
HTMLScriptElement ............................................................CD:1654
HTMLScriptElement.charset ................................................CD:1655
HTMLScriptElement.defer ....................................................CD:1656
HTMLScriptElement.event....................................................CD:1657
HTMLScriptElement.htmlFor ..............................................CD:1657
HTMLScriptElement.src........................................................CD:1657
HTMLScriptElement.text ......................................................CD:1658
HTMLScriptElement.type ....................................................CD:1658
HTMLSelectElement ............................................................CD:1659
HTMLSelectElement.add()....................................................CD:1660
HTMLSelectElement.blur() ..................................................CD:1661
HTMLSelectElement.disabled ..............................................CD:1661
HTMLSelectElement.focus() ................................................CD:1662
HTMLSelectElement.form ....................................................CD:1663
HTMLSelectElement.length ..................................................CD:1663
HTMLSelectElement.multiple ..............................................CD:1664
HTMLSelectElement.name ..................................................CD:1665
HTMLSelectElement.options ................................................CD:1665
HTMLSelectElement.remove()..............................................CD:1666
HTMLSelectElement.selectedIndex ......................................CD:1667
HTMLSelectElement.size......................................................CD:1667
HTMLSelectElement.tabIndex ..............................................CD:1668
HTMLSelectElement.type ....................................................CD:1669
HTMLSelectElement.value....................................................CD:1669
HTMLStyleElement ..............................................................CD:1670
HTMLStyleElement.disabled ................................................CD:1671
HTMLStyleElement.media....................................................CD:1671
HTMLStyleElement.type ......................................................CD:1672
HTMLTableCaptionElement..................................................CD:1673
HTMLTableCaptionElement.align ........................................CD:1673
00 0672321419 FM 7/24/01 11:46 AM Page xlv

xlv

HTMLTableCellElement........................................................CD:1674
HTMLTableCellElement.abbr................................................CD:1675
HTMLTableCellElement.align ..............................................CD:1676
HTMLTableCellElement.axis ................................................CD:1676
HTMLTableCellElement.bgColor..........................................CD:1677
HTMLTableCellElement.cellIndex ........................................CD:1677
HTMLTableCellElement.ch ..................................................CD:1678
HTMLTableCellElement.chOff..............................................CD:1678
HTMLTableCellElement.colSpan..........................................CD:1679
HTMLTableCellElement.headers ..........................................CD:1680
HTMLTableCellElement.height ............................................CD:1680
HTMLTableCellElement.noWrap..........................................CD:1681
HTMLTableCellElement.rowSpan ........................................CD:1681
HTMLTableCellElement.scope..............................................CD:1682
HTMLTableCellElement.vAlign............................................CD:1682
HTMLTableCellElement.width..............................................CD:1683
HTMLTableColElement ........................................................CD:1683
HTMLTableColElement.align................................................CD:1684
HTMLTableColElement.ch....................................................CD:1685
HTMLTableColElement.chOff ..............................................CD:1686
HTMLTableColElement.span ................................................CD:1686
HTMLTableColElement.vAlign ............................................CD:1687
HTMLTableColElement.width ..............................................CD:1687
HTMLTableElement ..............................................................CD:1688
HTMLTableElement.align ....................................................CD:1689
HTMLTableElement.bgColor ................................................CD:1690
HTMLTableElement.border ..................................................CD:1690
HTMLTableElement.caption..................................................CD:1691
HTMLTableElement.cellPadding ..........................................CD:1692
HTMLTableElement.cellSpacing ..........................................CD:1692
HTMLTableElement.createCaption() ....................................CD:1693
HTMLTableElement.createTFoot() ......................................CD:1693
HTMLTableElement.createTHead() ......................................CD:1694
HTMLTableElement.deleteCaption() ....................................CD:1695
HTMLTableElement.deleteRow()..........................................CD:1695
HTMLTableElement.deleteTFoot() ......................................CD:1696
HTMLTableElement.deleteTHead() ......................................CD:1696
HTMLTableElement.frame ....................................................CD:1697
HTMLTableElement.insertRow() ..........................................CD:1698
HTMLTableElement.rows......................................................CD:1698
HTMLTableElement.rules......................................................CD:1699
HTMLTableElement.summary ..............................................CD:1699
HTMLTableElement.tBodies ................................................CD:1700
HTMLTableElement.tFoot ....................................................CD:1701
HTMLTableElement.tHead....................................................CD:1701
00 0672321419 FM 7/24/01 11:46 AM Page xlvi

xlvi

HTMLTableElement.width ....................................................CD:1702
HTMLTableRowElement ......................................................CD:1702
HTMLTableRowElement.align ..............................................CD:1703
HTMLTableRowElement.bgColor ........................................CD:1704
HTMLTableRowElement.cells ..............................................CD:1705
HTMLTableRowElement.ch ..................................................CD:1705
HTMLTableRowElement.chOff ............................................CD:1706
HTMLTableRowElement.deleteCell() ..................................CD:1706
HTMLTableRowElement.insertCell()....................................CD:1707
HTMLTableRowElement.rowIndex ......................................CD:1708
HTMLTableRowElement.sectionRowIndex ..........................CD:1708
HTMLTableRowElement.vAlign ..........................................CD:1709
HTMLTableSectionElement ..................................................CD:1709
HTMLTableSectionElement.align ........................................CD:1710
HTMLTableSectionElement.ch..............................................CD:1711
HTMLTableSectionElement.chOff ........................................CD:1711
HTMLTableSectionElement.deleteRow()..............................CD:1712
HTMLTableSectionElement.insertRow() ..............................CD:1713
HTMLTableSectionElement.rows..........................................CD:1713
HTMLTableSectionElement.vAlign ......................................CD:1714
HTMLTextAreaElement ........................................................CD:1714
HTMLTextAreaElement.accessKey ......................................CD:1715
HTMLTextAreaElement.blur() ..............................................CD:1716
HTMLTextAreaElement.cols ................................................CD:1717
HTMLTextAreaElement.defaultValue ..................................CD:1717
HTMLTextAreaElement.disabled ..........................................CD:1718
HTMLTextAreaElement.focus() ............................................CD:1718
HTMLTextAreaElement.form................................................CD:1719
HTMLTextAreaElement.name ..............................................CD:1720
HTMLTextAreaElement.readOnly ........................................CD:1720
HTMLTextAreaElement.rows................................................CD:1721
HTMLTextAreaElement.select()............................................CD:1721
HTMLTextAreaElement.tabIndex..........................................CD:1722
HTMLTextAreaElement.type ................................................CD:1723
HTMLTextAreaElement.value ..............................................CD:1723
HTMLTitleElement................................................................CD:1724
HTMLTitleElement.text ........................................................CD:1725
HTMLUListElement..............................................................CD:1725
HTMLUListElement.compact ..............................................CD:1726
HTMLUListElement.type......................................................CD:1727

12 DOM EVENTS (CD-ROM) 1731


DocumentEvent......................................................................CD:1731
DocumentEvent.createEvent() ..............................................CD:1732
Event ......................................................................................CD:1732
00 0672321419 FM 7/24/01 11:46 AM Page xlvii

xlvii

Event.type ..............................................................................CD:1734
Event.bubbles ........................................................................CD:1734
Event.cancelable ....................................................................CD:1735
Event.currentTarget................................................................CD:1736
Event.eventPhase ..................................................................CD:1736
Event.initEvent() ....................................................................CD:1737
Event.preventDefault() ..........................................................CD:1738
Event.stopPropagation() ........................................................CD:1739
Event.target ............................................................................CD:1739
Event.timeStamp....................................................................CD:1740
EventException ......................................................................CD:1741
EventException.code ............................................................CD:1742
EventListener ........................................................................CD:1743
EventTarget ............................................................................CD:1744
EventTarget.addEventListener() ............................................CD:1745
EventTarget.dispatchEvent() ..................................................CD:1746
EventTarget.removeEventListener() ......................................CD:1747
MouseEvent ..........................................................................CD:1748
MouseEvent.altKey................................................................CD:1749
MouseEvent.button ................................................................CD:1749
MouseEvent.clientX ..............................................................CD:1750
MouseEvent.clientY ..............................................................CD:1751
MouseEvent.ctrlKey ..............................................................CD:1751
MouseEvent.initMouseEvent() ..............................................CD:1752
MouseEvent.metaKey ............................................................CD:1753
MouseEvent.relatedTarget ....................................................CD:1753
MouseEvent.screenX ............................................................CD:1754
MouseEvent.screenY ............................................................CD:1754
MouseEvent.shiftKey ............................................................CD:1755
MutationEvent........................................................................CD:1756
MutationEvent.relatedNode ..................................................CD:1757
MutationEvent.attrChange ....................................................CD:1758
MutationEvent.attrName........................................................CD:1758
MutationEvent.initMutationEvent() ......................................CD:1759
MutationEvent.newValue ......................................................CD:1760
MutationEvent.prevValue ......................................................CD:1760
UIEvent ..................................................................................CD:1761
UIEvent.detail ........................................................................CD:1762
UIEvent.initUIEvent()............................................................CD:1762
UIEvent.view ........................................................................CD:1763

13 DOM CSS (CD-ROM) 1767


Counter ..................................................................................CD:1767
Counter.identifier ..................................................................CD:1768
Counter.listStyle ....................................................................CD:1768
00 0672321419 FM 7/24/01 11:46 AM Page xlviii

xlviii

Counter.separator ..................................................................CD:1769
CSSCharsetRule ....................................................................CD:1770
CSSCharsetRule.encoding ....................................................CD:1770
CSSFontFaceRule ..................................................................CD:1771
CSSFontFaceRule.style..........................................................CD:1771
CSSImportRule ......................................................................CD:1772
CSSImportRule.href ..............................................................CD:1773
CSSImportRule.media ..........................................................CD:1773
CSSImportRule.styleSheet ....................................................CD:1774
CSSMediaRule ......................................................................CD:1774
CSSMediaRule.cssRules........................................................CD:1775
CSSMediaRule.deleteRule()..................................................CD:1776
CSSMediaRule.insertRule() ..................................................CD:1776
CSSMediaRule.media............................................................CD:1777
CSSPageRule ........................................................................CD:1778
CSSPageRule.selectorText ....................................................CD:1778
CSSPageRule.style ................................................................CD:1779
CSSPrimitiveValue ................................................................CD:1779
CSSPrimitiveValue.getCounterValue() ..................................CD:1782
CSSPrimitiveValue.getFloatValue() ......................................CD:1782
CSSPrimitiveValue.getRectValue()........................................CD:1783
CSSPrimitiveValue.getRGBColorValue()..............................CD:1783
CSSPrimitiveValue.getStringValue() ....................................CD:1784
CSSPrimitiveValue.primitiveType ........................................CD:1785
CSSPrimitiveValue.setFloatValue() ......................................CD:1785
CSSPrimitiveValue.setStringValue()......................................CD:1786
CSSRule ................................................................................CD:1786
CSSRule.cssText ....................................................................CD:1787
CSSRule.parentRule ..............................................................CD:1788
CSSRule.parentStyleSheet ....................................................CD:1789
CSSRule.type ........................................................................CD:1789
CSSRuleList ..........................................................................CD:1790
CSSRuleList.item()................................................................CD:1791
CSSRuleList.length................................................................CD:1791
CSSStyleDeclaration..............................................................CD:1792
CSSStyleDeclaration.cssText ................................................CD:1793
CSSStyleDeclaration.getPropertyCSSValue() ......................CD:1794
CSSStyleDeclaration.getPropertyPriority() ..........................CD:1794
CSSStyleDeclaration.getPropertyValue() ..............................CD:1795
CSSStyleDeclaration.item() ..................................................CD:1796
CSSStyleDeclaration.length ..................................................CD:1796
CSSStyleDeclaration.parentRule ..........................................CD:1797
CSSStyleDeclaration.removeProperty() ................................CD:1797
CSSStyleDeclaration.setProperty()........................................CD:1798
CSSStyleRule ........................................................................CD:1799
00 0672321419 FM 7/24/01 11:46 AM Page xlix

xlix

CSSStyleRule.selectorText ....................................................CD:1799
CSSStyleRule.style ................................................................CD:1800
CSSStyleSheet ......................................................................CD:1800
CSSStyleSheet.cssRules ........................................................CD:1801
CSSStyleSheet.deleteRule() ..................................................CD:1802
CSSStyleSheet.insertRule() ..................................................CD:1802
CSSStyleSheet.ownerRule ....................................................CD:1803
CSSUnknownRule ................................................................CD:1804
CSSValue ..............................................................................CD:1804
CSSValue.cssText ..................................................................CD:1805
CSSValue.cssValueType ........................................................CD:1806
CSSValueList ........................................................................CD:1806
CSSValueList.item() ..............................................................CD:1807
CSSValueList.length ..............................................................CD:1808
DocumentCSS........................................................................CD:1809
DocumentCSS.getOverrideStyle() ........................................CD:1809
DOMImplementationCSS......................................................CD:1810
DOMImplementationCSS.createCSSStyleSheet() ................CD:1810
ElementCSSInlineStyle..........................................................CD:1811
ElementCSSInlineStyle.style ................................................CD:1812
Rect ........................................................................................CD:1812
Rect.bottom............................................................................CD:1813
Rect.left..................................................................................CD:1814
Rect.right................................................................................CD:1814
Rect.top ..................................................................................CD:1815
RGBColor ..............................................................................CD:1815
RGBColor.blue ......................................................................CD:1816
RGBColor.green ....................................................................CD:1817
RGBColor.red ........................................................................CD:1817
ViewCSS ................................................................................CD:1818
ViewCSS.getComputedStyle() ..............................................CD:1818

14 JSCRIPT RUNTIME (CD-ROM) 1823


Dictionary ..............................................................................CD:1824
Dictionary.Add() ....................................................................CD:1825
Dictionary.Count....................................................................CD:1826
Dictionary.Exists() ................................................................CD:1826
Dictionary.Item()....................................................................CD:1827
Dictionary.Items() ..................................................................CD:1828
Dictionary.Key() ....................................................................CD:1829
Dictionary.Keys() ..................................................................CD:1830
Dictionary.Remove()..............................................................CD:1831
Dictionary.RemoveAll() ........................................................CD:1832
Drive ......................................................................................CD:1832
Drive.AvailableSpace ............................................................CD:1834
00 0672321419 FM 7/24/01 11:46 AM Page l

Drive.DriveLetter ..................................................................CD:1834
Drive.DriveType ....................................................................CD:1835
Drive.FileSystem....................................................................CD:1836
Drive.FreeSpace ....................................................................CD:1837
Drive.IsReady ........................................................................CD:1838
Drive.Path ..............................................................................CD:1838
Drive.RootFolder ..................................................................CD:1839
Drive.SerialNumber ..............................................................CD:1840
Drive.ShareName ..................................................................CD:1840
Drive.TotalSize ......................................................................CD:1841
Drive.VolumeName................................................................CD:1842
Drives ....................................................................................CD:1842
Drives.Count ..........................................................................CD:1843
Drives.Item() ..........................................................................CD:1844
File ........................................................................................CD:1845
File.Attributes ........................................................................CD:1846
File.Copy() ............................................................................CD:1847
File.DateCreated ....................................................................CD:1848
File.DateLastAccessed ..........................................................CD:1849
File.DateLastModified ..........................................................CD:1850
File.Delete..............................................................................CD:1851
File.Drive ..............................................................................CD:1852
File.Move() ............................................................................CD:1853
File.Name ..............................................................................CD:1854
File.OpenAsTextStream() ......................................................CD:1854
File.ParentFolder....................................................................CD:1856
File.Path ................................................................................CD:1857
File.ShortName ......................................................................CD:1857
File.ShortPath ........................................................................CD:1858
File.Size ................................................................................CD:1859
File.Type ................................................................................CD:1860
Files........................................................................................CD:1861
Files.Count ............................................................................CD:1862
Files.Item ..............................................................................CD:1863
FileSystemObject ..................................................................CD:1864
FileSystemObject.BuildPath() ..............................................CD:1865
FileSystemObject.CopyFile ..................................................CD:1866
FileSystemObject.CopyFolder() ............................................CD:1867
FileSystemObject.CreateFolder() ..........................................CD:1869
FileSystemObject.CreateTextFile()........................................CD:1869
FileSystemObject.DeleteFile() ..............................................CD:1871
FileSystemObject.DeleteFolder() ..........................................CD:1872
FileSystemObject.DriveExists() ............................................CD:1873
FileSystemObject.Drives ......................................................CD:1874
FileSystemObject.FileExists() ..............................................CD:1874
00 0672321419 FM 7/24/01 11:46 AM Page li

li

FileSystemObject.FolderExists() ..........................................CD:1876
FileSystemObject.GetAbsolutePathName() ..........................CD:1877
FileSystemObject.GetBaseName() ........................................CD:1878
FileSystemObject.GetDrive() ................................................CD:1879
FileSystemObject.GetDriveName() ......................................CD:1879
FileSystemObject.GetExtensionName()................................CD:1880
FileSystemObject.GetFile() ..................................................CD:1882
FileSystemObject.GetFileName()..........................................CD:1882
FileSystemObject.GetFolder() ..............................................CD:1883
FileSystemObject.GetParentFolderName() ..........................CD:1885
FileSystemObject.GetSpecialFolder() ..................................CD:1885
FileSystemObject.GetTempName() ......................................CD:1886
FileSystemObject.MoveFile()................................................CD:1887
FileSystemObject.MoveFolder()............................................CD:1888
FileSystemObject.OpenTextFile() ........................................CD:1889
Folder ....................................................................................CD:1891
Folder.Attributes ....................................................................CD:1892
Folder.Copy() ........................................................................CD:1893
Folder.DateCreated ................................................................CD:1894
Folder.DateLastAccessed ......................................................CD:1895
Folder.DateLastModified ......................................................CD:1896
Folder.Delete() ......................................................................CD:1897
Folder.Drive ..........................................................................CD:1898
Folder.Files ............................................................................CD:1899
Folder.IsRootFolder ..............................................................CD:1899
Folder.Move() ........................................................................CD:1900
Folder.Name ..........................................................................CD:1901
Folder.ParentFolder................................................................CD:1902
Folder.Path ............................................................................CD:1903
Folder.ShortName ..................................................................CD:1903
Folder.ShortPath ....................................................................CD:1904
Folder.Size ............................................................................CD:1905
Folder.SubFolders ..................................................................CD:1906
Folder.Type ............................................................................CD:1907
Folders....................................................................................CD:1908
Folders.Add() ........................................................................CD:1909
Folders.Count ........................................................................CD:1910
Folders.Item ..........................................................................CD:1911
TextStream ............................................................................CD:1912
TextStream.AtEndOfLine ......................................................CD:1913
TextStream.AtEndOfStream ..................................................CD:1914
TextStream.Close() ................................................................CD:1915
TextStream.Column ..............................................................CD:1915
TextStream.Line ....................................................................CD:1916
TextStream.Read() ................................................................CD:1917
00 0672321419 FM 7/24/01 11:46 AM Page lii

lii

TextStream.ReadAll() ............................................................CD:1918
TextStream.ReadLine() ..........................................................CD:1919
TextStream.Skip() ..................................................................CD:1919
TextStream.SkipLine() ..........................................................CD:1920
TextStream.Write() ................................................................CD:1921
TextStream.WriteBlankLines() ..............................................CD:1922
TextStream.WriteLine() ........................................................CD:1923

15 WINDOWS SCRIPT HOST (CD-ROM) 1927


Scripting.Signer ....................................................................CD:1927
WScript ..................................................................................CD:1929
WScript.Arguments ..............................................................CD:1930
WScript.ConnectObject() ......................................................CD:1931
WScript.CreateObject() ........................................................CD:1932
WScript.DisconnectObject()..................................................CD:1933
WScript.Echo() ......................................................................CD:1933
WScript.FullName ................................................................CD:1934
WScript.GetObject() ..............................................................CD:1934
WScript.Interactive ................................................................CD:1935
WScript.Name........................................................................CD:1936
WScript.Path ..........................................................................CD:1937
WScript.Quit() ......................................................................CD:1937
WScript.ScriptFullName........................................................CD:1938
WScript.ScriptName ..............................................................CD:1938
WScript.Sleep()......................................................................CD:1939
WScript.StdErr ......................................................................CD:1939
WScript.StdIn ........................................................................CD:1940
WScript.StdOut......................................................................CD:1941
WScript.Version ....................................................................CD:1942
WScript.WshArguments ........................................................CD:1942
WScript.WshController ........................................................CD:1943
WScript.WshNetwork............................................................CD:1943
WScript.WshShell..................................................................CD:1944
WshArguments ......................................................................CD:1944
WshArguments.Count............................................................CD:1945
WshArguments.Count() ........................................................CD:1946
WshArguments.Item() ..........................................................CD:1946
WshArguments.length ..........................................................CD:1947
WshArguments.Named ..........................................................CD:1948
WshArguments.ShowUsage()................................................CD:1949
WshArguments.Unnamed ......................................................CD:1950
WshArguments.WshNamed ..................................................CD:1951
WshArguments.WshUnnamed ..............................................CD:1952
WshController........................................................................CD:1952
WshController.CreateScript() ................................................CD:1953
00 0672321419 FM 7/24/01 11:46 AM Page liii

liii

WshController.WshRemote ..................................................CD:1954
WshEnvironment ..................................................................CD:1954
WshEnvironment.Count() ......................................................CD:1956
WshEnvironment.Item() ........................................................CD:1957
WshEnvironment.length ........................................................CD:1957
WshEnvironment.Remove() ..................................................CD:1958
WshNamed ............................................................................CD:1960
WshNamed.Count() ..............................................................CD:1961
WshNamed.Exists() ..............................................................CD:1961
WshNamed.Item ....................................................................CD:1962
WshNamed.length..................................................................CD:1963
WshNetwork ..........................................................................CD:1963
WshNetwork.AddPrinterConnection() ..................................CD:1964
WshNetwork.AddWindowsPrinterConnection() ..................CD:1965
WshNetwork.ComputerName................................................CD:1966
WshNetwork.EnumNetworkDrives() ....................................CD:1967
WshNetwork.EnumPrinterConnection()................................CD:1967
WshNetwork.MapNetworkDrive() ........................................CD:1968
WshNetwork.RemoveNetworkDrive() ..................................CD:1969
WshNetwork.RemovePrinterConnection() ............................CD:1970
WshNetwork.SetDefaultPrinter() ..........................................CD:1970
WshNetwork.UserDomain ....................................................CD:1971
WshNetwork.UserName ........................................................CD:1971
WshRemote............................................................................CD:1972
WshRemote.End ....................................................................CD:1973
WshRemote.Error (Event) ....................................................CD:1974
WshRemote.Error (Property) ................................................CD:1974
WshRemote.Execute() ..........................................................CD:1975
WshRemote.WshRemoteError ..............................................CD:1976
WshRemote.Start ..................................................................CD:1976
WshRemote.Status ................................................................CD:1977
WshRemote.Terminate() ........................................................CD:1978
WshRemoteError ..................................................................CD:1979
WshRemoteError.Character ..................................................CD:1980
WshRemoteError.Description................................................CD:1980
WshRemoteError.Line ..........................................................CD:1981
WshRemoteError.Number ....................................................CD:1982
WshRemoteError.Source ......................................................CD:1983
WshRemoteError.SourceText ................................................CD:1984
WshScriptExec ......................................................................CD:1985
WshScriptExec.Status ............................................................CD:1985
WshScriptExec.StdErr ..........................................................CD:1986
WshScriptExec.StdIn ............................................................CD:1987
WshScriptExec.StdOut ..........................................................CD:1988
WshScriptExec.Terminate() ..................................................CD:1989
00 0672321419 FM 7/24/01 11:46 AM Page liv

WshShell ................................................................................CD:1990
WshShell.AppActivate() ........................................................CD:1991
WshShell.CreateShortcut() ....................................................CD:1991
WshShell.CurrentDirectory ..................................................CD:1992
WshShell.Environment ..........................................................CD:1993
WshShell.Exec() ....................................................................CD:1993
WshShell.ExpandEnvironmentStrings() ................................CD:1994
WshShell.LogEvent() ............................................................CD:1995
WshShell.Popup() ..................................................................CD:1996
WshShell.RegDelete() ..........................................................CD:1997
WshShell.RegRead()..............................................................CD:1998
WshShell.RegWrite() ............................................................CD:1998
WshShell.Run()......................................................................CD:1999
WshShell.SendKeys() ............................................................CD:2000
WshShell.SpecialFolders ......................................................CD:2002
WshShell.WshShortcut ..........................................................CD:2003
WshShell.WshUrlShortcut ....................................................CD:2003
WshShell.WshEnvironment ..................................................CD:2003
WshShell.WshSpecialFolders ................................................CD:2004
WshShell.WshScriptExec ......................................................CD:2004
WshShortcut ..........................................................................CD:2004
WshShortcut.Arguments ........................................................CD:2005
WshShortcut.Description ......................................................CD:2006
WshShortcut.FullName..........................................................CD:2007
WshShortcut.Hotkey ..............................................................CD:2007
WshShortcut.IconLocation ....................................................CD:2008
WshShortcut.Save() ..............................................................CD:2009
WshShortcut.TargetPath ........................................................CD:2010
WshShortcut.WindowStyle....................................................CD:2010
WshShortcut.WorkingDirectory ............................................CD:2011
WshSpecialFolders ................................................................CD:2012
WshSpecialFolders.Count......................................................CD:2013
WshSpecialFolders.Item ........................................................CD:2014
WshSpecialFolders.length ....................................................CD:2015
WshUnnamed ........................................................................CD:2015
WshUnnamed.Count() ..........................................................CD:2017
WshUnnamed.Item ................................................................CD:2018
WshUnnamed.length..............................................................CD:2019
WshUrlShortcut ....................................................................CD:2019
WshUrlShortcut.FullName ....................................................CD:2020
WshUrlShortcut.Save() ..........................................................CD:2021
WshUrlShortcut.TargetPath ..................................................CD:2022
00 0672321419 FM 7/24/01 11:46 AM Page lv

About the Authors


R. Allen Wyke, of Durham, North Carolina is vice president of Research and
Development at the eMarketing solutions company Engage, where he works with prod-
uct managers, product marketing, and engineering to help ensure that their products
have the proper vision and direction in both online and offline worlds. He has also
developed intranet Web pages for a leading telecommunications and networking com-
pany, as well as worked on several Internet sites.
Wyke is the author of seven books on various Internet technologies including Perl,
JavaScript, and PHP. In the past, he has also written the monthly Webmaster column
for SunWorld, and a weekly article, “Integrating Windows and Unix,” for ITworld.com.
Jason D. Gilliam is a software developer at ichat, Inc. At ichat, he develops Web-based
chat and discussion group software using C++, JavaScript, HTML, and various other
Internet technologies. In addition to his work at ichat, he has developed intranet Web
pages and numerous C++ applications for a leading telecommunications company and
has worked on several Internet sites for other organizations. Gilliam is also a con-
tributing author to JavaScript Unleashed, Third Edition. He holds a bachelor’s degree
in Computer Engineering from North Carolina State University. Jason and his wife live
in Cary, North Carolina.
Charlton Ting, of Vienna, Virginia is a software engineer for KOZ Inc who began pro-
gramming in JavaScript with its first beta release. He has worked extensively with
many Internet technologies while developing Internet telephony solutions at Lucent
Technologies. His programming experience includes a variety of languages such as
Java, C++, Smalltalk, Perl, HTML, XML, and Pascal. Ting holds degrees in Computer
Engineering and Electrical Engineering from North Carolina State University.
Sean Michaels is a software engineer at Avesair, Inc. where he designs and implements
next generation mobile commerce applications. He has been in the Internet space since
1994 and has a depth of experience in developing highly distributed fault tolerant appli-
cations. He has used Java, C++, and XML extensively over the years. Previously, he
coauthored the Official Netscape ONE book and the Official Netscape Technologies
Developer Guide from Netscape Press. Michaels holds a degree in Latin from Millsaps
College in Jackson, MS and a degree in Computer Science from Mississippi College.
00 0672321419 FM 7/24/01 11:46 AM Page lvi

Dedications
This one is for my sisters: Sandra, Valerie, and Evelyn. They truly are inspirations in my life
and have broadened my visions and provided support well beyond anything I would have ever
imagined. I love each of you very much.
—R. Allen Wyke

I dedicate this book to my wonderful wife, Deena, who is the greatest! Your constant encour-
agement, love, and support has carried me through the writing of this book. I love you!
—Jason D. Gilliam

This book is dedicated to my family: John, Alice, Angela, Melissa, Olivia, and Tilly. Thank you
for all your love and support for everything I’ve done in my life. I love you all very much.
—Charlton Ting

I would like to dedicate this book to my wife April and my two children Noah, and Anna, and
to the memory of my father Alan Michaels without whose influence I would not be here today.
—Sean Michaels

Acknowledgments
R. Allen Wyke
On the publishing side, I would like to thank Bob Kern of TIPS Publishing and my
coauthors, Jason and Chuck, for their professionalism, hard work, and overall support
in the proposing and writing of this book. I would also like to thank Shelley Johnston-
Markanday, who has been nothing short of an absolutely fabulous acquisitions editor,
and Jon Steever, who developed the book and kept us focused. Additionally, I would
like to thank everyone at Sams who worked on the book and helped make sure that was
the best it could be.
I would also like to thank Dan Jaye for the professional opportunities he has allowed
me to pursue at Engage, as well as the pressure to push the envelope a little more. And
finally, I would like to thank the wonderful woman in my life, J, and the rest of the
“Raccoons.” It’s never a dull moment around any of you.

Jason D. Gilliam
I would like to thank Bob Kern of TIPS Publishing and my coauthors, Allen and
Chuck, for their efforts in developing and writing this book. I would also like to thank
our acquisitions editor, Shelley Johnston-Markanday, and development editor, Jon
Steever, for all their hard work as well as everyone at Sams who helped make this book
a success.
I would also like to thank the “lunch guys” for their open ears and words of encour-
agement.
00 0672321419 FM 7/24/01 11:46 AM Page lvii

Charlton Ting
I would like to thank Bob Kern of TIPS Publishing for all his hard work in making this
book possible. I also want to thank my coauthors, Allen and Jason, for all their hard
work, dedication, and encouragement to bring this book together and make it such a
great success. It’s truly an honor to work with you guys. Additionally I would like to
thank Shelley Johnston-Markanday, Scott Meyers, Jon Steever, and everyone at Sams
who worked so hard at making this book so successful.
I also want to thank all my friends who have been there when I needed them: Mike,
Carolyn, Monty, Theresa, Mitch, Sabrina, John O, Sunil “the Z Doc” Cherukuri,
Blanke, Cosima, Nairn, Airmer Roberts, and anyone I may have forgotten to mention.
You guys are the greatest friends anyone could have.

Sean Michaels
I would like to thank Bob Kern at TIPS Publishing for putting up with my antics dur-
ing the authoring process. Also, the coauthors: Allen, Chuck, and Jason for giving me
a solid foundation to work with and making the first edition of this book successful. I
would also like to thank the folks at Sams Publishing: Shelley Johnston-Markanday,
Scott Meyers, and Jon Steever for guiding the book through the process.
00 0672321419 FM 7/24/01 11:46 AM Page lviii

Tell Us What You Think!


As the reader of this book, you are our most important critic and commentator. We
value your opinion and want to know what we’re doing right, what we could do better,
what areas you’d like to see us publish in, and any other words of wisdom you’re will-
ing to pass our way.
You can e-mail or write me directly to let me know what you did or didn’t like about
this book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this
book, and that due to the high volume of mail I receive, I might not be able to reply to
every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or fax number. I will carefully review your comments and share them
with the author and editors who worked on the book.
Fax: 317-581-4770
Email: [email protected]

Mail: Mark Taber


Associate Publisher
Sams Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA
01 0672321416 Intro 7/24/01 11:47 AM Page 1

Introduction
Welcome to Pure JavaScript, 2nd Edition! This book has been written by JavaScript
programmers for JavaScript programmers, and has been updated to cover the most cur-
rent version of the language. It is your complete reference for developing, testing, and
deploying JavaScript solutions in pages and on Web sites.
Pure JavaScript was not written to teach a person how to program, but rather to provide
the details and semantics of the JavaScript language so programmers can exploit it as
they see fit. JavaScript has evolved over the past few years and is reaching into new
areas, especially in the most current browsers and server-side environments, most of
which are addressed in this book. The book itself is broken into three main parts,
including references on concepts, techniques, and syntax. Each represents a valuable
step in learning and using the language.
Part I, “A Programmer’s Overview of JavaScript,” acts as a bridge for programmers
who are currently programming in another language. It covers some programming
techniques, such as the use of regular expressions, event handlers, exceptions, and even
debugging. Many times programmers don’t want to buy a beginners book on JavaScript
because they do not need to know how to program, but rather they need specifics about
the language. When they know these specifics and semantics, the syntax is easy. This
section provides the necessary information for such a programming migration.
Part II, “Programming in JavaScript,” shows you the advantages and strengths of
JavaScript. It discusses some of the pros and cons of using the language on the client-
side, server-side, and even within the Windows Script Host environment. Programmers
will learn how to use JavaScript in real-world instances. They will be introduced to
some of the browser issues as well as how to process Web information. In addition, pro-
grammers will be shown how to access Java functions within an applet and to use
server-side JavaScript for Internet, intranet, or extranet development. After you have
completed this section, you will be ready to move forward and start programming. This
leads you into the last section of the book.
Part III, “JavaScript Reference,” makes up the majority of the book and contains some
of the most useful information for current JavaScript programmers—reference mater-
ial organized by object. Each property, method, and event is discussed in detail under
its associated object; and you’ll see an example of its use. Each entry also shows the
appropriate language version and environment (browser, server, and so on) support.
The section itself is broken into nine chapters. The first chapter covers the core
JavaScript objects and syntax. The next chapter covers objects specific to the client-
side, which is where JavaScript really has its roots. The third, fourth, fifth, and sixth
chapter in this section outlines the various support for the Document Object Model
(DOM) within JavaScript. The seventh chapter covers server-side JavaScript objects for
the Netscape and iPlanet Enterprise servers, and the Active Server pages (ASP) envi-
ronment present in Microsoft’s IIS Web Servers. The second to last chapter in the sec-
tion covers the JScript RunTime objects, and the final chapter covers Windows Script
Host.
01 0672321416 Intro 7/24/01 11:47 AM Page 2

2 Introduction

And that covers it! For new JavaScript programmers, welcome to the world of
JavaScript. For those of you wanting a good, solid reference for your programming
needs, we hope you find this book to be the most resourceful and current title on the
shelves today!
R. Allen Wyke
Jason Gilliam
Charlton Ting
Sean Michaels
02 0672321416 Part I 7/24/01 11:47 AM Page 3

PA R T I

A PROGRAMMER’S
OVERVIEW OF
JAVASCRIPT
1 What Is JavaScript to a Programmer? 5
2 Details of the Language 31
02 0672321416 Part I 7/24/01 11:47 AM Page 4
03 0672321416 CH01 7/24/01 11:47 AM Page 5

What Is JavaScript to a Programmer?


CHAPTER 1

What Is JavaScript to a
Programmer?
In the beginning, there were Assembly and compiled lan-
guages. Later came scripting languages such as sed, awk, and
Perl, which many programmers used to perform a variety of
tasks. Followed by, in the late 80s and early 90s, the Internet,
which exploded into a technological revolution that allowed
anyone with a modem to communicate and retrieve informa-
tion from around the world. As the Internet grew in number of
users, it was obvious that an increase in functionality was
needed in the browsers and the data they were rendering.
HTML, even with its advantages, was falling short of provid-
ing the control many developers wanted when creating Web
pages and applications. This prompted the use of server-side
programs, or scripts as they were often called, to handle some
of the page dynamics developers needed from their sites.
These programs helped Web developers by allowing them to
increase a site’s functionality as well as process user-submitted
information. However, CGI, or common gateway interface,
scripts had to generate and return a response when the user sent
incorrect or incomplete information. This led to the unneces-
sary back-and-forth transmission of data between browser and
server. But, overall, it was a minor price to pay for the func-
tionality it provided.
With time, and an increase in traffic, it became increasingly
obvious that client-side intelligence was needed to offload
some of the CGI functionality. Something was needed to per-
form this error checking and to decrease the amount of time a
user spent connecting to a server to validate data. This would
03 0672321416 CH01 7/24/01 11:47 AM Page 6

6 Chapter 1: What Is JavaScript to a Programmer?

also enable the Web site to offload some of its processing load to the browser machine,
which meant an increase in the overall performance of a site.
It was partially this lack of client-side functionality and efficiency that helped spawn a
new scripting language—one that could be executed within a browser’s environment
and not on the server. This language could be used to perform client-side tasks such as
form validation and dynamic page content creation—one that would put the program-
ming into HTML publishing. Welcome to the birth of JavaScript.

Welcome to JavaScript
On December 4, 1995, Netscape and Sun jointly introduced JavaScript 1.0, originally
called LiveScript, to the world. This language, unlike its server-based predecessors,
could be interpreted within the then new Netscape Navigator 2 browsers. As an inter-
preted language, JavaScript was positioned as a complement to Java and would allow
Web developers to create and deploy custom applications across the enterprise and
Internet alike. JavaScript gave Web developers the power to truly program—not just
format data with HTML.
In addition to the client-side control developers desired, Netscape implemented server-
side JavaScript. This allowed developers to use the same programming language on the
server as they did in their pages for browsers. Database connection enhancements were
added to the language (called LiveWire), allowing the developer to pull information
directly from a database and maintain user sessions for common functionality such as
shopping carts. JavaScript had truly bridged the gap between the simple world of
HTML and the more complex CGI programs on the server. It provided a common lan-
guage for Web developers to design, implement, and deploy solutions across their net-
works and distributed the overall processing load of their applications.
The next level of acceptance in the world of JavaScript was Microsoft’s implementa-
tion of the language in its Internet Explorer 3 browser—the implementation was called
JScript. Similar to Netscape, Microsoft also implemented the language on the server-
side (JScript 2.0) within its ASP (Active Server Pages) environment. It also allowed
developers the flexibility of using a common language on both the client and server-
side, while providing many of the robust features, such as object invocation and usage,
in compiled languages.

J AVA S C R I P T V E R S U S J S C R I P T, A N D W H AT I S
ECMASCRIPT?
JScript 1.0 was based on the published documentation from Netscape, so essen-
tially it is the same thing as JavaScript 1.0. However, there were a few “features”
that Netscape did not publish, as well as some functionality that was not re-cre-
ated by Microsoft correctly. The result of this is that there are some discrepancies
between JScript 1.0 and JavaScript 1.0.
Since the release of these initial browsers, JavaScript and JScript were both submit-
ted to the ECMA (European Computer Manufacturers Association) standardization
03 0672321416 CH01 7/24/01 11:47 AM Page 7

O b j e c t - B a s e d Te c h n o l o g y 7

body and have become the standard known as ECMAScript (ECMA-262). Because
of this standardization, it is now considered that JavaScript is Netscape’s implemen-
tation of ECMAScript while JScript is Microsoft’s implementation.
The adoption of the first edition of ECMAScript occurred in June 1997 followed by
its adoption by the International Organization for Standardization and International
Electrotechnical Commission in April 1998 (ISO/IEC 16262). A second edition of
the standard was approved by ECMA in June 1998, and a third edition was
adopted in December 1999.

NOTE
Because Netscape’s JavaScript was the foundation of all this, the book will refer to
JavaScript, JScript, and ECMAScript simply as JavaScript except where a differentia-
tion is needed.

So, what is JavaScript to the programmer? Well, in its purest form, it is an object-based,
cross-platform, loosely-typed, multi-use language that allows a programmer to deploy
many types of solutions to many clients. It not only involves adding functionality to
Web pages as rendered within a browser, it also allows server-side processing for
Netscape and Microsoft Web servers.
JScript has also been included in Microsoft’s Windows Script Host (WSH), to allow
programmers to write scripts to be executed on the operating system itself, and most
recently as a major language under their .NET strategy (more on that later). When oper-
ating within the WSH environment, JScript is similar to the old DOS batch files, but
gives programmers more functionality and versatility in what they can accomplish.
This type of advancement has allowed the language to take hold in the computer world
and continue to progress.
In addition to the benefits of these environments in which JavaScript can be executed,
security measures are in place to protect end users against malicious code. Even though
it is still young in terms of age, JavaScript is very mature and powerful. This function-
ality, ability, and versatility positions JavaScript as the best solution for many pro-
grammers.
Now that you’ve learned about what JavaScript is, you should dive a little deeper into
what it means to a programmer. Being programmers ourselves, we know that a few
strategically placed words do not make a language useful; so first, we’ll look at the
object-based characteristics of JavaScript.

Object-Based Technology
The fact that you are reading this reference somewhat implies that you have pro-
grammed in JavaScript or at least one other language before, even if only for one
semester in college. Going one step further, I bet the language you programmed in was
either C++, Java, or Perl—with each having various levels of object orientation (OO).
Java specifically is OO by virtue of having all programmer created objects extend from
core Java language classes or their own.
03 0672321416 CH01 7/24/01 11:47 AM Page 8

8 Chapter 1: What Is JavaScript to a Programmer?

Object-Oriented Programming
For those of you unfamiliar with object-oriented programming (OOP), it is a concept
that allows you to create reusable objects or classes in code. An object or class has
associated with it various characteristics and functionality that defines what kind of
properties and states it can take on. After these are created and defined, it is possible to
create new instances—sometimes referred to as children—that inherit the capability to
have the same characteristics of their parent object.
To give you an example of how this might work, let’s create a vehicle object. Some of
the characteristics assigned to this vehicle object are the number of doors, the color,
and the type (such as sports car or truck). In addition to these characteristics, let’s
define the ability to move or stop the vehicle. The pseudo-code for this type of object
might look something similar to the following:
object vehicle(){
// Characteristics of the vehicle
num_doors;
color;
type;

// Methods used to move and stop the truck. Note that the move()
// method takes a direction as an argument. This direction could
// be something like forward, backward, left, or right.
move(direction);
stop();
}

Now that this vehicle object is defined, it is easy to create new instances of it. A vehi-
cle that is a car with four doors and is red can be easily created. You could also create
a vehicle that is a truck with two doors and is black. The possibilities are endless.
In addition to creating these instances of the vehicle object, you have also made it pos-
sible to program in the ability to change the state of your instance. This is accomplished
by specifying whether it is stopped or moving. Again, this method of programming can
make the possibilities endless and certainly reusable.
Here is another example in pseudo-code to illustrate this concept. The sample creates
a black, two-door truck that is moving forward:
// Create the new instance of the vehicle
myTruck = new vehicle();

// Define the type, number of doors and color


myTruck.doors = 2;
myTruck.color = “black”;
myTruck.type = “truck”;

// Define the “state” of the truck


myTruck.move(forward);
03 0672321416 CH01 7/24/01 11:47 AM Page 9

Object-Oriented Programming 9

The basic process here is to create an instance of the vehicle object and then to assign
characteristic values to it. It is these values that make it a unique instance of this object,
which we have specified as a truck.
The existence of the vehicle object itself allows us to easily create more vehicles with
different characteristics. When programming, this “ease” translates into less code—
something all programmers like to hear.
Now that this object is defined, it is possible to create new instances that inherit its
characteristics without having to redefine them. You are able to capitalize on any over-
laps in characteristics within objects by doing this. The idea is to create a general, mas-
ter object that gives you the ability to then derive child instances that provide all the
functionality and characteristics you need.
We can take this a step further by creating new objects—not instances—that inherit the
parent objects’ characteristics. Doing so allows us to derive child instances from the
child object that we have decided will inherit only certain characteristics. We could
define a child object to only pass on the parent object’s color characteristic to any child
instances of its own. It is the concept of this object orientation that allows you to per-
form this modular type of programming.
The following pseudo-code example shows how we could create an airplane object
based on the previous vehicle object:
// Create the new object that inherits the vehicle
object airplane(){

// Inherit the vehicle object


this = new vehicle();

// Define the doors property, then assign it to the size


// property of the plane object, which makes the most sense
this.doors = “747”;
this.size = this.doors;

// Assign the color and type of plane


this.color = “silver”;
this.type = “American Airlines”;

// Define the “state” of the plane


this.move(up);

// Now that the object is created with the values, return the
// object.
return this;
}

Not all languages support this concept, and there are other languages only based on its
concepts. This concept definitely supplies advantages to the language, but it is not
required to write good, effective, modular code. JavaScript is a perfect example of how
03 0672321416 CH01 7/24/01 11:47 AM Page 10

10 Chapter 1: What Is JavaScript to a Programmer?

a language has applied some of these concepts, but is not completely OO. It does this
by being object based.

NOTE
Talking about OOP in further detail is beyond the focus of a JavaScript book, but it
is worth some investigation if you are a real programming enthusiast. Check out
your local bookstore for a selection of titles on this subject. You can also visit
Object Central (http://www.objectcentral.com) on the Web for reference and
links to OOP information.

So how does object-based programming fit into the equation? It is very similar to OO
except that it does not have all the functionality or characteristics. There are limited
amounts of inheritance, scope, and functionality that you can perform with an object-
based language. This should not be taken as mark against JavaScript, because it makes
the language easier to learn and maintain for the developer. OOP is no easy beast to
tackle and will provide many headaches before it is implemented correctly.
JavaScript also makes up for many of its OO limitations by allowing you to create your
own object-like elements, as well as extend the core objects in the language by proto-
typing new properties. To get an idea of how this is done, take a look at JavaScript
object orientation.

Object Orientation of JavaScript


Before we go into a lot of detail on the object orientation of JavaScript, let’s outline the
details of the core components as well as between server-side and client-side objects.
Both sets of objects are specific to their runtime environment, so default object initial-
ization and creation occur at different times. Because of this characteristic, you will
look at the language in several parts:
• Core
• Client-side
• Server-side
• JScript-specific
• Windows Script Host

Core
First and foremost, it is important for you to know and understand the core objects in
the JavaScript language. These objects are generally found across all implementations
and are defined in the ECMAScript standard. These objects lay the foundation for the
shared functionality, such as mathematical, array, or date related, which are used in
most all scripts. Figure 1.1 shows a list of these core objects.
As you can see, the core objects are Array, Boolean, Date, Function, Global, Math,
Number, Object, RegExp, Error, and String. In addition to these objects, both Netscape
03 0672321416 CH01 7/24/01 11:47 AM Page 11

Object-Oriented Programming 11

and Microsoft have created objects specific to their core implementations. These are
not specific to any environment, and are therefore core objects in the sense of their con-
sistency. Figure 1.2 shows these objects.

Array

Boolean

Date

Core Error

Function

Global

Math

Number

Object

RegExp

String

Figure 1.1
Core ECMAScript object hierarchy.

Client-Side
Client-side JavaScript is, at its lowest level, a set of objects created when a page
is loaded in the browser. In addition, there are also objects that revolve around
the browser loading the page and other derived objects that are created when certain
tags are contained on a page. These derived objects inherit some of the various char-
acteristics of their parent object and also allow scripting access to the HTML tag’s
properties.
Understanding the hierarchy of the JavaScript objects is essential if you plan on doing
any in-depth programming. You will get a better understanding of how parent and
child objects interact as well as how they are referenced. To help with this under-
standing, Figure 1.3 gives a graphical representation of the basic client-side
JavaScript hierarchy.
03 0672321416 CH01 7/24/01 11:47 AM Page 12

12 Chapter 1: What Is JavaScript to a Programmer?

As depicted in this diagram, all client-side objects are derived from either the Window
or navigator objects. Considering that this is an object-based language, this structure
makes complete sense. All objects on a given page are constructed within the browser’s
displaying window, hence all these objects are descendants of the Window object. By
using the Window object, a programmer is allowed to access the various frames, docu-
ments, layers, and forms on a page, as well as many other objects and properties.

Arguments

Netscape Java Array

Java Class

Java Object

Java Package

JSException

JSObject

Packages

Microsoft ActiveX

Automation

Enumerator

VBArray

Figure 1.2
Core object hierarchy for Microsoft and Netscape environments.

The navigator object pertains to elements that are part of the browser itself. This
specifically refers to the plug-ins installed and the MIME (Multipart Internet Mail
Extension) types with which the browser is associated. Using the navigator object
allows checking of the browser version, determining the plug-ins installed, and what
programs are associated with the various MIME types registered on the system. There
is also the ability to access other properties of the browser.
In addition to these client-side objects, browsers starting with Internet Explorer 5 and
Netscape 6 have implemented features to support the Document Object Model (DOM).
The DOM is a method in which documents can be referenced. We talk more about the
DOM in Chapter 4, “Client-Side Scripting,” but wanted to include Figure 1.4 to show
you the objects that make up this model.
03 0672321416 CH01 7/24/01 11:48 AM Page 13

Object-Oriented Programming 13

Window navigator

Text Area Plugin

Text MimeType
Frame
Layer FileUpload

Link Password

Document Image Hidden

Area Submit

Anchor Reset
Location
Applet Radio

Plugin Checkbox

History Form Button

Style Select Option

Figure 1.3
Client-side JavaScript object hierarchy.

Server-Side
Similar to client-side, server-side JavaScript has several objects from which all other
objects are derived. The root objects are the DbPool and database objects, for the
Netscape and iPlanet implementations, from which you can create connections to a
database, as well as access cursors, stored procedures, and the resultsets you generate.
Within the Microsoft ASP environment, you have access to several other objects, such
as Response, Session, and Request. Figure 1.5 shows the server-side objecthierarchy.

NOTE
Programmers familiar with Java will find this very similar to the Java language.
There are not as many objects/classes in the JavaScript language, but the structure
and manner in which you access them are similar.
03 0672321416 CH01 7/24/01 11:48 AM Page 14

14 Chapter 1: What Is JavaScript to a Programmer?

DOM

Core HTML

DOMException HTMLCollection HTMLPreElement

ExceptionCode HTMLDocument HTMLBRElement

DOMImplementation HTMLElement HTMLBaseFontElement

DocumentFragment HTMLHtmlElement HTMLFontElement

Document HTMLHeadElement HTMLHRElement

Node HTMLLinkElement HTMLModElement

NodeList HTMLTitleElement HTMLAnchorElement

NamedNodeMap HTMLMetaElement HTMLImageElement

CharacterData HTMLBaseElement HTMLObjectElement

Attr HTMLIsIndexElement HTMLParamElement

Element HTMLStyleElement HTMLAppletElement

Text HTMLBodyElement HTMLMapElement

Comment HTMLFormElement HTMLAreaElement

CDATASection HTMLSelectElement HTMLScriptElement

DocumentType HTMLOptGroupElement HTMLTableElement

Notation HTMLOptionElement HTMLTableCaptionElement

Entity HTMLInputElement HTMLTableColElement

EntityReference HTMLTextAreaElement HTMLTableSectionElement

ProcessingInstruction HTMLButtonElement HTMLTableRowElement

HTMLLabelElement HTMLTableCellElement

HTMLFieldSetElement HTMLFrameSetElement

HTMLLegendElement HTMLFrameElement

HTMLUListElement HTMLIFrameElement

HTMLOListElement

HTMLDListElement

HTMLDirectoryElement

HTMLMenuElement

HTMLLIElement

HTMLBlockquoteElement

HTMLDivElement

HTMLParagraphElement

HTMLHeadingElement

HTMLQuoteElement

Figure 1.4
DOM object hierarchy.
03 0672321416 CH01 7/24/01 11:48 AM Page 15

Object-Oriented Programming 15

Microsoft ASP Application

ASPError

Netscape/iPlanet ObjectContext

Request

Cursor Response

DbPool Connection Server


Stproc Resultset
Session

Cursor
database
Stproc Resultset

Figure 1.5
Server-side object hierarchy.

JScript Runtime
As with about every other language that Microsoft has put its hands on, its JScript
implementation contains objects that are specific to their runtime environment.
Because their JScript engine is used within several of their applications and is a very
important part of their .NET initiative, you will notice that many of the additional
objects are familiar if you have ever worked with COM. Figure 1.6 illustrates the
objects that are specific to the JScript implementation.

Dictionary

Drive

Drives

JScript RunTime File

Files

File System Object

Folder

Folders

Text Stream

Figure 1.6
JScript RunTime object hierarchy.
03 0672321416 CH01 7/24/01 11:48 AM Page 16

16 Chapter 1: What Is JavaScript to a Programmer?

Windows Script Host


In addition to the JScript-specific objects, Microsoft has also implemented objects that
are part of its Windows Script Host environment. These objects, and associated code,
are often used by administrators to perform everyday tasks previously done with batch
files. The Windows Script Host, however, is much more powerful than the batch files
of yesterday, and should be seriously considered for your administrative tasks. Figure
1.7 outlines the object hierarchy of the Windows Script Hostobjects.

WScript WshArguments WshNamed

WshUnnamed

WshController WshRemote WshRemoteError

WshNetwork

WshShell WshShortcut

WshUrlShortcut

WshEnvironment

WshSpecial Folders

WshScript Exec

Figure 1.7
Windows Script Host object hierarchy.

Object Access
Because of this object hierarchy, accessing the various objects and elements on a page
is accomplished by using the hierarchy itself. If you wanted to access a specific text
field in a form on a page, you would do so using the following syntax:
window.document.formName.textboxName.value

TIP
With JavaScript, programmers have the ability to create their own objects or
extend the core ones defined by the language. The explanation of how to create
your own objects—and some examples—is covered in the section on functions in
Chapter 2, “Details of the Language.” If you want to learn more about extending
the functionality of the existing objects, look up objects with the prototype prop-
erty in the reference section of this book.

Because JavaScript is object based, it automatically provides many advantages to using


a modular approach to your programming. By creating your own objects and methods,
03 0672321416 CH01 7/24/01 11:48 AM Page 17

Object-Oriented Programming 17

you are able to better maintain the code with which you are working. You will be cre-
ating code that can be reused in other programs, locations, and instances. Why write
virtually the same code twice (or many times), when you can create it once and pass
the characteristics that differentiate it from other, similar objects?

Modular Programming
To program in a modular fashion in JavaScript really involves three key things. Using
these items in your programming will allow you to create code that can be reused from
project to project. These are
• Creating your own objects
• Defining general functions to handle common tasks
• Placing reusable code in external JavaScript source files (commonly *.js files)

NOTE
As with any other language, remember that good comments within your code and
documentation are often the most beneficial aspects of programming.

Because creating your own objects is discussed in Chapter 2, let’s take a look at defin-
ing functions to handle common tasks. As with other programming languages, there are
instances in which you have to perform certain processes over and over. Many times
this might involve a different value of parameters passed, but the processes you go
through are the same.
As an example, think of verifying a date entered by a user. This user is supposed to
enter the month, date, and year in a form that will be submitted to your Web server for
further processing. One of the concerns of the programmer is that he needs to have the
date in a MM/DD/YYYY format, where the month and date need to be two characters
and the year should be four.
To accomplish this task, you can create a single function that prepends a 0 in front of
any single digit passed. This function could simply check to see if the value passed was
less than the number 10, and, if so, it would perform the prepend. By defining this
process in a function, a programmer will be able to use the same function for both the
month and date verification. This avoids the trouble of writing a function for each.
Even though this is a simple example, it illustrates the benefits of function and code
reuse.
Programmers can also modularize their programming techniques by including their
code in external JavaScript source files. This allows them to write code once, store it
in a single location, and include it on many pages by simply referencing the location
of the source file. If the function needs to change, they only have to change it in a sin-
gle file and not every file that uses it. It is simple things such as these that save Web
programmers hours or days of work time.
03 0672321416 CH01 7/24/01 11:48 AM Page 18

18 Chapter 1: What Is JavaScript to a Programmer?

TIP
Do you serve ads on your Web site? If so, you might want to consider placing your
ad tags in an external JavaScript source file. This will allow you to change the tags
across your entire site if need be. There might be some browser issues with older
versions, so if you make this decision, be sure you at least cover the browsers you
wish to support.

Security
One of the biggest issues facing Internet development today is security. It is not possi-
ble to successfully develop any kind of application, whether it’s Web based or based on
the Web, and not have to implement some kind of security features. A program’s secu-
rity measures can ultimately determine how valuable the overall application is to a user.
If the code can be tampered with or is subject to destruction from another program, the
program will be subject to scrutiny and denial of use.
Because JavaScript is interpreted most often within a browser’s environment, a user
can be subject to malicious code. Browser’s run off the operating system itself, mean-
ing that it has access to a user’s file system. This makes it feasible that a JavaScript pro-
gram could take advantage of a hole in the browser’s security measures to access the
file system. After a programmer has accomplished this, many things are possible—
even access to private documents or the ability to delete them altogether. This leaves a
user at the mercy of a hacker.
Providing security for JavaScript scripts is actually twofold. One is that of responsibil-
ity, which lies with the programmer. A programmer must ensure that the script the user
executes is not malicious. The second responsibility falls to the users themselves. Users
should make the ultimate decision whether to run a script on their systems—this is
something that must be implemented in the browser’s functionality.
Because of these potentially destructive situations, there are various levels of security
that users and programmers can rely on when programming in JavaScript. As dis-
cussed, some are the responsibility of the programmer, whereas others involve mea-
sures put in place by the browser that allow the user to control what is executed on his
system.

What Security Measures Are in Place?


When JavaScript 1.0 was released in the Navigator 2.0, Internet Explorer 3.0 (JScript
1.0), and Opera 3.0 browsers, the only real security layer was that of a user having the
ability to turn JavaScript on or off. The browser itself controlled the runtime environ-
ment for the language and any security measures it had in place.
In this model, when JavaScript was enabled, it was up to the browser to protect the user
from any harmful code. Originally, this seemed like a thorough plan for implementing
03 0672321416 CH01 7/24/01 11:48 AM Page 19

Security 19

security. Leave it to the experts to protect the users. However, where there is a will
there is a way, and the first misuses of JavaScript began to surface.
One of the first items that seemed to be a potential problem occurred when frames were
used on a Web site. Because frames load separate documents in each of the predefined
areas, it is possible to load documents from several different domains and servers to
make up the content displayed to the user. The problem arose when a document’s
JavaScript variables from one server were available for examination and modification
on another. But this was only the start of the potential security holes that would follow.
To help protect users from the frame problem, Navigator 2, Internet Explorer 3, and
Opera 3 implemented the Same Origin Policy. This policy prevented JavaScript code
sent from one server from accessing properties of a document sent from another server,
port, or protocol and returning that information to its original server.
Obviously, this policy does not affect all the elements of a given document, but it does
include a core set. At the time of this printing, the document properties that must pass
this origin check are in Table 1.1.

Table 1.1 Document Objects That Must Pass Origin Verification


Object Property/Method
document Read/Write: anchors, applets, cookie, domain, elements,
embeds, forms, lastModified, length, links, referrer, title,
URL, each form instance, each Java class available to
JavaScript via LiveConnect
Write: all other
image lowsrc, src
layer src
location all except location.X and location.Y
window find

Because it might be desirable for a script to access variables located on a page served
from another server within the same domain, there is an exception to this security
model. By definition, it would not be possible to access and upload document proper-
ties in a frame served from http://myscripts.purejavascript.com from another
frame that was delivered from http://mydocs.purejavascript.com. Even though the
domain is the same, the complete URL is not.
To get around this minor situation, programmers can set the document.domain prop-
erty to the suffix of the current domain. This will allow them to access JavaScript prop-
erties on pages served from other servers within their domain. Following the example
in the last paragraph, using the following line in the code can enable this feature:
document.domain = “purejavascript.com”;

Setting this property will allow you to access the other sub-domains within your
domain.
03 0672321416 CH01 7/24/01 11:48 AM Page 20

20 Chapter 1: What Is JavaScript to a Programmer?

Data Tainting
When JavaScript 1.1 was released in Navigator 3.0, Netscape furthered its security
implementation by using what is referred to as data tainting. In addition to the security
model in the first generation JavaScript browsers, data tainting allowed the user and
programmer to specify if they wanted scripts to access properties in other documents
from other servers. When data tainting is not enabled, which is the default, the user will
get a message saying that accessing document properties from other servers is not
allowed.

NOTE
Data tainting was only implemented in JavaScript 1.1, and because the majority of
users are now using browsers that support language versions higher than this, it is
recommended not to use this security approach. However, this section is relative to
understand some of the history of security within JavaScript, as well as answer
some questions for anyone having to create code for Navigator 3 browsers.

Users can enable tainting if they want scripts on a page to have global access to other
scripts and document properties. This is a security risk, but might be necessary within
an enterprise environment in which other security measures are in place. To enable data
tainting, environment variables must be set for the browser running the scripts. Table
1.2 shows how this can be accomplished on the various operating systems.

Table 1.2 How to Enable Data Tainting for Your Navigator Browser
Operating Environment Variable Notes
System
Windows NS_ENABLE_TAINT=1 Set this in the autoexec.bat for all
Windows systems.
UNIX NS_ENABLE_TAINT=1 Depending on which shell you are
in, you will use some form of set
env or env to set this variable.
Macintosh Remove the two This can be found by
ASCII slash (//) editing the resource with
comments before type Envi and number 128
the NS_ENABLE_TAINT in the Navigator
application itself. It
should be near the end.
OS/2 NS_ENABLE_TAINT=1 Set this in the config.sys.

After this variable is set, a number of document properties are affected. Table 1.3 shows
a list of the document objects that are tainted by default.
03 0672321416 CH01 7/24/01 11:48 AM Page 21

Security 21

Table 1.3 Document Objects That Are Tainted by Default


Object Tainted Property
document cookie, domain, forms, lastModified, links, referrer, title,
URL
Form action, name
each Form instance checked, defaultChecked, defaultValue, name, selected,
selectedIndex, text, toString, value
history current, next, previous, toString
image name
Link hash, host, hostname, href, pathname, port, protocol, search,
toString
location hash, host, hostname, href, pathname, port, protocol, search,
toString
Option defaultSelected, selected, text, value
Plugin name
window defaultStatus, > name, status

TIP
As a programmer, you can test to see if the Navigator 3 user has tainting enabled
by using the navigator.taintEnabled() method. See this entry in Chapter 8,
“Client-Side” for an example of using this method.

In addition to the user having the ability to specify how he wants to handle tainting, a
programmer can specify, or taint, objects or information that cannot be passed from
one script to the next without the user’s permission. When this occurs, the browser will
pop up a dialog box that allows the user to decide whether the information can be
passed.

NOTE
For more information on data tainting, see the Client-Side JavaScript Guide on
Netscape’s DevEdge (http://developer.netscape.com) site. There is an entire
section (“Using Data Tainting in JavaScript 1.1”) in the “JavaScript Security” chap-
ter devoted to security and the concepts of data tainting.

Because data tainting did not provide the true security model JavaScript needed,
Netscape deprecated its functionality in JavaScript 1.2 and replaced it with Signed
Scripts. This is the current and most complete model that has been implemented, and
should be used by JavaScript developer’s moving forward.

Signed Scripts
Signed scripts allow a programmer the ability to gain access, after user authorization,
to restricted information. This model, which was based on the signed objects model in
03 0672321416 CH01 7/24/01 11:48 AM Page 22

22 Chapter 1: What Is JavaScript to a Programmer?

Java, uses LiveConnect and the Java Capabilities API to execute its functionality. Using
this model gives programmers very defined control over what they can and cannot do
on a user’s machine.

TIP
More information on the Java Capabilities API can be found on Netscape’s
DevEdge site at http://developer.netscape.com/docs/manuals/
signedobj/capabilities.

When using this model, you have the ability to sign external JavaScript source files
(called through the src attribute of the <script> tag), event handlers, and code that is
included inline on the page. The actual signing of these scripts is implemented by using
Netscape’s Page Signer tool, which is available at http://developer.netscape.com.
This Page Signer tool allows you to build a JAR (Java Archive) file that includes the
programmer’s security certificate and code. When the browser encounters a <script>
tag that has an archive attribute set, it will go through the proper verification process
before the script is executed. This process involves popping up a Java Security dialog
box that gives the user the ability to grant or deny the rights to the script. The follow-
ing is an example of syntax used on a page that includes a signed script:
<script src=”myScripts.js” archive=”sample.jar”></script>

If the code is inline, the JAR file will contain only the programmer’s certificate. Calling
the appropriate JAR file would then resemble the following, which does not have the
src attribute, and it would have the code between the beginning and ending <script>
tags.
<script archive=”sample.jar” id=”purejs”>
// Your code here
</script>

Even though signed scripts are based on a Java model, there are enough differences in
the languages that make it a bit harder to secure JavaScript code. Unlike JavaScript, a
Java programmer can protect, make private, or make final variables and methods in
their code. This inherently protects them from hackers because these elements cannot
be accessed or changed—the Java language defines them as such.
Some expanded privileges can be accessed through the netscape.
security.PrivilegeManager.enablePrivilege() method, which gives more control
in scripting. This Java method allows a programmer to try to enable one of a set of priv-
ileges by asking the user to accept or reject his access. As with other signed scripts, this
will prompt the user to grant or deny a programmer’s request. The following list shows
the privileges that a programmer can attempt to access for these purposes:
• UniversalBrowserAccess—Allows both reading and writing of privileged data
in browser.
03 0672321416 CH01 7/24/01 11:48 AM Page 23

Advantages of JavaScript 23

• UniversalBrowserRead—Allows the reading of privileged data in browser.


This is required when using an about: (but not about:blank), getting any
property of the history object, or getting the value of the data property of a
DragDrop event within your scripts.
• UniversalBrowserWrite—Allows the writing of privileged data in browser.
This is required when setting any property of an event object, adding or
removing any of the browser’s bars (location, menu, status, and so on), as well
as using several of the methods and setting some of the properties of the
Window object within your scripts.
• UniversalFileRead—Allows the script to read files on the file system of the
machine on which it is running. This is required when using a file upload
within your scripts.
• UniversalPreferencesRead—Allows the script to read browser preference set-
tings.
• UniversalPreferencesWrite—Allows the script to write browser preference
settings.
• UniversalSendMail—Allows the script to send mail under the user’s name.
This is required when using a news: or mailto: within your scripts.
JavaScript has quite an extensive list of security measures in place that can be used
by the programmer. However, a programmer should use the security measures in a
manner that maximizes his effectiveness. If this is not done, the scripts are subject to
hacking.
Now that you have an understanding of the security measures in place for JavaScript,
take a look at some of the overall advantages of using the language as a means of
deploying solutions on the Internet or within an enterprise.

Advantages of JavaScript
Up to this point, you might not have seen any big reasons where and why JavaScript
can help you. It is object based, can be interpreted within a browser, and there are secu-
rity measures in place—but the same can be said for Java. Now that browsers support
plug-ins and ActiveX controls, it is possible to design client-side functionality with
more common languages such as C++ or Visual Basic. So what does JavaScript really
give you?
For starters, it is platform independent. This is a major advantage over ActiveX con-
trols and plug-ins because they have to be recompiled and potentially rewritten for the
various platforms out there today. Previous versions of Navigator and the new Netscape
6, for example, run on many different platforms, and even though most of these are var-
ious flavors of Unix, at its core, you would still have to build a control or plug-in for
Windows 16- and 32-bit systems, MacOS, Unix, BeOS, OS/2, and the list goes on.
Also note that flavors of Unix and Linux can run on several types of processors (MIPS,
Intel, PowerPC, and so on), and Windows NT runs on Intel and Alpha machines. This
becomes quite an extensive list of components to maintain if you develop in a platform-
dependant language.
03 0672321416 CH01 7/24/01 11:48 AM Page 24

24 Chapter 1: What Is JavaScript to a Programmer?

Another advantage of JavaScript is that both Netscape and Microsoft Web servers have
built-in interpreters. Both of these companies have implemented this in a different fash-
ion, but, as a Web developer, you still have the ability to use the same language on the
server-side that you do on the client-side. The only real competitor to JavaScript in this
aspect is Java with its Java applet and servlet technology.

Platform Independence
Platform independence is probably the number one reason to use JavaScript within
your applications. True, some environments interpret JavaScript a bit differently, but
the majority of the language is processed the same. The code is interpreted so that you
can write it once and let the execution environment interpret it.
This is a simple concept, but can be a big factor in deciding how to implement an appli-
cation solution. As a programmer, you do not want to have to modify code to work on
different operating systems or recompile for different microprocessors. You want to
write the code once and be done with it. You want to be able to make changes easily
and quickly without having to recompile 10 or 15 times. Let’s face it; you want and
need JavaScript.

Client-Side and Server-Side Versatility


The majority of the discussion so far has focused on using JavaScript on the client-side.
Even with its initial release, JavaScript has also been implemented on the server-side
within the Netscape/iPlanet and Microsoft Web servers. This server-side code contains
many of the same objects and methods as the client-side, but it also has objects specific
to the server environment—objects that allow you to connect to, query, and get results
from a database. All this information is collected and processed before the server sends
the page back to the requesting browser.
By providing this scripting capability on the server, a programmer can now use the lan-
guage to dynamically build pages based on the execution of the server-side scripts it
contains. Server-side JavaScript also can be used to maintain state for users as they
move through a site. This maintaining of state is often implemented as a shopping cart
on commercial sites. As users shop on a given site, server-side JavaScript can be used
to track them and keep selected items in their carts.
Microsoft has also implemented a type of server-side JScript within its Internet
Information Server (IIS). Its implementation is used in Active Server Pages (ASP),
where the ASP filter parses a site’s pages before they are sent back to the requesting
browser. JScript is also a very important language within Microsoft’s .NET initiative,
where developers can use the language to create Web services that operate much the
same as COM objects, but across the Internet. As with Netscape’s implementation, this
allows a Web developer to dynamically build the content of a page before it is sent back
to the browser.

NOTE
Remember that JScript is Microsoft’s equivalent to JavaScript.
03 0672321416 CH01 7/24/01 11:48 AM Page 25

When to Use JavaScript 25

Because of the functionality of these pages, ASP has given developers the ability to use
JScript to call server-side components (such as ActiveX controls), pass the necessary
parameters, and write the results to the screen. This allows a Web site to modularize all
the functionality of building pages with individual components that are responsible for
their specific tasks. JScript is used to handle the requests and results to and from these
modules, and then write the results to the page.

When to Use JavaScript


One of the most important things to know about JavaScript is when to use it. Even
though it provides much needed functionality in many scenarios, often it is simply not
needed. One reason is the fact that JavaScript is not always interpreted the same or cor-
rectly—an important point to remember.
As a programmer, you should be able to write code, no matter how simple or com-
plex, that will be executed correctly. However, there are browsers that have bugs that
prevent JavaScript from working the way it was programmed. Before programming
in JavaScript, you should first try to understand any documented bugs that exist.
Doing so can save you hours of debugging in the long run. You can often find these
bug lists on the Web, so check out our resource section toward the end of this chap-
ter to get started.
Try to determine if you really need to use JavaScript on a given page as well. Ask your-
self whether you are using it to add functionality to the page or just to make its appear-
ance better. JavaScript can do a lot of neat things to a Web page, but, if it causes your
page to break in certain browsers, you should avoid using it. A fine line exists between
what you gain in functionality and what you expose as problems, so be sure to test your
code with as many browsers and platforms as possible.
Depending on programmers’ objectives when using JavaScript, they might be able to
impose browser requirements. If they have stated that their pages only work in
browsers later than Netscape 6 and Internet Explorer 5, it is safe for them to use
JavaScript 1.3 or lower for their scripting needs. This immediately eliminates them
from having to support older browsers, which can save many lines of code. Developers
might not be able to impose these restrictions on a Web site, but it is likely that they
can on Web-based applications.
Overall, programmers should be smart about using the language. They need to evalu-
ate what their objectives are and who their audience is. When these requirements are
defined, they can reverse engineer the project to determine what code they need to
write. This is often a much easier approach than starting with an idea and trying to
make it work in all circumstances.
Now that you’ve taken a quick look at some of the general issues to analyze before
using JavaScript, take a look at what you can do with it. The following sections con-
tain some of the common uses of the language, as as some more complex and specific
uses.
03 0672321416 CH01 7/24/01 11:48 AM Page 26

26 Chapter 1: What Is JavaScript to a Programmer?

Web Page Enhancements


Web page enhancements were the first real use of JavaScript. Any of you who have
been working with the Internet since the release of Netscape Navigator 2 probably
remember those annoying scrolling messages in the status bar of the browser window.
This was one of the first enhancements done using JavaScript. Even though it became
annoying, it definitely caught the eye of users.
Another popular item JavaScript is used for is writing the current date and time to a
page. Some sites write the date and time the document was last modified, whereas oth-
ers write the current date and time. This is widely used on sites that are news related in
which the date of the document is very important to readers.

TIP
Writing the date and time to a page is a perfect item to modularize. If the code is
written as a function, it can be included easily on all your pages and called when
needed. If you are using some kind of browser intelligence on the server side, it
is possible to include this function based on the browser that is requesting the
page. If it can interpret JavaScript, make it part of the page. If it cannot, do not
include it.

A final example of using JavaScript to enhance Web pages is to produce rollover but-
tons. This usually occurs on pages in which the linked images change when a user rolls
over them. It is also possible to program in a down state when a user clicks and holds
their mouse button down on the image. Even though this is a simple enhancement, it
makes a page look and feel more professional. This effect allows a Web site to give the
user the same experience as using his favorite application, be it a Web browser, a word
processor, or a money manager.
These three implementations of JavaScript to enhance Web pages are pretty simple, but
are by no means the limit of what can be done. Many sites have used JavaScript for
advertisements, pop-up navigation windows, page redirects, and validating forms.
Because the language is executed within the browser’s environment and is often used
to complement HTML publishing, there is virtually no limit to what can be done.

TIP
If you want to use JavaScript to enhance your Web pages, don’t make the mistake
of trying to think of something cool you can do with the language. You should try
to reverse engineer it. Think of something cool for your site, and then figure out
how to implement it in JavaScript.

Interactive E-Mail
Interactive e-mail is something that has come about within e-mail applications. It
wasn’t long ago that many of these programs were only able to read text e-mails. These
programs now have the capability to render HTML e-mail within their interface, which
03 0672321416 CH01 7/24/01 11:48 AM Page 27

When to Use JavaScript 27

extends the formatting options a user can exploit. This not only improves the look and
feel of the e-mail, but it also improves the readability of it. If a user wants something
in italic, you can put it in italic.
Because HTML e-mail has become widely used in the Internet community, more and
more e-mail applications are supporting it. In addition to HTML, Netscape and
Microsoft’s most recent e-mail applications support JavaScript within the body of an
e-mail message (assuming that the user has it enabled). This makes it possible for a
user to send HTML e-mails containing JavaScript that is interpreted when the recipi-
ent reads the message.
As a programmer, you need to keep in mind that an e-mail application is not a browser.
Users are very particular about what they experience in their messages, and overuse of
JavaScript could lead to annoying your recipients. JavaScript should be used sparingly
in e-mails. It should be reserved for simple page enhancements such as image and link
rollovers or calling ads within your message. Anything beyond this could cause prob-
lems when the application interprets your scripts.

Web-Based Applications
Web-based applications are probably the most useful instances of JavaScript. They
allow a programmer to set user browser requirements, which in turn gives them a head
start on the version of JavaScript they have at their disposal. This also results in limited
exposure to browser bugs because programmers can define which browsers they sup-
port.
One of the most common uses of JavaScript within Web-based applications seems to
be in controlling forms on a page. This can be anything from checking a user’s values
before submission to dynamically adjusting the values based on user-selected data. By
implementing JavaScript at this level, a programmer is able to reduce the amount of
user error when submitting forms. No more invalid credit card numbers because one
digit too many was entered. No more usernames and passwords submitted as e-mail
addresses, and no more incomplete forms.
JavaScript is also used in more full-blown Web-based applications. These applications
are not necessarily for the common Internet user to experience, but rather are interfaces
to enterprise level applications a company might have purchased. Some of the more
common applications are used for reporting or ad delivery and management. Because
the content on the application’s pages is dynamic and always changing, a developer
usually interfaces the application with a database or system process to build the pages
on-the-fly. Using JavaScript allows developers to verify items before requests are
made, as well as add an appealing look and feel to the application.

Windows Scripting
Microsoft’s Windows Script Host comes with Windows 98, including Windows 2000,
and can be installed in Windows 95 and NT 4 systems. This scripting host is language
independent for ActiveX scripting on Windows 32-bit systems. Language independent
means that a variety of programming languages can be used in conjunction with the
03 0672321416 CH01 7/24/01 11:48 AM Page 28

28 Chapter 1: What Is JavaScript to a Programmer?

host. The reason it’s mentioned in this book is that it natively supports JScript—
Microsoft’s implementation of ECMAScript.

NOTE
In addition to the JScript language, this scripting host also supports Visual Basic
Script (VBScript) as well as other third-party languages such as Perl, REXX, TCL,
and Python.

Using JScript in the scripting host allows an administrator or user to create scripts that
perform various tasks on the operating system. These can be as simple as logon scripts
or can be used to call ActiveX controls to perform more complex tasks. If you work in
the Microsoft Windows environment, you will find this implementation of JScript can
be very helpful.

TIP
For more information on the Windows Script Host, check out Microsoft’s
Developer Network site at http://msdn.microsoft.com/scripting and click
the link to Windows Script Host.

JavaScript Resources
When you program a lot in a particular language, especially one that’s Internet related,
you come across many resources. Additionally, when you program a lot in a particular
language, especially one that’s Internet related, you need many resources. So to con-
clude this introductory chapter, we have included some resources for you. There’s
everything from general information to core documentation and references to news-
groups—all on the JavaScript language and all online.

General Information
One of the most important types of resources in any given language is the general
resource. Even if a book carries comprehensive coverage of a topic, it might not have
conveyed the subject matter in a form that you understood. For this reason, you might
want to study the same topic from a different person’s perspective. Table 1.4 lists some
resources that will allow you to do this.

Table 1.4 General Resources


Resource URL
About.com Focus on http://javascript.about.com/compute/
JavaScript javascript/mbody.htm
DevEdge Online http://developer.netscape.com/tech/
javascript/index.html
Danny Goodman’s http://www.dannyg.com/javascript
JavaScript Pages
03 0672321416 CH01 7/24/01 11:48 AM Page 29

JavaScript Resources 29

Resource URL
JavaScript.com http://www.javascript.com
Developer.com http://developer.earthweb.com/dlink.
index-jhtml.72.1313.-.0.jhtml
Doc JavaScript http://www.webreference.com/js
The JavaScript http://www.starlingtech.com/books/
Workshop javascript
JavaScript World http://www.jsworld.com
Java/JavaScript http://www.dezines.com/dezines/
Resources on the javalinks.html
Internet
Microsoft Developer’s http://msdn.microsoft.com/scripting
Network
Timothy’s JavaScript http://www.essex1.com/people/timothy/
Examples js-index.htm
Using JavaScript and http://www.javaworld.com/javaworld/
Graphics jw-08-1996/jw-08-javascript.html
Using JavaScript’s http://www.javaworld.com/javaworld/
Built-In Objects jw-05-1996/jw-05-javascript.html
Voodoo’s Introduction http://rummelplatz.uni-mannheim.de/
to JavaScript ~skoch/js/script.htm
WebCoder.COM http://webcoder.com
Yahoo! Computers and http://dir.yahoo.com/computers_and_
Internet, Programming internet/programming_languages/
Languages, JavaScript javascript
Open Directory Top, http://dmoz.org/Computers/
Computers, Programming, Programming/Languages/JavaScript
Languages, JavaScript

Reference
Another important resource for any programmer is true reference documentation. This
documentation represents information about that language as defined by standards or
by companies who have built or implemented the language. Table 1.5 includes a list of
online resources for the various reference documents out there today.

Table 1.5 Reference Resources


Resource URL
Ecma-262 (ECMAScript) http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM
Microsoft Scripting http://msdn.microsoft.com/scripting/
Technologies (JScript) default.htm?/scripting/jscript/
techinfo/jsdocs.htm
03 0672321416 CH01 7/24/01 11:48 AM Page 30

30 Chapter 1: What Is JavaScript to a Programmer?

Resource URL
Mozilla.org http://www.mozilla.org/js
Netscape’s Core http://developer.netscape.com/docs/
JavaScript 1.4 manuals/js/core/jsref/index.htm
Reference
Netscape’s Server- http://developer.netscape.com/docs/
Side JavaScript 1.2 manuals/js/server/jsref/index.htm
Reference
Netscape’s Client- http://developer. netscape.com/docs/
Side JavaScript 1.3 manuals/js/client/jsref/index.htm
Reference

Newsgroups
The final resource that we are going to discuss is the old standby—Usenet, or
Newsgroups. Newsgroups are often a very good forum to post questions about prob-
lems and see responses to issues that others are having. It’s global collaboration at its
best and often is an overlooked resource. Table 1.6 lists some of our favorites, so be
sure to check them out before giving up on any project.

Table 1.6 Newsgroup Resources


Server Newsgroup
secnews.netscape.com netscape.public.mozilla.jseng
secnews.netscape.com (Secure) netscape.dev.js-debugger
netscape.dev.jsref
netscape.dev.livewire
netscape.dev.livewire.dbconfig
netscape.dev.livewire.programming
netscape.dev.visual-javascript
netscape.devs-livescript
Public Newsgroups comp.lang. javascript

Moving On
This chapter covers the overview of the JavaScript language. As you can see, JavaScript
is actually a very powerful scripting language that has many advantages. Security fea-
tures are in place, and other implementations of the language make it worth any pro-
grammer’s time to learn.
In the next chapter, you will take a look at the details of the language. Details that will
give you, the programmer, an understanding of how the language deals with operators,
data types, variables, functions, loops, conditionals, as well as how to correctly imple-
ment JavaScript within the body of an HTML document.
04 0672321416 CH02 7/24/01 11:49 AM Page 31

Details of the Language


CHAPTER 2

Details of the Language


For experienced programmers to pick up a new language
quickly, they look for similarities at the core of the new lan-
guage and other languages they have used. These similarities
generally include operators that enable programs to function,
variables that provide memory, and the ability to apply the
same operation to various items. Understanding how to use
these core pieces of the language is essential if you want to
begin programming in JavaScript.
If you have been programming for a long time, you might be
tempted to skip over this chapter. Because JavaScript is still a
young scripting language with some wrinkles to be ironed out,
it is a good idea to understand these instances for backward
compatibility reasons. Taking a little time to make sure that the
core elements perform as you are expecting will save a lot of
programming time in the future.

Things to Know about JavaScript


Syntax
Before getting too deep into the core elements of the language,
there are a few things a programmer should know about
JavaScript syntax. Understanding these points will get you up
and programming in a more timely fashion.

The Semicolon
If you have done any programming in C, C++, or Java, even as
simple as a Hello World program, you already know 75% of all
there is to know about the JavaScript semicolon (;). Just the
same as C and C++, the semicolon is placed at the end of a
JavaScript statement to signify that the code between the
beginning of the line and the semicolon should be executed
04 0672321416 CH02 7/24/01 11:49 AM Page 32

32 Chapter 2: Details of the Language

before moving to the next portion of code. If you forget a semicolon at the end of a line
in C++, you get compile errors, but JavaScript doesn’t complain. Because JavaScript is
a loosely typed language, forgetting a semicolon tells JavaScript to assume that you
intended for one to appear at the end of the line, and it executes your code accordingly.
This does not mean that you should not use semicolons! It is good programming prac-
tice to always include semicolons at the end of a line of code except when dealing with
statements such as for, while, and if.
Although it is good programming practice to have only one functional piece of code
per line, there are times when it is advantageous to put two independent pieces of code
on one line. When this case arises, you must use a semicolon to separate the two pieces
of code. In Listing 2.1, a semicolon is used to separate two independent pieces of vari-
able declaration code that are placed on one line. Notice that semicolons were placed
at the end of each line although JavaScript would do it for you. The result of executing
the code is the phrase, “The sales tax on $5 is $.3”, being displayed in the
browser.

Listing 2.1 Using Semicolons


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

// Declare 2 numeric variables on the same line


var fiveDollars = 5; var salesTax = 0.06;

// Compute the sales tax on 5 dollars and use the


// document.write() function to display the result.
document.write(“The sales tax on $”);
document.write(fiveDollars);
document.write(“ is $”);
document.write(fiveDollars*salesTax);

//-->
</script>
</html>

Using the <script> Tag


The first time a programmer works with a new language, he’ll want to know the key
pieces of syntax needed to start programming. In JavaScript, the HTML <script> tag
is that key piece. <script> tags tell the browser that everything between <script> and
</script> should be interpreted by the interpreter specified in the type attribute. There
is no limit to the number of <script> tags that can be used, as long as they are used in
pairs.
Notice that the browser interprets the code between the <script> tags based on the
type attribute. Because the type attribute has no default value it is important that the
04 0672321416 CH02 7/24/01 11:49 AM Page 33

D a t a Ty p e s a n d V a r i a b l e s 3 3

type attribute be set any time the <script> tag is used. To set the content type to the
most current version of JavaScript supported by the browser, use the format <script
type=”text/javascript”>. It is also possible to force the interpreter to use older ver-
sions of JavaScript (<script type=”text/javascript1.2”>, for example) as well as
other languages such as Microsoft’s JScript (type=”text/jscript”).

NOTE
Before HTML 4, the language attribute of the <script> tag was the only way to
set the scripting language. But as of HTML 4, the language attribute was depre-
cated in favor of the content type attribute discussed above. In order to ensure
backward compatibility, both attributes are specified in the <script> tags
throughout all the code examples in this book.

Comments
JavaScript is very generous with its commenting options by providing the /* */ com-
ment tags from C, the // comment tag from C++, and the <!-- --> tags from HTML.
Just as in C and C++, the /* */ enables comments to span multiple lines by just plac-
ing comments between the two tags. The // comment tag enables comments to be
placed between the // and the end of the line. As mentioned earlier, JavaScript pro-
vides one other comment tag that might not be familiar to you, the HTML <!-- com-
ment. JavaScript interprets this comment the same way it interprets the // characters.
You are probably asking yourself, “Why use two different comment tags that do the
same thing?” Some older browsers that did not understand the <script> tags would
display all the code between the <script> tags as standard HTML text. To prevent this
with non-JavaScript–enabled browsers, <!-- is placed on the line directly below the
<script> tag, and //--> is placed on the line directly above the closing </script> tag.
This causes non-JavaScript–enabled browsers to treat the code between the tags as
HTML comments, but allows browsers with JavaScript interpreters to execute the code.
Examples of this style of commenting can be seen in the examples throughout the
book.

NOTE
The // comment characters have to be placed in front of the HTML --> comment
closer because JavaScript will misinterpret --> as a pre-decrement operator.

Data Types and Variables


Before discussing JavaScript operators, conditionals, and loops, one should understand
JavaScript data types and variables. These are building blocks that will be important
going forward. Fortunately, JavaScript kept its implementation of data types simple and
easy to use, unlike other programming languages. In addition to simple data types, vari-
ables are much easier to work with because there are no restrictions on the types of val-
ues they can hold.
04 0672321416 CH02 7/24/01 11:49 AM Page 34

34 Chapter 2: Details of the Language

Numbers
JavaScript’s approach to numbers is different from other languages because every num-
ber is treated as a floating-point number. JavaScript does support integers, octals, and
hexadecimals from a formatting perspective, but, at the lowest level, JavaScript sees
numbers as floating-point numbers. The following sections discuss different formats
that numbers can have at the higher level.

Integers
Integers are numbers that contain no fractional parts, can be positive or negative, and
can be formatted as a decimal, octal, or hexadecimal in JavaScript. Because integers
are actually floating-point numbers in JavaScript, it is possible for the numbers to be
very large.
• Decimal integers, also referred to as base 10, are probably the most common
numerical values programmers use in their code. This type of integer is made
up of numbers from 0 to 9 and cannot begin with leading zeros.
• Octal integers, also referred to as base 8, are a little different from decimal inte-
gers in that they must begin with a leading zero. Each digit following the lead-
ing zero can be 0 to 7.
• Hexadecimal integers, also referred to as base 16, must begin with 0x or 0X.
Each digit following the leading zero can be 0 through 15, but 10 through 15
are represented by the letters a (or A) through f (or F).

Floating-Point Numbers
Unlike the integer, floating-point numbers can contain fractional parts and can use
exponential notation for added precision. Floating-point numbers are made up of a dec-
imal integer followed by a period (.) and the fractional portion of the number.
Exponential notation can be used by adding an e or E to the end of a floating-point
number followed by a decimal integer that does not exceed three digits. This tells
JavaScript to multiply the floating-point number by 10 to the exponent of the number
following the e.

Built-in Values
Because computer programs are often used to solve scientific problems, the programs
must know many of the numerical constants that are used in math and science. To make
programming easier for you, JavaScript has included some of the more commonly used
numerical constants in the Math object, which are shown in Table 2.1.

Table 2.1 Numerical Constants Provided by JavaScript


Math Constant Description
Math.E Base of natural logarithms
Math.LN2 Natural log of 2
Math.LN10 Natural log of 10
Math.LOG2E Base 2 log of e
04 0672321416 CH02 7/24/01 11:49 AM Page 35

D a t a Ty p e s a n d V a r i a b l e s 3 5

Math Constant Description


Math.LOG10E Base 10 log of e
Math.PI Pi
Math.SQRT1_2 Square root of 1/2
Math.SQRT2 Square root of 2

Special Values
JavaScript also provides some special values that are common in the mathematical
world but not so common in the computer world. These special values are available
through the Number object, as shown in Table 2.2.

Table 2.2 Special Numerical Values


Number Constant Description
Number.MAX_VALUE Largest representable number
Number.MIN_VALUE Smallest representable number
Number.NaN Not a number
Number.POSITIVE_INFINITY Positive infinity
Number.NEGATIVE_INFINITY Negative infinity

Strings
Strings provide programs a voice with which to communicate. It would be inconceiv-
able to create a programming language today that did not use strings because they are
so important.

JavaScript Strings
In the world of C and C++, dealing with strings is like having to go to the dentist—
dreaded! Dealing with strings in JavaScript is like going to a big candy store. A string
is made up of any number of characters or a lack of characters. Strings are declared by
placing the characters that make up the string between a pair of double quotes (“ “) or
single quotes (‘ ‘). What if a string contains double quotes or single quotes? No prob-
lem. JavaScript interprets single quotes as part of the string if the single quotes are
inside a pair of double quotes. Likewise, double quotes are considered part of the string
if they appear between a pair of single quotes. If single quotes are your only option for
declaring a string that contains single quotes, or if double quotes must be used to
declare a string that contains double quotes, you will you need to use escape sequences
(see the next section, “Special Characters”).

Special Characters
Just as in C and C++, escape sequences, which are noted by a backslash character (\),
allow special characters that cannot normally be stored in a string to be declared. Table
2.3 lists all the possible escape characters.
04 0672321416 CH02 7/24/01 11:49 AM Page 36

36 Chapter 2: Details of the Language

Table 2.3 Escape Sequences and Their Associated Characters


Escape Sequence Character
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\’ Single quote
\” Double quote
\\ Backslash
\XXX Character represented by three octal digits XXX (000 to
377)
\XX Character represented by two hexadecimal digits XX
(00 to FF)
\uXXXX Unicode character represented by four hexadecimal
digits XX (0000 to FFFF).

Other Data Types


Outside of the world of computers, there are uncertainties and indefinable values that
we come in contact with daily. When computer programs are written to simulate the
world we live in, they must handle uncertainties and values that have no definition.
JavaScript provides some special data types to handle these situations.

Boolean
The Boolean data type is much simpler than any of the other data types because it has
only two possible values: true and false. Sometimes it is easier to think of true as on
or yes and false as off or no when working with some expressions that use the Boolean
data type. In JavaScript, true and false are often represented by 1 (true) and 0
(false).

null
JavaScript provides the keyword null for representing a condition in which there is no
value. In some languages, null and 0 are considered the same value, but JavaScript
sees null and 0 as two completely different values.

Undefined Values
At this point, you might be thinking that undefined and null are essentially the same,
but this is not true. In fact, undefined is a concept rather than a keyword like the null
data type. Undefined is equivalent to NaN for numbers, the string undefined for strings,
and false when dealing with Boolean values.

What to Know About Variables


Computer programs would not do much if they did not have some type of temporary
memory. Variables provide a way for data to be stored during the execution of a
04 0672321416 CH02 7/24/01 11:49 AM Page 37

D a t a Ty p e s a n d V a r i a b l e s 3 7

program. Some languages, such as C and C++, impose many restrictions on how vari-
ables are used, but JavaScript keeps variables simple and easy to use.

Naming Variables
One of the keys to writing great code is to use variable names that help you, and pro-
grammers that modify your code, remember what data is stored in the variable. Before
beginning to think of great variable names, remember the following guidelines
imposed on variable names by JavaScript:
• The first character of the name must be a letter or an underscore (_).
• All characters following the first character can be letters, underscore, or digits.
• Letters can be either upper- or lowercase. JavaScript does distinguish between
the two cases. For example, a variable called jobTitle is different from a vari-
able called JOBtitle.

Assigning Values
When the perfect variable name has been derived, it is time to declare that variable and
assign it a value. To declare a variable, use the keyword var followed by the variable
name. Some programmers prefer to keep their code compact by declaring multiple
variables using the same var statement. When this is the case, the variable names are
separated by commas. At this point, the variable is undefined because no value has
been assigned to it. Keep in mind that undefined is a special JavaScript value.
Now that the variable is declared, a value can be assigned to it using the assignment
operator (=). In many cases, the declaration and assignment steps are performed in one
step. If a value is assigned to a variable that has not been declared using the var key-
word, JavaScript will automatically create a global variable. Listing 2.2 demonstrates
the ways variable declaration and assignment can be performed. The code displays the
sentence “James is 49 and 6 feet tall.” in the browser window.

Listing 2.2 Variable Declaration and Assignment


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Variable declaration without assignment


var firstName;

//Variable assignment without declaration


firstName = “James”;

//Variable declaration and assignment


var age = 49, height = 6;

//Display the results


document.write(firstName,” is “,age,” and “,height,” feet tall.”);
04 0672321416 CH02 7/24/01 11:50 AM Page 38

38 Chapter 2: Details of the Language

Listing 2.2 Continued


//-->
</script>
</html>

TIP
Always use the var keyword to declare all variables to prevent variable scope prob-
lems.

Scope
A variable can be either global or local in JavaScript. All variables are global unless
they are declared in a function; in which case the variable is local to that function. It is
possible for two variables with the same name to exist if one is global and the other is
local to a function. When accessing the variable from within the function, you are
accessing the local variable. If the variable is accessed outside the function, the global
variable is used (see Listing 2.3).

CAUTION
Always use the var keyword to declare local variables in functions. Without var,
JavaScript will create a global variable.

Listing 2.3 Variable Scope Example


<html>
<h2><u>Computer monitor specifications</u></h2>

<script type=”text/javascript” language=”JavaScript”>


<!--

//Initialize global variables


color = “green”;
var size = 15;

//Declare a monitor specification function


function monitorSpecs()
{
//Declare and set variables inside function
color = “purple”;
price = “$300.00”;
var size = 17;
document.write(“The “,size,” inch “,color);
document.write(“ monitor is “,price);
}

//Display results of monitorSpecs() function


monitorSpecs();
04 0672321416 CH02 7/24/01 11:50 AM Page 39

D a t a Ty p e s a n d V a r i a b l e s 3 9

//Display variable values outside of function


document.write(“<br>The “,size,” inch “,color);
document.write(“ monitor is “,price);

//-->
</script>
</html>

The results of running this script within the body of an HTML document can be seen
in Figure 2.1. The code begins by declaring two global variables, color and size. The
monitorSpecs() function creates a new variable called size that only exists within the
scope of the function. Because the function did not specify var, the global variable
color was changed from green to purple. In addition, a new global variable, price,
was declared within the function because the word var was not used.

Figure 2.1
The 17-inch monitor has the same color price due to the use of global variables.

Type Conversion
In languages such as C and C++, type conversion is very important and complicated,
but, in JavaScript, type conversion is effortless. Unlike other languages, JavaScript
allows a variable to hold any data type at any time. This means that a variable can be
assigned a string initially, but then could later contain a integer. JavaScript also
attempts to perform all necessary type conversions for you, such as strings to numbers
and numbers to strings.

Arrays
Arrays enable programmers to store multiple data, based on a numbered position
called an index, into one storage structure. The numbering of the index always starts at
0 and goes up. Also, JavaScript supports having arrays within arrays, called multi-
dimensional arrays.
The implementation of arrays in JavaScript has been changing ever since JavaScript
was introduced. The original implementation of arrays in JavaScript 1.0 was not really
an array at all but rather JavaScript objects with multiple property settings. A true
Array object was added in JavaScript 1.1, and additional features added in following
versions. Today, arrays are very robust and full featured, but, because of their chang-
ing past, you should spend some time digging into the history of arrays as they apply
to JavaScript versions. You will begin by understanding how arrays work in the latest
04 0672321416 CH02 7/24/01 11:50 AM Page 40

40 Chapter 2: Details of the Language

versions of JavaScript and then go back and learn how arrays were created in.
JavaScript 1.1

One-Dimensional
To create an instance of an array, you must use the new operator along with the Array
object. There are four ways to declare an array. First, an empty array that contains no
elements can be created by leaving the constructor parameters empty as shown in the
following JavaScript statement:
var x = new Array();

The second way to create an array is to fill in the constructor parameters with the array
elements. One of the nice things about JavaScript arrays is that an array can contain
elements of various types. For example, the following JavaScript statement creates an
array that contains three strings, “red”, “yellow”, and “green”, as well as the integers
1, 5, and 8:

var x = new Array(“red”,”yellow”,”green”,1,5,8);

The third way to create an array is to fill in the constructor parameter with just the size
of the array. This causes the array to be initialized to hold the number of elements spec-
ified, but does not specify the actual elements. For example, the following JavaScript
statement creates an array that can hold 6 elements.
var x = new Array(6);

NOTE
The var x = new Array(n); format, described previously, is not recognized by
JavaScript 1.2, so the number specified in the constructor parameter is stored as
an element in position 0.

The fourth, and quickest, way to create an array is to use the standard array square
brackets to fill in the array elements directly:
var x = [“red”,”yellow”,”green”,1,5,8];

After an array has been created, it can be written to and read from using the [] opera-
tor. By placing a position number in this operator, the data stored at this index can be
accessed and even overwritten.

String Indexes
So far, you have only accessed elements in arrays via the numerical index, but it is
possible to index arrays using strings. To access an element, a string index value is
placed into the [] operator. Listing 2.4 demonstrates the use of strings as indexes for a
clothing store’s product quantity array. Figure 2.2 displays the clothing store’s current
inventory of products.
04 0672321416 CH02 7/24/01 11:50 AM Page 41

D a t a Ty p e s a n d V a r i a b l e s 4 1

Listing 2.4 Using Strings for Array Indexes


<html>
<h2><u>Clothing Store Inventory</u></h2>

<script type=”text/javascript” language=”JavaScript”>


<!--

//Populate an array with product quantities


function populateArray(products)
{
products[“shirts”]=46;
products[“pants”]=23;
products[“hats”]=14;
products[“socks”]=153;
}

//Display product quantities


function displayArray(products)
{
document.write(products[‘shirts’],” shirts.<br>”);
document.write(products[‘pants’],” pants.<br>”);
document.write(products[‘hats’],” hats.<br>”);
document.write(products[‘socks’],” pairs of socks.”);
}

//Create a product quantity array


var productQty = new Array();

//Set product quantities


populateArray(productQty);

//Display the product quantities


displayArray(productQty);

//-->
</script>
</html>

Figure 2.2
The clothing store’s current inventory of products is displayed using string indexes to
access arrays.
04 0672321416 CH02 7/24/01 11:50 AM Page 42

42 Chapter 2: Details of the Language

Length
Unlike arrays in C and C++, JavaScript allows the size of an array to change dynami-
cally at any time. For example, it is possible to write directly to a position that was not
even declared using the [] operator. The length of the array can also be changed by
altering the length attribute of the Array object. If the length of an array is originally
10 and is reduced to 5 by changing the value stored in the length attribute, the ele-
ments in position 5 through 9 are lost.
One of the advantages to using the Array object is the methods it provides to manipu-
late and access itself. Table 2.4 lists some of the methods that are currently available in
the Array object. Details of these methods can be found in Chapter 7, “Core
Language,” in the “Array” section.

Table 2.4 Methods Available in the Array Object


Method Description
join() Concatenates all elements into one string
reverse() Reverses the order of the elements in the array
sort() Sorts elements in array
concat() Concatenates an array on to an array
slice() Returns a subsection of the array
splice() Inserts and removes elements from an array
push() Adds elements to the end of an array
pop() Deletes the last element from an array
unshift() Adds elements to the front of an array
shift() Deletes elements from the front of an array
toString() Converts elements to a string

Multidimensional
To create multidimensional arrays in JavaScript, the element of an array must be
another array. The inner array can be accessed by putting two [] operators back to
back. Listing 2.5 uses a multidimensional array to hold an inventory list of brake parts.
As seen in Figure 2.3, the brake parts list is accessed by using double [] operators and
displayed in a table.

Listing 2.5 Using a Multidimensional Array


<html>
<h2><u>Brake Parts Inventory List</u></h2>

<script type=”text/javascript” language=”JavaScript”>


<!--

//Display brake part inventory in a table


function displayInventory(table)
{
document.write(“<table border=on>”);
04 0672321416 CH02 7/24/01 11:50 AM Page 43

D a t a Ty p e s a n d V a r i a b l e s 4 3

document.write(“<th>Item Number</th><th>Item Name</th>”);


document.write(“<th>Model Number</th><th>Quantity</th>”);
//Display each part
for(x=1; x<=3; x++)
{
document.write(“<tr><td>”,x,”</td>”);
//Display all information for each part
for(y=0; y<=2; y++)
{
document.write(“<td>”,table[x][y],”</td>”);
}
document.write(“</tr>”);
}
document.write(“</table>”);
}

//Create a brake parts inventory list using a


//multidimensional array
part1 = new Array(“Brake Pads”,”39D48G”,78);
part2 = new Array(“Brake Shoes”,”7D9UK3”,45);
part3 = new Array(“Rotors”,”97WOST”,”14”);
brakeParts = new Array(“”,part1,part2,part3);

//Display the inventory of brake parts


displayInventory(brakeParts);

//-->
</script>
</html>

Figure 2.3
Using a multidimensional array to display the inventory list of brake parts.

Arrays as Objects
Because arrays are essentially JavaScript objects, it is possible to access the elements
of arrays as properties if a string index is used. Dot notation is used, rather than the []
operators. For example, the clothing store example, in Listing 2.4, could have been
04 0672321416 CH02 7/24/01 11:50 AM Page 44

44 Chapter 2: Details of the Language

created using properties as shown in Listing 2.6. Notice how the [] operators and dot
notation are used interchangeably when accessing the contents of the array. The result
of executing the code is the same as previously shown in Figure 2.2.

Listing 2.6 Accessing Array Properties


<html>
<h2><u>Clothing Store Inventory</u></h2>

<script type=”text/javascript” language=”JavaScript”>


<!--

//Populate an array with product quantities


function populateArray(products)
{
products.shirts=46;
products.pants=23;
products[“hats”]=14;
products[“socks”]=153;
}

//Display product quantities


function displayArray(products)
{
document.write(products[‘shirts’],” shirts.<br>”);
document.write(products[‘pants’],” pants.<br>”);
document.write(products.hats,” hats.<br>”);
document.write(products.socks,” pairs of socks.”);
}

//Create a product quantity array


var productQty = new Array();

//Set product quantities


populateArray(productQty);

//Display the product quantities


displayArray(productQty);

//-->
</script>
</html>

JavaScript 1.0 Arrays


As mentioned earlier, JavaScript originally used the Object() constructor to create
arrays in JavaScript 1.0. Because the properties of an Object() could be accessed by
using the [] operator, it was possible to give the illusion of an array.
To create an array using this concept, a new object is created using the Object() con-
structor. Once created, elements can be assigned to the object using the [] operators.
04 0672321416 CH02 7/24/01 11:50 AM Page 45

Operators 45

Because this is just a basic object, the programmer is responsible for keeping track of
the length of the array. The easiest way to remember the length is to create a property
called length. Unfortunately, properties use the same positions that are accessed by the
[] operator, so the length property would actually be array position 0.

Listing 2.7 demonstrates how to create an array representing a toolbox using the
Object() constructor. The code displays the sentence “The toolbox holds: hammer
wrench nails” in the browser window.

Listing 2.7 Creating Arrays in JavaScript 1.0


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Create a toolbox array using the Object() constructor


var toolbox = Object();
toolbox.length=3; //array position zero
toolbox[1]=”hammer”;
toolbox[2]=”wrench”;
toolbox[3]=”nails”;

//Display the items in the toolbox.


document.write(“The toolbox holds: “);
for(x=1; x<=toolbox.length; x++)
{
document.write(toolbox[x],” “);
}

//-->
</script>
</html>

Operators
JavaScript provides most of the common operators that can be found in other pro-
gramming languages. Because of JavaScript’s way of handling strings, some of these
operators are a bit easier to use than in other languages.

Arithmetic
Just the same as other programming languages, JavaScript allows many arithmetic
operations. These operations include the common addition and subtraction that all pro-
grammers use as well as the less common modulus and incremental.

NOTE
All the common arithmetic operators will attempt to convert strings to numbers
when applicable. If a string cannot beconverted to a number, NaN (Not A
Number) will be returned.
04 0672321416 CH02 7/24/01 11:50 AM Page 46

46 Chapter 2: Details of the Language

Those who have programmed in other languages will find that JavaScript is very robust
in its support of operators and mathematical functions. This is not only because of the
built-in operators, but also because of the access to advanced mathematical operations
that are provided through the Math object. The functions of this object are shown in
Table 2.5 and are covered in Chapter 7.

Table 2.5 Advanced Mathematical Methods


Method Description
Math.abs() Absolute value
Math.acos() Arc cosine
Math.asin() Arc sine
Math.atan() Arc tangent
Math.atan2() Arc tangent
Math.ceil() The smallest integer that is greater than or equal to a
number (ceiling).
Math.cos() Cosine
Math.exp() Natural exponent
Math.floor() The largest integer that is equal or less than a number
(floor).
Math.log() Natural logarithm
Math.max() The larger of two numbers
Math.min() The smaller of two numbers
Math.pow() Power of
Math.random() Random number
Math.round() Round
Math.sin() Sine
Math.sqrt() Square root
Math.tan() Tangent

Addition
The addition operator (+) is, of course, one of the most widely used and common oper-
ators. If the values on either side are numerical values, the values are added together.
When the values are strings, they are concatenated together. The following line of code
var resultOfAdd = 34 + 12;

would set the variable resultOfAdd equal to 46, whereas this line of code
var resultOfAdd = “a” + “corn”;

would set the variable resultOfAdd equal to the string “acorn”.

Subtraction
The subtraction operator (-) subtracts the number to the right of the operator from the
number on the left. When either of the operands are strings, an attempt is made to con-
vert the strings to numbers. For example, the following lines of code
04 0672321416 CH02 7/24/01 11:50 AM Page 47

Operators 47

var aNum = String(“102”);


var resultOfSub = 25 - aNum;

convert the string stored in aNum to a number before performing the subtraction opera-
tion. The result of the subtraction (-77) is then stored in the variable resultOfSub.

Multiplication
The multiplication operator (*) works the same as it would in any other language by
multiplying the left operand by the right operand. The multiplication operator is no dif-
ferent from subtraction in its efforts to handle strings. If either of the values is a string,
an attempt is made to convert the string to a number. For example, the following lines
of code
var aNum = String(“7”);
var resultOfMult = 5 * aNum;

convert the string stored in aNum to a number before performing the multiplication
operation. The result of the multiplication (35) is then stored in the variable
resultOfMult.

Division
The division operator (/) is the operator that, although simple, can be confusing when
you have been writing code all day and your senses are dulled. You ask yourself,
“Which number divides into the other?” Reading the expression from left to right, the
left value is divided by the right value. As before, if either of the operands is a string,
an attempt is made to convert the string to a number. For example, the following lines
of code
var aNum = String(“7”);
var resultOfDiv = 42 / aNum;

convert the string stored in aNum to a number before performing the division operation.
The result of the division (6) is then stored in the variable resultOfDiv.

Modulus
Although the modulus operator (%) is not used as often as some of the other operators,
I am always excited when I do get to use it because it usually means I am performing
a neat math trick. This operator starts similar to the division operator, by dividing the
left value by the right, but, instead of returning the normal result of division, only the
remainder is returned by the operation. Once again, if either value is a string, an
attempt is made to convert the string to a number. For example, the following lines of
code
var aNum = String(“3”);
var resultOfMod = 26 % 3;

convert the string stored in aNum to a number before performing the modulus operation.
The remainder of 2 is then stored in the variable resultOfMod.
04 0672321416 CH02 7/24/01 11:50 AM Page 48

48 Chapter 2: Details of the Language

Pre-Increment
The pre-increment operator (++) combines two very common steps that programmers
use over and over again into one, thus making code more concise and readable. This
operator is especially handy when working with for loops. In your code, the pre-
increment operator is placed directly before the variable to be incremented. The oper-
ation begins by incrementing the variable by 1. The new incremented value is returned
by the operation to be used in another expression. If the variable is a string, it is con-
verted to a number. For example, the following segment of code
//The price is $5.00 dollars
var price = String(“5”);

//Add the shipping rate ($3.00 dollars) to the price after incrementing price
var pricePlusShipping = (++price) + 3;

converts the string stored in price to a number before performing the pre-increment
operation. The pre-increment operation results in the variable price being changed
from 5 to 6 dollars, and the value of 9 dollars is stored in the variable
pricePlusShipping.

Post-Increment
The post-increment operator (++) has the same operator as the pre-increment operator
but it behaves differently based on its position. First, the post-increment operator
appears directly after the variable that is to be incremented. Unlike the pre-increment
operator, the post-increment operator returns the original value before it is incremented
by 1. If either of the values is a string, an attempt is made to convert the string to a
number. For example, the following segment of code
//The price is $5.00 dollars
var price = String(“5”);

//Add the shipping rate ($3.00 dollars) to the price before incrementing price
var pricePlusShipping = (price++) + 3;

converts the string stored in price to a number before performing the post-increment
operation. The post-increment operation causes the variable price to be changed from
5 to 6 dollars but the original price of 5 dollars is added to the shipping rate resulting
in the value of 8 dollars being stored in the variable pricePlusShipping.

Pre-Decrement
The pre-decrement operator (--) is very similar to the pre-increment operator in its
placement to the left of a variable and its order of execution. But there is one key dif-
ference between the operators: the pre-decrement operator decrements the value by 1.
Once again, if the variable is a string, it is converted to a number. For example, the fol-
lowing segment of code
//The price is $20.00 dollars
var price = String(“20”);
04 0672321416 CH02 7/24/01 11:50 AM Page 49

Operators 49

//Subtracted discount ($6.00 dollars) from the price after decrementing price
var priceMinusDiscount = (--price) - 6;

converts the string stored in price to a number before performing the pre-decrement
operation. The pre-decrement operation would result in the variable price being
changed from 20 to 19 dollars, and the value of 13 dollars being stored in the variable
priceMinusDiscount.

Post-Decrement
The post-decrement operator (--) is very similar to the post-increment operator in its
placement to the right of a variable and its order of execution. But, as the name implies,
the post-decrement operator decrements the value by 1. If the variable is a string, it is
converted to a number. The following segment of code
//The price is $20.00 dollars
var price = 20

//Subtract the discount ($6.00 dollars) from the price before decrementing
price
var priceMinusDiscount = (price--) - 6;

converts the string stored in price to a number before performing the post-decrement
operation. The post-decrement operation causes the variable price to be changed from
20 to 19 dollars but the original price of 20 dollars is used to calculate the value of 14
dollars that is stored in the variable priceMinusDiscount.

Unary Negation
The unary negation operator (-) is usually used when performing a mathematical equa-
tion in which a number needs to be changed from positive to negative or vice versa.
When negating a variable, keep in mind that the contents of the variable do not change,
only the value returned is negated. As with all the other operators, if the value is a
string, an attempt is made to convert the string to a number. For example, the follow-
ing segment of code
var aNumber = String(“67”);
var resultOfNeg = -aNumber;

converts the string stored in aNumber to a number before performing the negation oper-
ation. The result of negation on the number results in the value of -67 being stored in
the variable resultOfNeg.

String
The addition operator (+) has a special purpose when dealing with strings. If the values
on either side of the addition operator are strings, the strings are concatenated together.
If only one of the values is a string, the other value is converted to a string and con-
catenated with the first value. To help understand these various combinations of apply-
ing the addition operator to numeric and string values, see Listing 2.8.
04 0672321416 CH02 7/24/01 11:50 AM Page 50

50 Chapter 2: Details of the Language

Listing 2.8 Using the Addition Operator on Numeric and String Values
<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

// Declare 2 numeric variables and 2 string variables


var sStringVar1 = “Hello”;
var sStringVar2 = “World”;
var nNumVar1 = 5;
var nNumVar2 = 10;

// Apply the addition operator to create 3 totals


var sStringTotal = sStringVar1 + sStringVar2;
var nNumTotal = nNumVar1 + nNumVar2;
var sStringNumTotal = sStringTotal + nNumTotal;

// Use the document.write() function to write the totals to the page


// Notice that we even use the addition operator in place of a comma
// to concatenate the results with some text on the page.
document.write(“<b>The string total is: </b>”+sStringTotal+”<br>”);
document.write(“<b>The numeric total is: </b>”,nNumTotal,”<br>”);
document.write(“<b>The string + numeric total is: </b>”,sStringNumTotal);

//-->
</script>
</html>

The results of running this script within the body of an HTML document can be seen
in Figure 2.4. As the figure shows, when the addition operator is applied to two strings
or a string and a numeric value, a string concatenation occurs. As expected, when
applying this operator to the two numeric values, the numbers are added.

Figure 2.4
Using the addition operator to add numbers and concatenate strings.

Assignment
What good are variables if data cannot be assigned to them? Similar to all languages,
JavaScript provides assignment operators to allow data to be stored in variables. The
basic format of the assignment operator is shown in the following example, where a
value of 6 is assigned to the variable x:
x = 6;
04 0672321416 CH02 7/24/01 11:50 AM Page 51

Operators 51

In addition to this one-to-one assignment, this operator can also be stacked to create
simultaneous assignments. Simultaneous means that several variables can be assigned
at once. This is demonstrated in the following example, where variables x, y, and z all
contain the value of 6:
x = y = z = 6;

Anytime multiple assignment operators occur in the same expression, they are evalu-
ated from right to left. So in the previous example, z would be assigned the value 6
first. After the assignment has been made, y would be assigned the value stored in z
and, finally, x would be assigned the value stored in y. The overall effect is that all three
variables would be assigned a value of 6.
Because the assignment operator is an operator, similar to addition (+) or subtraction
(-), it can be used within an expression. This enables a programmer to perform an
assignment and evaluate a mathematical expression all in one step.
y = (x = 3) + 4;

In the preceding example, the value 3 is assigned to the variable x, which is then added
to the value 4 and assigned to the variable y. After the expression is fully evaluated, y
will contain the value 7. This enables programmers to accomplish three operations at
once. They are able to assign a value to the x variable, perform addition, and assign the
result to the y variable. Features such as this help make JavaScript very versatile and
easy to use.
Now that you have looked at how the assignment operator works, look at a more
detailed example—one that performs each of the assignments discussed, as well as
some more complex ones. Listing 2.9 contains such an example, and Figure 2.5 shows
the result.

Listing 2.9 Use of the Assignment Operators in JavaScript


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

// Declare variables using single assignment


x = 3;
y = 7;
z = 9;

//Display the values stored in the variables after single assignment


document.write(“<u>After single assignment</u><br>”);
document.write(“x=”,x,”<br>y=”,y,”<br>z=”,z,”<br>”);

//Perform multiple assignment on variables


x = y = z = 14;
04 0672321416 CH02 7/24/01 11:50 AM Page 52

52 Chapter 2: Details of the Language

Listing 2.9 Continued


//Display the values stored in the variables after multiple assignment
document.write(“<u>After multiple assignment</u><br>”);
document.write(“x=”,x,”<br>y=”,y,”<br>z=”,z,”<br>”);

//Perform multiple assignment in one expression


x = (y = 17) + (2 * (z = 2));

//Display the values stored in the variables after multiple assignment


//in one expression.
document.write(“<u>After multiple assignment in one expression</u><br>”);
document.write(“x=”,x,”<br>y=”,y,”<br>z=”,z,”<br>”);

//-->
</script>
</html>

Figure 2.5
The result of various assignment operations.

In addition to the basic assignment operator, JavaScript also offers a number of


advanced assignment operators that extend assignment functionality. These operators
combine the functionality of basic assignment and other operators into one functional
operator. Table 2.6 shows these advanced assignment operators along with their equiv-
alent operations. Details of these assignment operators can be found in Chapter 7.

Table 2.6 Advanced Assignment Operators


Operator Example Description
+= x+=y x = x + y;
-= x-=y x = x – y;
*= x*=y x = x * y;
/= x/=y x = x / y;
04 0672321416 CH02 7/24/01 11:50 AM Page 53

Operators 53

Operator Example Description


%= x%=y x = x % y;
<<= x<<=y x = x << y;
>>= x>>=y x = x >> y;
>>>= x>>>=y x = x >>> y;
&= x&=y x = x & y;
|= x|=y x = x | y;
^= x^=y x = x ^ y;

All the advanced assignment operators, except for +=, will attempt to convert strings to
numbers before performing the operation. If strings are used with the += operator, the
left operand is concatenated to the end of the right operand. For example, in Listing
2.10, the string “lighthouse” would be assigned to the variable y and the phrase “y=
lighthouse” is written to the browser.

Listing 2.10 Using the Addition Operator to Perform String


Concatenation
<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

// Declare a string
y = “light”;

//Concatenate the string “house” to the


//end of string stored in the variable y
y += “house”;

// Print the output to the screen


document.write(“y= “,y);

//-->
</script>
</html>

So far, you have only considered assignment of values to variables, but what about
assigning a reference to a variable? When the assignment operator works on primitive
values (numbers, strings, Boolean, null, and undefined), a copy of the value is made.
When the assignment operator works on JavaScript objects, references to the objects
are copied. To demonstrate this difference, Listing 2.11 creates a variable and an array
to hold numbers. The variable is then copied by value to another variable, and the array
is copied by reference to another array. To show the difference, the value stored in one
of the variables and one of the arrays is changed, and then all the values are displayed
in the browser as seen in Figure 2.6.
04 0672321416 CH02 7/24/01 11:50 AM Page 54

54 Chapter 2: Details of the Language

Listing 2.11 Assignment by Value Versus by Reference


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare a variable and an array object


var number1 = 94;
var arrayOfNum1 = new Array(23,86);

//Assign by value
var number2 = number1;

//Assign by reference
var arrayOfNum2 = arrayOfNum1;

//Modify value stored in copied variable and array.


number2 = 29;
arrayOfNum2[1] = 47;

//Display the values stored in each variable and array


document.write(“number1=”,number1,”<br>”);
document.write(“number2=”,number2,”<br>”);
document.write(“arrayOfNum1[0]=”,arrayOfNum1[0],”<br>”);
document.write(“arrayOfNum1[1]=”,arrayOfNum1[1],”<br>”);
document.write(“arrayOfNum2[0]=”,arrayOfNum2[0],”<br>”);
document.write(“arrayOfNum2[1]=”,arrayOfNum2[1],”<br>”);

//-->
</script>
</html>

Figure 2.6
The variables number1 and number2 are assigned values by value, whereas the arrays
arrayOfNum1 and arrayOfNum2 are assigned values by reference.

Logical
JavaScript provides three logical operators. Without these operators, programs would
be very long and complex. At first glance, most programmers might think that they
04 0672321416 CH02 7/24/01 11:50 AM Page 55

Operators 55

already know how these operators work, but it is important to dig a little deeper. Not
knowing how the logical operators work can lead to what would appear to be random
errors that are impossible to locate and correct. So take the time to read the description
of each of the logical operators.

NOTE
JavaScript defines true as anything other than 0 (zero), “” (empty string), null,
undefined, or, of course, false.

Logical AND
The logical AND operator (&&) returns true if the expression to the left and the expres-
sion to the right of the operator evaluate to true. If either the left, right, or both expres-
sions evaluate to false, the result of the operation is false.
Unfortunately, the implementation of the logical AND operator in JavaScript is more
complex than what was just mentioned. The AND operation begins by evaluating the left
operand. If the left operand evaluates false, the basic logic of the AND operator is com-
plete, so the right operand is never evaluated. But if the left operand evaluates true, the
right operand must be evaluated to determine the final result of the AND operation. In
either case, the final result returned by the AND operation is actually the result of the last
operand to be evaluated.

Logical OR
The logical OR operator (||) returns true if the expression to the left or the expression
to the right of the operator evaluates to true. If both the left and the right expressions
evaluate to false, the result of the operation is false.
Similar to the logical AND operator, it is important that you understand how JavaScript
actually evaluates the logical OR operator. The OR operation begins by evaluating the left
operand. If the left operand evaluates true, the basic logic of the OR operator is com-
plete, so the right operand is never evaluated. But if the left operand evaluates false,
the right operand must be evaluated to determine the final result of the OR operation. In
either case, the final result returned by the OR operation is actually the result of the last
operand to be evaluated.

Logical NOT
The logical NOT operator (!) is not as complex as the comparison operators. The result
of the expression following the operator is inverted. If the expression evaluates to true,
the result of the operation is false. If the expression evaluates to false, the result is
true. When the expression evaluates to a non-Boolean value, it is converted to true or
false before performing the inversion.

Comparison
JavaScript provides the usual comparison operators found in most languages plus a
couple of more unusual ones. JavaScript had some inconsistencies in the operator
04 0672321416 CH02 7/24/01 11:50 AM Page 56

56 Chapter 2: Details of the Language

department during its early years, which resulted in the addition of some unconven-
tional comparison operators. For this reason, it is important to understand how these
operators work.

Equal
The equal operator (==) compares the value on the left of the operator to the value on
the right of the operator. If the values are equal, true is returned from the operation. If
the values are not equal, false is returned from the operation.
Originally, JavaScript attempted to convert the operands of the equality operator to the
same type before performing a comparison. For example, if the left operand of an equal
operator is a number and the right operand is a string, JavaScript would attempt to con-
vert the string to a number so that two numbers are compared. In an attempt to guess
what would be in the then unreleased ECMAScript standard, the decision was made not
to do type conversion on the operands of the equality operator in JavaScript 1.2. When
the ECMAScript standard was released, it supported type conversion, so JavaScript 1.3
came full circle by once again attempting to convert the operands of the equality oper-
ator to the same type before performing a comparison.
JavaScript determines which behavior should be used by the <script> tag. By setting
the language attribute of the <script> tag equal to JavaScript, type conversion will
be used. If the language attribute is set to “JavaScript1.2”, no type conversion will
be used. An example of this behavior is demonstrated in the Listing 2.12.

Listing 2.12 Type Conversion and the Equal Operator


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Type-conversion turned on
document.write(“The == operator with type-conversion turned on returns: “);
document.write(3==”3”);
// -->
</script>

<script type=”text/javascript1.2” language=”JavaScript1.2”>


<!--
// Type-conversion turned off
document.write(“<br>The == operator with type- “);
document.write(“conversion turned off returns: “);
document.write(3==”3”);
// -->
</script>
</html>
04 0672321416 CH02 7/24/01 11:50 AM Page 57

Operators 57

TIP
Avoid setting the language attribute to “JavaScript1.2” in your code because
the industry standard is for type conversion to be used on the operands of the
equality operator.

So far you’ve seen when type conversion is used with the equality operator, but you
haven’t seen how the type conversion operates. Understanding how type conversions
work for the equality operators will again save time when trying to find bugs. Type con-
version adheres to the following rules:
• True is converted to the number 1, and false is converted to zero before being
compared.
• If either of the operands are NaN, the equality operator returns false.
• null and undefined are equal.
• null and undefined are not equal to 0 (zero), “”, or false.
• If a string and a number are compared, attempt to convert the string to a num-
ber and then check for equality.
• If an object and a string are compared, attempt to convert the object to a string
and then check for equality.
• If an object and a number are compared, attempt to convert the object to a
number and then check for equality.
• If both operands of an equality operation are objects, the addresses of the two
objects are checked for equality.

Not Equal
The not equal operator (!=) compares the value on the left of the operator to the value
on the right. If the values are not equal, true is returned from operation. If they are
equal, false is returned. The != operator is victim to the same type-conversion bug as
the == operator. As with the == operator, use the language attribute of the <script> tag
to force the desired behavior.

Greater Than
The greater than operator (>) compares the value on the left of the operator to the value
on the right. If the value on the left is greater than the value on the right, true is
returned from operation. If the value on the left of the operator is less than or equal to
the value on the right, false is returned. If either of the values is a string, it is converted
to a number before the comparison takes place.

Less Than
The less than operator (<) compares the value on the left of the operator to the value on
the right. If the value on the left is less than the value on the right, true is returned from
operation. If the value on the left of the operator is greater than or equal to the value on
04 0672321416 CH02 7/24/01 11:50 AM Page 58

58 Chapter 2: Details of the Language

the right, false is returned. If either of the values is a string, it is converted to a num-
ber before the comparison takes place.

Greater Than or Equal


The greater than or equal operator (>=) compares the value on the left of the operator
to the value on the right. If the value on the left is greater than or equal to the value to
the right of the operator, true is returned from operation. If the value on the left of the
operator is less than the value on the right, false is returned. If either of the values is
a string, it is converted to a number before the comparison takes place.

Less Than or Equal


The less than or equal operator (<=) compares the value on the left of the operator to
the value on the right. If the value on the left is less than or equal to the value on the
right, true is returned from the operation. If the value on the left of the operator is
greater than the value on the right, false is returned. If either of the values is a string,
it is converted to a number before the comparison takes place.

Identity
The identity operator (===), also referred to as strict equal, compares the value on the
left of the operator to the value on the right. If the value on the left is equal to the value
on the right side of the operator, true is returned from operation. If the values are not
equal, false is returned. No type conversion is performed on the operands before the
comparison.

Non-Identity
The non-identity operator (!==), also referred to as strict does-not-equal, compares the
value on the left of the operator to the value on the right. If the value on the left is not
equal to the value on the right side of the operator, true is returned from operation. If
the values are equal, false is returned. No type conversion is performed on the
operands before the comparison is made.

NOTE
The identity and non-identity operators are only available in JavaScript 1.3 and
later.

Conditional
Many programmers are not familiar with the conditional operator (?:), even though it
exists in numerous languages. Most individuals will use the standard if statement
rather than the conditional operator, even though they do the same thing. The condi-
tional operator is a little harder to read than the standard if statement, but it is much
more compact, which is important when download time is a consideration.
The format of the conditional operator can be a bit confusing. An expression that eval-
uates to a Boolean is always placed to the left of the question mark (?). If the expres-
sion evaluates to true, the value between the question mark and the colon (:) is
04 0672321416 CH02 7/24/01 11:50 AM Page 59

Operators 59

returned from the operation. If the expression evaluates to false, the value following
the colon is returned. In Listing 2.13, a standard if statement is shown, along with
same functionality produced by using the conditional operator. Figure 2.7 shows
that the same functionality is produced from both the if statement and the conditional
operator.

Listing 2.13 The Conditional Operator and if Statement Are Compared


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

// Set the mail flag to “YES”


mailFlag = “YES”
var message1;
var message2;

//Standard if statement
if (mailFlag == “YES”)
message1 = “You have email!”;
else
message1 = “No email.”;

//Same statement using conditional operator


message2 = (mailFlag == “YES”) ? “You have email!” : “No email.”;

// Print the message to the screen


document.write(“The if statement returns: “,message1,”<br>”);
document.write(“The conditional operator returns: “,message2);

//-->
</script>
</html>

Figure 2.7
The result of using the if statement is the same as using the conditional operator.

Bitwise
The bitwise operators look similar to the comparison operators, but their functionality
is very different. If you have ever worked with truth tables, you might recognize the
operators in this section. Bitwise operators in JavaScript only work with integers that
04 0672321416 CH02 7/24/01 11:50 AM Page 60

60 Chapter 2: Details of the Language

are 32 bits in length. If an integer is not 32 bits, it is turned into a one because the bit-
wise operators evaluate numbers at the binary level where everything is ones and zeros.
Bitwise operations are not used often in programming, but there are times when the
operators are indispensable.

Bitwise AND
The bitwise AND operator (&) looks at the integer numbers on both sides of the operator
as 32-bit binary numbers. Then the logical AND (&&) operator, discussed earlier in the
chapter, individually evaluates each of the 32 bits representing the number to the left
of the operator to the corresponding bit of the number to the right of the operator. The
32-bit binary result of logical AND operation is converted to an integer value and
returned from the bitwise AND operation.

Bitwise OR
The bitwise OR operator (|) looks at the integer numbers on both sides of the operator
as 32-bit binary numbers. Then the logical OR (||) operator, discussed earlier in the
chapter, individually evaluates each of the 32 bits representing the number to the left
of the operator to the corresponding bit of the number to the right of the operator. The
32-bit binary result of logical OR operation is converted to an integer value and returned
from the bitwise OR operation.

Bitwise XOR (exclusive OR)


The bitwise XOR operator (^) looks at the integer numbers on both sides of the operator
as 32-bit binary numbers. Unlike the bitwise OR operator, bitwise XOR uses a special
version of the logical OR operator, called exclusive OR, to evaluate each bit of a binary
number.

NOTE
An exclusive OR operation returns true if either the value to the left or the value
to the right of the operator is true, but not both. If both values are false or both
values are true, the result of the operation is false.

The exclusive OR individually evaluates each of the 32 bits representing the number to
the left of the bitwise XOR operator to the corresponding bit of the number to the right
of the operator. The 32-bit binary result of exclusive OR operation is converted to an
integer value and returned from the bitwise XOR operation.

Bitwise NOT
The bitwise NOT operator (~) is simpler than the bitwise AND, OR, and XOR operators. The
bitwise NOT operator begins by looking at the number to the right of the operator as a
32-bit binary number. Each bit of the given number is reversed so that all ones become
zeros and all zeros become ones. The 32-bit binary result is converted to an integer
value and returned from the bitwise NOT operation.
04 0672321416 CH02 7/24/01 11:50 AM Page 61

Operators 61

Shift Left
The shift left operator (<<) looks at the integer to the left of the operator as a 32-bit
binary number. All the bits in this number are shifted to the left by the number of posi-
tions specified by the integer to the right of the operator. As the bits are shifted to the
left, zeros are filled in on the right. Because the number can only be 32 bits long, the
extra bits on the left are lost. The 32-bit binary result of shifting operation is converted
to an integer value and returned from the shift left operation.

Shift Right with Sign


The shift right with sign operator (>>) is similar to the shift left operator. The shift right
with sign operator looks at the integer to the left of the operator as a 32-bit binary num-
ber. All the bits in this number are shifted to the right by the number of positions spec-
ified by the integer to the right of the operator. As the bits are shifted to the right, either
ones or zeros are filled in on the left. If the original number is positive, ones are added
to the left side of the binary number. On the other hand, if the original number is neg-
ative, zeros are used. Because the result can only be 32 bits long, the extra bits on the
right are lost. The 32-bit binary result of the shifting operation is converted to an inte-
ger value and returned from the shift right with sign operation.

Shift Right Zero Fill


The shift right zero fill operator (>>>) operates the same as the shift right with sign
operator, except that the binary number is always padded on the left with zeros, regard-
less of the sign of the original integer.

Precedence
JavaScript, similar to other languages, enables numerous operators to be used in one
expression. Because operators can appear just about anywhere within an expression,
JavaScript follows guidelines that determine which operator is evaluated first, second,
third, and so on. Table 2.7 shows the precedence of all the JavaScript operators. The
Read From… column tells what order (left-to-right or right-to-left) operators of equal
precedence are evaluated. It is possible to override the precedence of operators by using
parentheses.

TIP
Use parentheses to ensure that your code operates like you expect and to make
your code more readable.

Table 2.7 Operator Precedence


Precedence Read From… Operator Operator Type
Highest L to R ., [] Member access
L to R (), new Call/ create instance
R to L ++, --, +, Pre/Post
-, !, ~, Increment/Decrement,
04 0672321416 CH02 7/24/01 11:50 AM Page 62

62 Chapter 2: Details of the Language

Table 2.7 Continued


Precedence Read From… Operator Operator Type
void, and so on.
delete, typeof

L to R *, /, % Multiplication, divi-
sion, modulus
L to R +, - Addition, Subtraction
L to R <<, >>, >>> Bitwise shift
L to R <, <=, >, >= Relational operations
L to R ==, !=, Equality operations
===, !==
L to R & Bitwise AND
L to R ^ Bitwise XOR
L to R | Bitwise OR
L to R && Logical AND
L to R || Logical OR
R to L ?: Conditional
R to L =, *=, /=, Assignment operation
%=, +=, -=,
<<=, >>=,
>>>=, &=,
^=, |=
Lowest L to R , Multiple evaluation

Loops and Conditionals


Loops and conditionals give programs the power to make decisions and perform tasks
multiple times. JavaScript provides the standard conditionals and looping structures
that are available in many computer languages. In fact, these structures were patterned
after those found in C, C++, and Java, so if you have written code in any of these lan-
guages, you will find this section very straightforward.

Conditionals
Conditional statements enable programs to make decisions based on preset conditions
that use the operators discussed earlier in the chapter.

if
The if statement is by far the most common conditional statement simply because it is
simple and easy to use. The format of a simple if statement looks as follows:
if (expression)
statement;

If the expression in parentheses evaluates to true, the statement is executed; otherwise,


the statement is skipped. The statement to be executed can appear on the same line as
04 0672321416 CH02 7/24/01 11:50 AM Page 63

Loops and Conditionals 63

the if expression, but the code is usually easier to read if the statement appears on the
next line as shown in the preceding pseudo code. If two or more lines of code are to be
executed, curly braces {} must be used to designate what code belongs in the if state-
ment.
Use the keyword else to extend the functionality of the basic if statement to provide
other alternatives if the initial statement should fail. The format of an if...else com-
bination resembles the following:
if (expression)
statement1;
else
statement2;

Now, if the expression evaluates to true, statement1 is executed; otherwise,


statement2 is executed. Listing 2.14 demonstrates the use of if and else with a hotel
occupancy example. When executed, the code returns the message “There are not
enough rooms for 5 guests.”.

Listing 2.14 Basic if...else Structures


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare variables
var emptyRooms = 2; //Two people per room
var numberOfGuests = 5;

if (emptyRooms == 0)
document.write(“There are no rooms available.”);
else
{
if ((emptyRooms*2) >= numberOfGuests)
document.write(“There are enough rooms for “,numberOfGuests,” guests.”);
else
document.write(“There are not enough rooms for “);
document.write(numberOfGuests,” guests.”);
}
}

//-->
</script>
</html>

Notice how Listing 2.14 used curly brackets {} to nest an if...else structure inside
another if...else structure. Nesting gives programs more decision-making power,
but this power comes at the cost of readability.
04 0672321416 CH02 7/24/01 11:50 AM Page 64

64 Chapter 2: Details of the Language

else...if
The else...if phrase is used in place of nested if...else structures to make code
more readable. Each else...if phrase is followed by an expression enclosed in paren-
theses. Use as many else...if statements as needed. Use a final else statement to
execute code when all other conditionals evaluate to false. Listing 2.15 has the same
functionality as the code in Listing 2.14, but it uses the else...if structure. This code
displays the phrase, “There are not enough rooms for 5 guests.”.

Listing 2.15 Making Nested if...else Statements More Readable with


the else...if Phrase
<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare variables
var emptyRooms = 2; //Two people per room
var numberOfGuests = 5;

if (emptyRooms == 0)
document.write(“There are no rooms available.”);
else if ((emptyRooms*2) >= numberOfGuests)
document.write(“There are enough rooms for “,numberOfGuests,” guests.”);
else
document.write(“There are not enough rooms for “,numberOfGuests,” guests.”);

//-->
</script>
</html>

switch
JavaScript offers the switch statement as an alternative to using the if...else struc-
ture. The switch statement is especially useful when testing all the possible results of
an expression. The format of a switch structure resembles the following:
switch (expression)
{
case label1:
statement1;
break;
case label2:
statement2;
break;
default:
statement3;
}
04 0672321416 CH02 7/24/01 11:50 AM Page 65

Loops and Conditionals 65

The switch statement begins by evaluating an expression placed between parentheses,


very similar to the if statement. The result is compared to labels associated with case
structures that follow the switch statement. If the result is equal to a label, the state-
ment(s) in the corresponding case structure are executed. A default structure can be
used at the end of a switch structure to catch results that do not match any of the case
labels. Listing 2.16 gives an example of the switch structure.

Listing 2.16 Using the switch Structure


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare variables
var color = “green”;

//Display the color of the car based on the variable “color”


switch (color)
{
case “red”:
document.write(“The car is red.”);
break;
case “blue”:
document.write(“The car is blue.”);
break;
case “green”:
document.write(“The car is green.”);
break;
default:
document.write(“The car is purple.”);
}

//-->
switch
</script>
</html>

There are a few key points to note about the format of the switch structure in Listing
2.16. First, notice that a colon (:) always follows a label. Second, curly brackets {} are
used to hold all the case structures together, but they are not used within a case struc-
ture, even when multiple statements are to be executed. Finally, the keyword break is
used to break out of the entire switch statement after a match is found, thus prevent-
ing the default structure from being executed accidentally. The result of executing the
code in Listing 2.16 is the string “The car is green.” being displayed.

Loops
There are times when the same portion of code needs to be executed many times with
slightly different values. Use loops that run until a condition is met to create this func-
tionality.
04 0672321416 CH02 7/24/01 11:50 AM Page 66

66 Chapter 2: Details of the Language

for
The for loop is a structure that loops for a preset number of times. JavaScript uses the
C and C++ for loop structure. This particular structure is flexible, which makes this
type of loop very useful.
From a very high level, the for loop is made up of two parts: condition and statement.
The condition portion of the structure determines how many times the loop repeats,
whereas the statement executes every time the loop occurs.
The condition structure is contained within parentheses and is made up of three parts,
each separated by a semicolon (;). The first part of the condition structure initializes a
variable to a starting value. In most cases, the variable is declared within this section
as well as initialized. The second part is the actual conditional statement that deter-
mines how many times the loop will be iterated. The third and final part determines
how the variable, which was initialized in the first part, should be changed each time
the loop is iterated. This third part gives the for loop its flexibility by causing the vari-
able to be incremented, decremented, factored, or any other adjustment trick you can
devise. The format of the for loop appears as follows:
for (initialize; condition; adjust)
{
statement;
}

It is important to take time to think about how to implement for loops because it is easy
to accidentally create an infinite loop. Specifically, make sure that the conditional will
catch the adjusted variable at some point. In many cases, it is advantageous to use the
variable in the statement portion of the for loop, but take care not to adjust the vari-
able in such a way that an infinite loop is created. Listing 2.17 makes use of the for
loop to create a multiplication table as shown in Figure 2.8.

Listing 2.17 Multiplication Table Using for Loop


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

document.write(“<h2>Multiplication table for 4</h2>”);


for (var aNum = 0; aNum <= 10; aNum++)
{
document.write(“4 X “,aNum,” = “,4*aNum,”<br>”);
}

//-->
</script>
</html>
04 0672321416 CH02 7/24/01 11:50 AM Page 67

Loops and Conditionals 67

Figure 2.8
The multiplication table is created using a for loop.

while
When the for loop is too restrictive for a particular piece of code, consider using the
while loop. The while loop can do everything that the for loop can do, but not as
cleanly. So why even use the while loop? The while loop goes beyond the for loop’s
capabilities by not restricting the number of times the loop will execute.
The while loop is easy to understand if the phrase “While true, loop” is remembered.
This phrase means that while the expression in parentheses evaluates to true, execute
the statements in the loop. After the last statement in the loop is executed, go back to
the top of the loop and evaluate the expression again. When the expression evaluates to
false, the next line of code following the while loop structure is executed. To keep the
loop from executing indefinitely, a statement must be included in the loop that modi-
fies a variable in the expression. The format of the while loop resembles the follow-
ing:
while (expression)
{
statement;
}

Because the expression is evaluated before the loop, it is possible the loop will never
be executed if the expression should evaluate to false the first time. Listing 2.18 sim-
ulates an automated traffic light using the while loop.

Listing 2.18 Automated Traffic Light Using while Loop


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare variables
var light = “red”; //traffic light
04 0672321416 CH02 7/24/01 11:50 AM Page 68

68 Chapter 2: Details of the Language

var counter = 1; //create car traffic


var carsInLine = new Array(); //cars in line
//Make 5 cars go through intersection
while (counter <= 5)
{
document.write(“Car “,counter,” approaches intersection.<br>”);
carsInLine[carsInLine.length++] = counter;

//When 2 cars are in line light turns green


if (carsInLine.length == 2)
{
light = “green”;
document.write(“Traffic light turns “,light,”<br>”);
}

//while light is green cars pass through intersection


while (light == “green”)
{
document.write(“Car “,carsInLine[carsInLine.length-1]);
carsInLine.length--;
document.write(“ goes through intersection.<br>”);

//When no cars are in line light turns red


if (carsInLine.length == 0)
{
light = “red”;
document.write(“Traffic light turns “,light,”<br>”);
}
}
counter++; //Next car
}

//-->
</script>
</html>

Listing 2.18 uses two while loops to simulate an automated traffic light. The first
while loop could have just as easily been created using a for loop, but the second
while loop would have been nearly impossible to implement using a for loop. The
while loop handles this type of conditional loop with ease. In Figure 2.9, you see that
the traffic light automatically turns green when two cars are in line at the intersection.
After the two cars go through the intersection, the light turns red.

do...while
The do...while loop is simply a variation of the basic while loop that was just dis-
cussed. Other than syntax, the only difference between the do...while loop and the
while loop is that the do...while loop always executes the loop once before evaluat-
ing the expression for the first time. This difference is seen in the following format:
04 0672321416 CH02 7/24/01 11:50 AM Page 69

Loops and Conditionals 69

do
{
statement;
}
while (expression);

Figure 2.9
Simulating a traffic light using two while loops.

After the loop has executed for the first time, the expression in parentheses is evalu-
ated. If true, the loop is executed again. When the expression evaluates to false, the
next line of code following the while structure is executed. As was the case with the
while loop, a statement must be included in the loop that modifies a variable in the
expression to prevent an infinite loop. Also, notice that a semicolon (;) must be placed
after the rightmost parenthesis. Listing 2.19 is the same automated traffic light simu-
lator as shown in Listing 2.18, except do...while loops are used instead of while
loops.

Listing 2.19 Automated Traffic Light Using do...while Loop


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare variables
var light = “red”; //traffic light
var counter = 1; //create car traffic
var carsInLine = new Array(); //cars in line
//Make 5 cars go through intersection
while (counter <= 5)
{
document.write(“Car “,counter,” approaches intersection.<br>”);
carsInLine[carsInLine.length++] = counter;
04 0672321416 CH02 7/24/01 11:50 AM Page 70

70 Chapter 2: Details of the Language

Listing 2.19 Continued


//If light green then execute loop more than once
do
{
//When 2 cars are in line light turns green
if (carsInLine.length == 2)
{
light = “green”;
document.write(“Traffic light turns “,light,”<br>”);
}

//When no cars are in line light turns red


if (carsInLine.length == 0)
{
light = “red”;
document.write(“Traffic light turns “,light,”<br>”);
}

//Cars pass through intersection while light is green


if (light == “green”)
{
document.write(“Car “,carsInLine[carsInLine.length-1]);
carsInLine.length--;
document.write(“ goes through intersection.<br>”);
}
}
while (light == “green”);

counter++; //Next car


}

//-->
</script>
</html>

The output generated from running Listing 2.19 is exactly the same as executing
Listing 2.18.

for...in
The for...in loop should not be confused with the for loop because they are quite
different. The only similarity is that both iterate through the loop a set number of times,
but this is as far as the similarity goes. The for...in loop is a special looping construct
found only in JavaScript to provide access to all the enumerated properties of a
JavaScript object. This includes elements of the Array object because they are stored
the same way that property names are stored in JavaScript object. The statement(s) in
the loop are executed for each property of an object until every property has been
04 0672321416 CH02 7/24/01 11:50 AM Page 71

Loops and Conditionals 71

accessed. Any parts of an object—such as methods and some properties—that are not
enumerated are not accessed by this looping structure. The format of the for...in loop
appears as follows:
for (variable in object)
{
statement;
}

Before the statements in the loop are executed, a property name of the object specified
to the right of the keyword in is assigned to the variable on the left side of the keyword
in. The variable would then be used within the loop code. This process will continue
until all the properties have been accessed. Unfortunately, the order in which the prop-
erties are accessed can vary, so do not assume a particular order. Listing 2.20 shows the
properties of a simple HTML button.

Listing 2.20 Accessing Property Names of the Button Object Using a


for...in Loop
<html>
<form name=”aForm”>
<input type=”button”
name=”Big_Button”
value=”Big Button”
onClick=”alert(‘The Big Button was pressed!’)”;
>
</form>
<script type=”text/javascript” language=”JavaScript”>
<!--

var aProperty;
for (aProperty in document.aForm.Big_Button)
{
document.write(aProperty,”<br>”);
}

//-->
</script>
</html>

Notice that in Figure 2.10, the name of the properties in the Big Button object, rather
than the values stored in those properties, was returned.

break
The keyword break provides a way for JavaScript to exit out of loop structures and
switch conditionals prematurely. Most of the time, the word break appears on a line
by itself, but there are times when a label will follow the keyword. When a label is
used, JavaScript completely breaks out of the area designated by label and proceeds
to the code that follows the area.
04 0672321416 CH02 7/24/01 11:50 AM Page 72

72 Chapter 2: Details of the Language

Figure 2.10
The properties of the Big Button object.

JavaScript labels can be thought of as placeholders. To label a statement, simply place


the label name followed by a colon (:) in front of the code that needs to be broken out
of during code execution. Labels are useful when working with nested loops, as shown
in Listing 2.21.

Listing 2.21 Using Breaks and Labels


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Create outerloop
forLoop1:
for (var counter1 = 1; counter1 <= 5; counter1++)
{
//Create innerloop
for (var counter2 = 1; counter2 <= 5; counter2++)
{
//Display values in counters for both loops
document.write(“Counter1=”,counter1);
document.write(“ Counter2=”,counter2,”<br>”);

//Determine when to break out of loop


if (counter2 == 3)
break;
if (counter1 == 3)
break forLoop1;
}
}
04 0672321416 CH02 7/24/01 11:50 AM Page 73

Loops and Conditionals 73

document.write(“All done!”);

//-->
</script>
</html>

Notice how the break statement with no label (see Figure 2.11) breaks out of just the
inner loop. When the break statement is used with a label, JavaScript knows at which
level to break.

Figure 2.11
Result of using labels and nested loops.

continue
Unlike the JavaScript break structure, the continue statement forces the execution of
the code to continue at the beginning of the loop. Similar to the keyword break, the
continue keyword usually appears on a line by itself, but there are times when a label
will follow the keyword. When a label is used, JavaScript immediately jumps to the
beginning of the loop designated by a label and begins executing code.
The beginning of a loop varies depending on the type of loop structure. Table 2.8
shows where each looping structure jumps when a continue structure is encountered.

Table 2.8 Where the continue Statement Jumps


Looping Structure Continue Jumps To
for Expression in parentheses following the for keyword
while Expression in parentheses following the while keyword
do...while Expression in parentheses following the while keyword
for...in Next property name in the object

CAUTION
A bug in Navigator 4 causes the expression in parentheses following the while key-
word to not get executed when jumped to using a continue statement. Instead,
execution of code starts at the top of the loop after the continue statement.
04 0672321416 CH02 7/24/01 11:50 AM Page 74

74 Chapter 2: Details of the Language

As discussed in the break section, JavaScript labels can be thought of as placeholders.


To label a statement, simply place the label name followed by a colon (:) in front of
the code where code execution should continue. Listing 2.22 demonstrates the use of
label and continue.

Listing 2.22 Using the continue Statement and Labels


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Create outerloop
outerLoop:
for (var counter1 = 1; counter1 <= 2; counter1++)
{
document.write(“Top of outerLoop.<br>”);
//Create innerloop
innerLoop:
for (var counter2 = 1; counter2 <= 2; counter2++)
{
//Display values stored in counters of both loops
document.write(“Top of innerLoop.<br>”);
document.write(“Counter1=”,counter1,”<br>”);
document.write(“Counter2=”,counter2,”<br>”);

//Determine where to continue looping


if (counter2 == 2)
{
document.write(“Continue at top of innerLoop.<br>”);
continue;
}
if (counter1 == 2)
{
document.write(“Continue at top of outerLoop.<br>”);
continue outerLoop;
}
document.write(“Bottom of innerLoop.<br>”);
}
document.write(“Bottom of outerLoop.<br>”);
}

document.write(“All done!”);

//-->
</script>
</html>

This example is a bit complicated, so take time to compare Listing 2.22 to the output
in Figure 2.12. Notice how the phrase “Bottom of innerLoop” was not printed after
04 0672321416 CH02 7/24/01 11:50 AM Page 75

Loops and Conditionals 75

the “Continue at top of innerLoop” because code execution jumped back to begin-
ning of the innermost loop. When a label was attached to the continue keyword, code
execution jumped back to the beginning of the loop labeled outerLoop.

CAUTION
Even though JavaScript provides labels, continue statements, and break state-
ments, be careful when using these constructs because they can lead to errors that
are hard to trace if they are used improperly.

Figure 2.12
Result of using the continue statement in nested loops.

with
The object-oriented design of JavaScript quite often requires long lines of code to
access properties and methods of objects. JavaScript provides a special with statement
to help reduce the length of code needed to access these properties and methods. The
with statement works by placing the repetitive portion of the object’s path in paren-
theses after the with keyword. Now, any properties or methods used within the with
statement will automatically have the repetitive portion of the object’s path (located in
parentheses) added to the front of the string. Listing 2.23 shows how the with state-
ment can save time when resetting text fields to their default values.

Listing 2.23 The with Statement Reduces Repetitive Code


<html>
<!--Create a form that has 3 text fields and a reset button-->
<form name=”personalInfoForm”>
Name<input type=”text” name=”nameBox”><br>
Occupation<input type=”text” name=”occupationBox”><br>
04 0672321416 CH02 7/24/01 11:50 AM Page 76

76 Chapter 2: Details of the Language

Listing 2.23 Continued


Age<input type=”text” name=”ageBox”><br>
<input type=”button” name=”ResetButton”
value=”Reset” onClick=”ResetFields()”>
</form>

<script type=”text/javascript” language=”JavaScript”>


<!--

//Set text field values initially


ResetFields();
//Reset text fields to default values
function ResetFields()
{
with(document.personalInfoForm)
{
nameBox.value=”[Enter your name]”;
occupationBox.value=”Student”;
ageBox.value=””;
}
}

//-->
</script>
</html>

In Figure 2.13, you see that the text fields contain default data that appear initially as
well as any time the Reset button is clicked. To achieve this functionality, the Reset but-
ton is connected to a function, called ResetFields(), that assigns default values to the
text fields. To reduce repetitive code, the with statement was used in setting the default
values, as seen in Listing 2.23.

Figure 2.13
Using the with statement reduces the amount of code needed to set the default text
box values.

Functions
One of the strengths of JavaScript is that it provides support for functions, which is
uncommon among scripting languages. On the other hand, JavaScript functions are
04 0672321416 CH02 7/24/01 11:50 AM Page 77

Functions 77

not as fully developed as those found in languages such as C and C++. The function-
ality that JavaScript does provide through its functions is more than enough to make
Web pages come alive.

Syntax
The syntax of JavaScript functions is very straightforward. All function declarations
must begin with the keyword function followed by the name of the function. The
name of the function is the name that will be used to call on the function within code.
Parentheses are placed after the function name to hold arguments that are to be passed
into the function. If more than one argument is to be passed into the function, use com-
mas to separate the arguments. On the other hand, if no arguments need to be passed
into the function, leave the space between the parentheses empty. Finally, curly brack-
ets are used to contain the code related to the function. Curly brackets are not optional:
They are required in JavaScript, even if the function is only made up of one line of
code.

Call By Value Versus Call By Reference


If you have done programming in C or C++, you are probably familiar with the phrases
call by value and call by reference as related to function arguments. In very basic terms,
call by reference passes the location of the actual argument to the function, whereas
call by value makes a copy of the argument to be used just within the function.
JavaScript keeps the functionality of passing arguments simple by just using call by
value. Using call by value gives the freedom to manipulate the arguments within the
function without fear of changing the argument’s values outside the function. Listing
2.24 shows an example of JavaScript call by value.

Listing 2.24 Call By Value


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Declare variables
var aString = “banana”
var aNumber = 15;

//Function declaration
function test(aString, aNumber)
{
aString = “orange”;
aNumber = 124;

//Display values stored in function variables.


document.write(“During function call:<br>”);
document.write(“aStringCopy=”,aString,”<br>”);
document.write(“aNumberCopy=”,aNumber,”<br>”);
}
04 0672321416 CH02 7/24/01 11:50 AM Page 78

78 Chapter 2: Details of the Language

Listing 2.24 Continued


//Display variables before function call
document.write(“Before function call:<br>”);
document.write(“aString=”,aString,”<br>”);
document.write(“aNumber=”,aNumber,”<br>”);

//Call on function
test(aString,aNumber);

//Display variables after function call


document.write(“After function call:<br>”);
document.write(“aString=”,aString,”<br>”);
document.write(“aNumber=”,aNumber,”<br>”);

//-->
</script>
</html>

In Figure 2.14, you see that the values stored in aString and aNumber appeared to be
changed while in the function test. But after exiting the function, the values reverted
back to their initial value. What actually happened was that a local copy of the vari-
ables was made for use within the function. These new variables even have the same
name as the ones that were passed into the function. After execution of the function was
completed, the local variables no longer existed, so final values displayed were of the
original variables.

Figure 2.14
Result of using call by value.

If you need to pass in a large number of arguments but do not want to assign each one
to a variable, it is possible to access the arguments as an array. To do this, leave the
area in parentheses blank and use the arguments object and the array operator [] to
access each argument. Listing 2.25 displays the arguments passed into the function
using the arguments array as shown in Figure 2.15.
04 0672321416 CH02 7/24/01 11:50 AM Page 79

Functions 79

Listing 2.25 Accessing Function Arguments with the arguments Array


<html>
<script type=”text/javascript1.2” language=”JavaScript1.2”>
<!--

//Create a function that displays the arguments it receives.


function displayArguments()
{
document.write(“The following arguments were passed:<br>”);
for(i=0; i<arguments.length; i++)
{
document.write(i,” = “,arguments[i],”<br>”);
}
}

//Pass some arguments into function


displayArguments(34,”hat”,-7945,”shoes”);

//-->
</script>
</html>

Figure 2.15
The arguments passed into the displayArguments() function using the arguments array.

Returning Values
What if a value needs to be passed back from a function to be used later in the code?
JavaScript provides a return statement that can be used in a function to return a value
back to the statement that called the function. The value to be returned is simply placed
after the keyword return. The undefined value is returned from a function if no value
is specified after the keyword return or if the return statement is not used at all.
A value returned from a function can be assigned to a variable or used within an
expression. In Listing 2.26, the value returned from the function is used in an expres-
sion to write the phrase “3*5=15” to the browser window.
04 0672321416 CH02 7/24/01 11:50 AM Page 80

80 Chapter 2: Details of the Language

Listing 2.26 Returning a Value from a Function


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Function declaration
function multiplyByFive(aNumber)
{
return aNumber*5;
}

//Display variables before function call


document.write(“3*5=”,multiplyByFive(3));

//-->
</script>
</html>

Functions as Objects
The functions that have been described so far are created statically when the Web page
is loaded, but there is also a dynamic function that is not created until it is called, which
enables functions to be objects. The syntax for this type of function is very similar to
the declaration of a variable.
var varName = new Function(argument1,...,lastArgument);

The keyword Function is used to create a new function dynamically from the argu-
ments. All the arguments must be strings, and the last argument should always contain
the functionality of the function. Listing 2.27 shows a simple example of using the
Function object. Once again the phrase “3*5=15” is written to the browser window.

Listing 2.27 Returning a Value from a Function


<html>
<script type=”text/javascript” language=”JavaScript”>
<!--

//Create the dynamic Function


var multiplyByFive = new Function(“y”,”return y*5”);

document.write(“3*5=”,multiplyByFive(3));

//-->
</script>
</html>
04 0672321416 CH02 7/24/01 11:50 AM Page 81

Moving On 81

Moving On
In this chapter, you were introduced to the details of the JavaScript language that are
common across many computer languages. Armed with an understanding of JavaScript
data types, variables, operators, loops, conditionals, functions, and basic syntax, which
were covered in this chapter, you could start constructing JavaScript programs right
now. But don’t you want to learn some JavaScript specific programming techniques
that will help you tap into JavaScript’s full potential? In the next chapter, we will do
just that by diving into some JavaScript programming techniques that take JavaScript
beyond just a plain computer scripting language.
04 0672321416 CH02 7/24/01 11:50 AM Page 82
05 0672321416 Part II 7/24/01 11:52 AM Page 83

PA R T I I

PROGRAMMING IN
JAVASCRIPT
3 Programming Techniques 85
4 Client-Side Scripting 107
5 JavaScript on the Server-Side 157
6 Windows Scripting 179
05 0672321416 Part II 7/24/01 11:52 AM Page 84
06 0672321416 CH03 7/24/01 11:53 AM Page 85

Programming Techniques
CHAPTER 3

Programming Techniques
In Chapter 2, “Details of the Language,” you were given a
quick overview of the core JavaScript language to show you
differences and similarities to other computer languages. Now
it is time to go to the next level by examining some of the fea-
tures of the JavaScript language and programming techniques
that will make your JavaScript programs more powerful and
more resilient to errors and maybe even make you say, “Wow,
I didn’t know JavaScript could do that!”
In this chapter we will look at pattern matching and event han-
dling and show you how to use these two pieces of JavaScript
functionality to make your JavaScript programs more power-
ful. This chapter will also examine two programming tech-
niques that will make your JavaScript programs less error
prone. You will be introduced to the try...catch block and
shown how to use it. You will also be introduced to some free
JavaScript debugging programs and techniques.

Pattern Matching
Two of the most common uses of Web pages today are for
gathering and distributing data. These two areas, by nature, use
data manipulation to understand what the user needs and then
return information tailored to the user’s specifications. One of
the key tools for processing data is pattern matching. Some
scripting languages, such as Perl, are well suited to handle pat-
tern matching, whereas others provide very little pattern
matching capabilities. If you are familiar with Perl, you will
probably recognize JavaScript pattern matching because it was
based on Perl’s implementation of pattern matching. The
implementation of pattern matching into JavaScript greatly
aids in the processing of data for the Internet.
06 0672321416 CH03 7/24/01 11:53 AM Page 86

8 6 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s

JavaScript uses the RegExp (short for Regular Expression) object to handle pattern
matching. This object holds the pattern definition, as well as provides methods for per-
forming matching. You’ll begin by learning how to define patterns and then by learn-
ing how to use the RegExp objects to test for pattern matches.

Defining the RegExp Object


The RegExp object can be created in two different ways, which are similar to defining
strings. The first way is to use the RegExp constructor and the keyword new:
var lastName = new RegExp(“Jones”);

This notation creates a new RegExp object called lastName and assigns the pattern
Jones. The same functionality could have been accomplished by using a direct assign-
ment:
var lastName = /Jones/;

To differentiate this notation from that used to define strings, the forward slash char-
acter (/) is used to designate the beginning and end of the pattern. Notice that forward
slashes were not needed in the RegExp() constructor because this could be distin-
guished from the String() constructor.

Defining Patterns
The syntax used to define patterns in JavaScript could be considered a scripting lan-
guage in itself because it is so extensive. There are special characters for creating
almost any pattern one could imagine, including characters for handling groups, repe-
tition, position, and so on. Table 3.1 shows the special pattern matching characters
available in JavaScript.

Table 3.1 Special Pattern Matching Characters


Character Description
\w Matches any word character (alphanumeric).
\W Matches any non-word character.
\s Matches any whitespace character (tab, newline, carriage
return, form feed, vertical tab).
\S Matches any non-whitespace character.
\d Matches any numerical digit.
\D Matches any character that is not a number.
[\b] Matches a backspace.
. Matches any character except a newline.
[...] Matches any one character within the brackets.
[^...] Matches any one character not within the brackets.
[x-y] Matches any character in the range of x to y.
[^x-y] Matches any character not in the range of x to y.
{x,y} Matches the previous item at least x times but not to
exceed y times.
06 0672321416 CH03 7/24/01 11:53 AM Page 87

Pattern Matching 87

Character Description
{x,} Matches the previous item at least x times.
{x} Matches the previous item exactly x times.
? Matches the previous item once or not at all.
+ Matches the previous item at least once.
* Matches the previous item any number of times or not at
all.
| Matches the expression to the left or the right of the |
character.
(...) Groups everything inside parentheses into a subpattern.
\x Matches the same characters that resulted from the sub-
pattern in group number x. Groups, which are designated
with parentheses, are numbered from left to right.
^ Matches the beginning of the string or beginning of a
line, in multiline matches.
$ Matches the end of the string or end of a line, in multiline
matches.
\b Matches the position between a word character and a
non-word character.
\B Matches the position that is not between a word charac-
ter and a non-word character.

These special pattern matching characters are used within the p