Except where otherwise noted, the contents of this presentation are © Copyright 2007 Marty Stepp and are licensed under the Creative Commons Attribution 2.5 License.
document.write()
document.write("message");
var name = value;
var clientName = "Connie Client"; var age = 32; var weight = 137.4;
var
keywordabstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with
+ - * / % ++ -- = += -= *= /= %= == != > < >= <= && || !
==
just checks value ("5.0" == 5
is true
)===
also checks type ("5" === 5
is false
)5 < "7"
is true
for
loopfor (initialization; condition; update) { statements; }
for (var i = 0; i < 10; i++) { document.write("<p>" + i + " squared = " + (i * i) + "</p>"); }
body
(runs when page loads)head
(runs when events occur).js
script filebody
(example)<body> ... <script type="text/javascript"> Javascript code </script> ... </body>
head
(example)<head> ... <script type="text/javascript"> Javascript code </script> ... </head>
<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>
head
or body
.js
fileString
typevar clientName = "Connie Client";
charAt
,
indexOf
,
lastIndexOf
,
replace
,
split
,
substring
,
toLowerCase
,
toUpperCase
var fName = s.substring(0, s.indexOf(" "));
charAt
method returns a value of type String
char
type in Javascript)length
property
clientName.length
is 13
" "
or ' '
(this is useful later)String
\' \" \& \n \t \\
String
var s = String(myNum);
var s = count + " bananas, ah ah ah!"
<
automatically convertvar enrollment = 99; var median142Grade = 2.8;
String
into a Number
var integerValue = parseInt("String");
var floatValue = parseFloat("String");
parseInt("123hello")
returns 123
parseInt("booyah")
returns NaN
(not a number)if/else
statementif (condition) { statements; } else if (condition) { statements; } else { statements; }
if/else
statementBoolean
type on next slide)var iLike190M = true;
Boolean
if ("Marty is great") { // true, of course!
...
}
0
, NaN
, ""
, null
, and undefined
are all false
true
Boolean
explicitly
var boolValue = Boolean(otherValue);
while
loopwhile (condition) { statements; }
do { statements; } while (condition);
break
and continue
keywords also behave as in Java
// single-line comment
/*
multi-line comment
*/
A "Person of the Day" page has been made for this class. Today's winner is Marty, but you have two favorite pictures of him!
Randomly choose between these two pictures on each page refresh.
function name(parameterName, ..., parameterName) { statements; }
function quadratic(a, b, c) { return -b + Math.sqrt(b*b - 4*a*c) / (2*a); }
var
is not written on parameter declarationsreturn
statement return an undefined
valuename(parameterValue, ..., parameterValue);
var root = quadratic(1, -3, 2);
undefined
value
var count = 1;
function f1() {
var x = 999;
count *= 10;
}
function f2() { count++; }
f2();
f1();
count
above is global (can be seen by all functions)x
above is local (can be seen by only f1
)f1
and f2
can use and modify count
(what is its value?)alert("message"); // message confirm("message"); // returns true or false prompt("message"); // returns user input string
var today = new Date(); // today var midterm = new Date(2007, 4, 4); // May 4, 2007
getYear
returns a 2-digit year; use getFullYear
insteadgetDay
returns day of week from 0 (Sun) through 6 (Sat)getDate
returns day of month from 1 to (# of days in month)Date
stores month from 0-11 (not from 1-12)
<h2 onclick="myFunction();">Click me!</h2>
onclick
is just one of many event HTML attributes we'll see later (complete list)var stooges = new Array(); stooges[0] = "Larry"; stooges[1] = "Moe"; stooges[2] = "Curly";
var stooges = new Array("Larry", "Moe", "Curly");
var stooges = ["Larry", "Moe", "Curly"];
var a = new Array(); a.push("Morgan"); // Brian a.push("Brian"); // Morgan,Brian a.unshift("Kenneth"); // Kenneth,Morgan,Brian a.push("Helene", "Jeff"); // Kenneth,Morgan,Brian,Helene,Jeff a.shift(); // Morgan,Brian,Helene,Jeff a.pop(); // Morgan,Brian,Helene a.sort(); // Brian,Helene,Morgan
push
and pop
add and remove from end of arrayunshift
and shift
add and remove from front of arrayshift
and pop
return the element that is removedsplit
and join
var s = "the quick brown fox"; var a = s.split(" "); // [the,quick,brown,fox] a.reverse(); // [fox,brown,quick,the] s = a.join("!"); // "fox!brown!quick!the"
split
breaks apart a string into an array using a delimiterjoin
groups an array of strings into a single string, placing the delimiter between themundefined
and null
var ned;
var benson = 9;
// at this point in the code,
// ned is null
// benson is 9
// caroline is undefined
undefined
: has not been declarednull
: has been declared but not assigned a valuetypeof
function
typeof(value)
function foo() { alert("Hello"); }
var a = ["Huey", "Dewey", "Louie"];
true
:
typeof(3.14) == "number"
typeof("hello") == "string"
typeof(true) == "boolean"
typeof(foo) == "function"
typeof(a) == "object"
typeof(null) == "object"
typeof(undefined) == "undefined"
setTimeout
, clearTimeout
function delayedMessage() {
var myTimer = setTimeout("alert('Booyah!');", 5000);
}
<h2 onclick="delayedMessage();">Click me now!</h2>
setTimeout
executes a piece of code once after a given number of millisecondsclearTimeout
and pass the timer object
clearTimeout(myTimer); // cancel self-destruct sequence!
setInterval
, clearInterval
function repeatedMessage() {
var myTimer = setInterval("alert('Rudy!');", 1000);
}
<h2 onclick="repeatedMessage();">Click me now!</h2>
setInterval
executes a piece of code repeatedly, every given number of millisecondsclearInterval
and pass the timer object
clearInterval(myTimer); // please make it stop!
function delayed(text) {
var myTimer = setTimeout("alert(text);", 1000);
}
<h2 onclick="delayed('hello');">Click me now!</h2>
setTimeout
and setInterval
will execute later, after your function is done runningarguments
arrayfunction example() { for (var i = 0; i < arguments.length; i++) { alert(arguments[i]); } }
example("how", "are", "you");
arguments
representing the parameters passedvar map = new Array(); map[42] = "the answer"; map[3.14] = "pi"; map["champ"] = "suns";
Map
collection or a hash table data structure...
for (var name in arrayOrObject) { do something with arrayOrObject[name]; }