JavaScript Operators
| Operator |
Description |
Comment |
| /* */
// |
encloses multi-line comment
indicates rest of line is a comment |
|
| = |
assignment |
|
| ; |
terminates a line (optional) |
x = 1 or x = 1; are both
acceptable in JavaScript Note: semi-colons can
be used to separate more than one statement on a line but this style of
coding is inadvisable. |
| == |
checks for equality, e.g.
if (x==1) |
if you use single = when
trying to check for equality: if(j=5)
{statement}
then the expression evaluates to true and the
expression is also executed (j is assigned 5). This is comparable to
bug-prone ‘C’ behaviour |
| !=
> >=
< <= |
checks for inequality
greater than, gr. than or equal
less than, less than or equal |
|
| ! |
NOT (negates a boolean
expression) |
|
| += -= *= |
shorthand operator to
add/subtract/multiple two numbers and assign to first |
x += s (is like x = x + s,
doing addition or string concat. depending on whether these are numbers
or strings) |
| ++ -- |
quick increment (decrement) |
x++ is like x = x + 1 |
| &&
|| |
Logical and,
Logical or respectively. |
(a && b) if a is false, b is
not evaluated (or executed) (a || b) if a is
true, b is not evaluated (or executed) |
| a ? b : c |
Conditional operator |
if boolean expr. "a" is
true, use expr. "b", otherwise use expr. "c" |
Variables
JavaScript is a very loosely-typed language:
- Variables do not need to be declared before use (but declaration is
supported and is good style)
- A variable’s type is determined by the value assigned. So x=1 causes it
to be a number (you can determine the current data type of a variable by
using typeof(x)). The same variable can become a string on the next line by
assigning it a string like x = "walk". This is called "dynamic typing". This
behaviour may be alarming to developers used to "tighter" (more restrictive)
languages.
- An array can be declared but each element in the array will take on its
own variable type according to the current value assigned to that element.
So the first array element can be a number, the second a string and the
third array element could be a complex object.
- Variable values are automatically converted between variable type, as
needed. So, if a "x" is concatenated with 13, then the number is
automatically converted to string to make the operation possible.
- Booleans true and false convert to "true" and "false" for strings and 1
and 0 for numbers.
- Declaration: if desired, a variable can be declared (and
optionally initialized) with "var" statement, e.g. var x or var j = 1; The
declaration doesn’t limit future data types it can take (either x or j in
the preceding example could later be turned into an array or object with an
appropriate assignment).
- Global Variables: global variables (i.e. global to the page) are
declared in the lines immediately after <SCRIPT LANGUAGE=JavaScript> but
before the first JavaScript function declaration. These "global" (or
page-level) variables last for the life of the page.
- Why use Var: One question JavaScript raises is: why declare
variables at all? Declaration doesn't limit the data type and JavaScript
will "create" a variable on first use anyway. Two benefits of explicit
declaration are:
- it provides a consolidated list of local variables used in a
function (for easier readability and maintainability)
- it can "protect" global variables from inadvertent corruption by
functions. If a function has a local variable with the same name as a
global variable but the local variable is declared with var, then the
local variable will take precedence while the function is executing (and
so it will leave the global variable untouched). This may be
particularly important for general-purpose functions whose author may
not be aware of the global variables names on every page where it is
used. A distinct naming convention for globals would be an alternative
way of avoiding such corruption.
- Array: an array is declared using the new keyword. The length of
the array is optional.
investmentTypes = new Array(5)
If extra array elements are needed, JavaScript
automatically adds them.
So investmentTypes[6] = "options" would lengthen the
array. JavaScript provides a rich set of supporting functions for arrays
such as length (# elements), sort, reverse, push, pop, etc.
- Custom (or User-defined) Object: a function can be used to
implement a custom object in JavaScript as follows:
function graphLoc (xloc, yloc) {
this.xloc = xloc
this.yloc = yloc
}
The "object" can then be instantiated using the "new"
keyword as follows:
baseLoc = new graphLoc(24, 32)
An array of this object could be declared as follows:
plotPoints = new Array(3)
plotPoints[0] = new graphLoc(1, 2)
plotPoints[1] = new graphLoc(3, 2)
plotPoints[2] = new graphLoc(5, 2)
The third plot point could then be displayed:
document.write("xloc = " + plotPoints[2].xloc + " yloc = " + plotPoints[2].yloc)
Note: there is nothing stopping you from accidentally
referring to an invalid element in the object (e.g. plotPoints[1].xlc).
JavaScript simply adds the new "element" to the custom object.
Data Types
According to the last value assigned to a variable, it will
"become" a data type (or an object). Each data type has its own series of rules
and supporting functions. These are outlined below.
STRING
- a string is a series of zero or more characters
- string literals can be surrounded by single or double quotes (as long as
left and right quotes match)
- there are a number of supporting string functions, e.g.
myString.subString(), myString.toUpperCase(), myString.search()
- there are also some string properties, e.g. myString.length
- to explicitly convert a string to a number, use parseInt() or
parseFloat()
NUMBER
- a number can be integer or floating-point (i.e. decimal). Numbers are
64-bit in JavaScript and are in the range 1.79 E+308 to 2.22 E-308. A number
will be considered integer if it currently has no decimal portion (e.g.
decimals 3.4 + 4.6 = 8 which is an integer).
- to test if a string is not a valid number, use the JavaScript function
isNaN()
- there are a number of supporting math functions (sin, log, random,
round, etc.)
- to explicitly convert a number to a string, do the following:
num.toString() or ("" + num)
BOOLEAN
- boolean (with values true, false)
NULL
- null is completely devoid of value (the value is all lowercase).
- can be tested if (j == null)
- when added to a number, it is treated as zero. When concatenated to a
string, it converts to "null".
- a database null value is converted to a zero-length string (so it is
different from a null data type)
DATE
- dates can be created using the Date object. JavaScript stores the number
of milliseconds since Jan 1, 1970. A number of supporting functions are
provided (e.g. setYear, getMonth, etc.).
- Counter-intuitively, months run from 0 to 11 (0=Jan).
- Early browser versions (3 and especially 2) have many date-related bugs.
Simple Output Statement
JavaScript can output values with the write command.
var hours = 12
var pay = 20
document.write("Hours worked: " + hours + "Payrate: " + pay);
Flow Control Constructs
Statements blocks are delimited with { }. The brace brackets
are optional for single level constructs (e.g. an if with no embedded
construct) but it is good style to always include them.
IF Statement
if ((a==b) && (b<c)) {
statements
} else {
statements
}
Note: when the block delimiters{} are excluded, JavaScript
assumes there is a single line in the scope of "if" or "else". If there are
multiple lines before the else, an error will result.
SWITCH Statement
switch (age) {
case 1:
...
break;
case 2:
...
break;
default:
...
}
Note: if break is omitted, the code in the remaining case
statement(s) is automatically executed (until a break is encountered or the
switch statement is complete).
FOR Loop
for(i=0; i<10; i++) {
...
}
WHILE Loop
i=0
while (i<10) {
...
i++
}
WITH Statement
with (document.form1) {
...
}
Note: when JavaScript encounters an otherwise unknown
identifier inside the with, it tries to
prefix the object specified by the with.
Functions
Access
All functions are public. JavaScript does not support private vs. public
functions.
Function Declaration
function product (var1, var2) {
result = var1 * var2
return result
}
As usual, variable types of the function arguments are not
explicitly specified. The fact that the function returns a value only becomes
"known" when the return statement within the function is executed.