<head> section of
HTML document.
<script type="text/javascript">
<!--
// code here
// -->
</script>
.js file).
To include JavaScript code in another file, do:<script type="text/javascript" src="prog.js">
</script>
alert, open,
java, this, self.NumberStringBooleanUndefinedNullNumber.Boolean: true or false
Null: only value is null
(either as a primitive or an object)
null is value an object reference has when
it doesn't refer to any object.Undefined: only value is undefined
(value of a variable not yet assigned a value)
falseNaNvar.var declaration.+, -, /, *, %(remainder after
division).-(sign), --, ++.*, /, %; +, -.Math ObjectNumber objects.floor: truncates floating point numbersround: rounds floating point numbersmax: finds maximum of two numbersNumber ObjectNumber.Number.PI the value of pi.NaN)isNaN() used to check if a variable has the value
NaNtoString() -- converts number calling it to a
stringvar num = 2.28;
.
.
.
str_num = num.toString();+ operator.NaNy = 8"y + 2 = " + y + 2 gives "y + 2 = 82"
Fix: "y + 2 = " +(y + 2) gives "y + 2 = 10"String primitives,
as if they were objects.length
var str = "Happy";
var len = str.length;
// len = 5| Method | Parameters | Result |
|---|---|---|
charAt |
one number | the character at specified location |
indexOf |
one-character string | the position in the String object of the parameter |
substring |
two numbers | the substring of the String object from the position
given by the first parameter to the position given by the second |
toLowerCase |
no arguments | converts all uppercase letters in the string to lowercase |
toUpperCase |
no arguments | converts all lowercase letters in the string to uppercase |
var str="PIC 40A is fun!";
str.charAt(5); // returns 0
str.indexOf('C'); // returns 2
str.substring(4, 8); // returns "40A i"
str.toLowerCase(); // str is now "pic 40 is fun!"
parseIntparseFloatNaN is returned.typeof OperatorReturns the type of its single operand ("number", "string", "boolean") or "object" if the operand is an object or "null".
Same as C++: +=, -=, *=, /=, %=
Document object.Window object.Window object has two properties:
document
(Document object), andwindow
(Window object)Document
object)writeln
document.writeln("<h1>Heading into
JavaScript</h1>");write
document.write("<h1>Happy Days ");
document.writeln("Are Here Again</h1>");
//displays: Happy Days Are Here Again as <h1> header<br /> in a write or
writeln argument to get multiple lines of textdocument.writeln("<h1>Happy Days<br />Are Here Again</h1>");
// displays: Happy Days
// Are Here Again
// as a level 1 headerWindow
object)alert
OK.alert("Always be alert to changes in the wind!");
.confirm
OK and Cancel.true for OK and
false for Cancelvar query = confirm("Continue program?");prompt
OK and
Cancel.parseInt or parseFloat to
convert string to a number.prompt("Enter an integer", "");==, !=, >, >=, <, <====, !== (stand for strict equality, inequality)var but not yet assigned a
variable is false.=== or !==, JavaScript attempts to
convert operands to type that can be compared.
true == 1 // true
true === 1 // falseUses short-circuit evaluation, like C++ and Perl.
if-elseif- statements, use multi-way branching.switch statementSame as in C++
while loops
var n = 1, product = 1;
while (n <= 5) {
product *= n;
n++;
}for loop
var prod = 1;
for (var i = 1; i <=5; i++)
prod *= i; // i local to for loopdo-while loop
do {
.
.
.
} while(condition);parseInt, parseFloatfunctionreturn statement required to return control to the point
where the function was called (either return; or
return expr;)<body> section
of the document and define them in the <head>.var to declare variables within a function -- makes them
local variables (without using var, they are global).arguments.
arguments has property length.new expression,
which must include a
call to a constructor methodvar default_circle = new Object(); // creates a blank object
default_circle.radius = 1.0;
default_circle.center = new Object();
default_circle.center.x_coord = 0;
default_circle.center.y_coord = 0;
var rad=default_circle.radius;.var rad = default_circle["radius"];undefined returned.delete method, e.g.,
delete default_circle.radius;for-in loop
foreachfor (identifier in object)
statement;
for (var prop in default_circle)
document.writeln("<p>Name: " + prop + "; value: " + default_circle[prop] + "</p>");Array.Array Object Creationvar arr = new Array(5); // creates array of length 5var a = new Array();for (var i = 0; i < 5; i++) a[i] = i + 1;So,
a is an array of size 5.var b = [2, 4, 6, 8, "appreciate"];
new not required to create the Array
object done by interpreter automatically upon seeing
initializer list.var b = new Array(2, 4, 6, 8, "appreciate");
var b = [2, 4, , 8, "appreciate"];b[2] = 6;undefinedlength
propertyb.length = 25; -- makes length of array
b 25var len = arr.length; -- so, len
is equal to the length of arr, 5Array methodsjoin: turns all elements into strings and
joins them together into a single string. With no arguments, a
comma separates the elements.reverse: reverses the order of elements in the arraysort: uses string comparison to determine the sorting
order (i.e., via ASCII values).
sort takes an optional argument, the comparator
functionconcat: concatenates its parameters to the end of the
arrayslice: returns the part of the array starting from the
position of the first parameter and up to, but not including, the
position of the second parameterpush, pop, shift, unshift: like the Perl functionsnew operator
function Circle (rad, cx, cy) {
this.radius = rad;
this.centerx = cx;
this.centery = cy;
}this_circle = new Circle(5, 4, 2);
function display_circle () {
document.write("Circle: <br />");
document.write("Radius: " + this.radius + "<br />");
document.write("Center: (" + this.centerx + ", " + this.centery + ")<br />");
} So, the constructor must look like:
function Circle (rad, cx, cy) {
this.radius = rad;
this.centerx = cx;
this.centery = cy;
this.display = display_circle;
}
Then, to display the circle, do: this_circle.display();Circle: Radius: 5 Center: (4, 2)
String object class.search: returns first position of the character in the
match (-1, if no match).replace: corresponds to s/// in Perl,
stores matches in $1, $2, etc.var str = "Sally sells seashells by the seashore."; str.replace(/sea/g, "cow");replaces "sea" in "seashells" and "seashore" by "cow" and stores "sea" in "seashells" in
$1 and the
"sea" in "seashore" in $2. split: corresponds to split in Perl