Lecture: JavaScript II
JavaScript Syntax
References: Stein, L.D. 'How To Set Up and Maintain a Web Site'
2nd edn, Addison Wesley 1997, Chpt10.
Flanagan, D. 'JavaScript, The Definitive Guide'
2nd edn, O'Reilly & Associates, Inc.
- It is essential that one or both of these texts, or some other reference
(eg. the WWW) be consulted on this topic.
- This page is a summary only of a few
important JavaScript language features after Stein. It is not intended to be a
comprehensive explanation of JavaScript.
Strings
- "This is a string" and 'This is a string'
- 'T' 'h' "e" "s" "e" "are strings too!"
- There is no distinction between single characters and strings
- Single quotes are useful:
onClick = "confirm('Are you sure you want to become a potato Dave?')"
|
- You can escape a quotation mark using backslash:
quote = "\"Eat my shorts HAL!\", muttered Dave."
|
- \n linefeed (UNIX newline), \r carriage return (Macintosh newline)
\t (tab)
- Strings may be concatenated using the + operator.
Numbers
- 2001
- 2001.0
- -2001.0
- +2001.0 Does not work!
- 2.01E3
- 0x2A (hexadecimal numbers preceded by a 0x, digits from 0-F)
- 0743 (octal numbers preceded by a 0, digits from 0-7)
Booleans
- Keywords true and false
- These are not the same as 1 and 0!
Comments
- // This is a comment to the end of a line
- /* This is a comment
which spans more
than one line */
Type Conversion
- JavaScript has automatic type conversion
- eval (string) forces conversion of a string to a numeric value.
var aString = "2001";
var aNumber = eval(aString);
|
- parseInt (string, radix)
returns an integer value upto the first non-numeric character in the string.
Base 10 is assumed if no radix is specified.
- parseFloat (string)
returns a floating point value or NaN (not a number) if the string
contains any non-numeric characters.
- isNaN(number)
returns true or false if number is NaN. (Windo$ implementation of parseFloat()
may return 0 instead of NaN!)
Variables & Assignment
- JavaScript is loosely typed hence the statements...
myVariable = "Dave";
myVariable = 2001;
|
...work just fine one after another even though one assigns myVariable
to a string and the other to a number!
- Strings are automatically converted to numbers if you try to
perform arithmetic with them. (& vice versa)
- Variable names must be alphanumeric characters starting with a letter
or underscore. (Case is significant)
- Variables do not need to be declared before use but it is important to
declare local variables in a function to avoid overwriting global variables of the same
name!
aVariable = "HAL";
function eliminateDave () // Function to keep HAL happy
{
var aVariable = "Dave";
eliminate(aVariable);
}
|
Operators & Expressions
The following operators and expressions are valid in JavaScript,
just as they are in the C programming language.
- x = a + (b - 2001 * (c % 2)) / 10.1
- x++; x--; y = ++x; y = x--; x += 2001 etc.
- (x && y); (x || y); y = !x;
Comparisons & Conditional Statements
The following are valid in JavaScript, just as they are
in the C programming language.
-
if (x > 2001){ ... }
else if (x < 2001){ ... }
else { ... }
-
result = (x > 2001) ? ( ... ) : ( ... );
-
x >= y; x <= y; x > y; x < y; x == y; x != y
Early versions of JavaScipt do not support C's switch() statement.
Unlike in C, you can compare strings using the comparision operators.
if (name < "D")
{ alert("Your name comes before Dave's alphabetically"); }
Loops
The following are valid in JavaScript, just as they are
in the C programming language.
-
var year=0;
while (year < 2001) { ...; year++; }
-
for (year=0; year < 2001; year++) { ... }
-
break; continue;
- Also see for ... in loops.
Functions
- JavaScript function definitions are made using the function keyword.
- JavaScript function definitions do not include the return type.
- Sample function definitions
function blah() { ... }
function bloo(myVar) { ... }
function blod(myVar1, myVar2) { return myVar1 + myVar2; }
|
- Functions are called using C syntax:
machineName = blod("Hal", "9000");
|
- Remember to declare local variables to avoid
over-writing globals!
- Functions can be assigned to variables. (The variable is a reference
to the function)
function eliminateHAL() { ... }
function singToHAL() { ... }
function doSomethingDave()
{
var action;
if (misbehave(HAL)) { action = eliminateHAL; }
else { action = singToHAL; }
return action;
}
thingToDo = doSomethingDave();
thingToDo();
|
Arrays
- JavaScript has some pre-defined arrays:
- browser history list
- current document list of hyper links
- list of frames in the current window
- You cannot (strictly speaking) create your own JavaScript arrays
- Array indices begin at 0.
- Arrays are indexed using square brackets [ and ].
- Arrays have a read only length property which holds the
size of the array.
- Sample array access:
for (var i = 0; i < document.links.length; i++)
{ link = document.links[i]; }
|
Objects
- JavaScript is not truly object oriented.
- JavaScript "objects" contain data parts (properties) and functions (methods).
Creating a JavaScript Object
Create a constructor function with the same name as the object type.
The constructor can have any number of arguments.
Constructors return no result.
Constructors are responsible for defining the data and method members of an object.
function spaceShip(name, captainName, numberOfEngines)
{
this.shipName = name;
this.pilotName = captainName;
this.engines = numberOfEngines;
}
|
Remember that variables can be references to functions too!
Call the new operator to create instances of the object.
discovery = new spaceShip("Discovery", "Dave", 1);
enterprise = new spaceShip("Enterprise", "Kirk", 3);
|
Accessing Object Members
Access works just like access to a C struct's fields.
discovery.engines = 0; // Discovery's engine is not operational
enterprise.shipName = "klingonStarshipOne"; // Klingons hijack the Enterprise
|
- JavaScript objects are really just arrays indexed by strings (rather than integers).
- A special for ... in loop runs through the properties of an object
in the order they were created.
var prop;
for (prop in discovery)
{ thePropHolder = discovery[prop]; }
|