Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp and Jessica Miller and are licensed under the Creative Commons Attribution 2.5 License.
Special thanks to Hélène Martin for creating the 2007 version of these slides and presenting this material to the students.
+
= JavaScript
<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>
head.js file
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
abstract 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
var, functionvar name = expression;
var clientName = "Connie Client"; var age = 32; var weight = 137.4;
var keyword (case sensitive)typeofvar enrollment = 99; var median142Grade = 2.8;
int vs. double)
String into a Number
var name = parseInt("String"); var name = parseFloat("String");
parseInt("123hello") returns 123parseInt("booyah") returns NaN (not a number)var credits = 5 + 4 + (2 * 3);
+ - * / % ++ -- = += -= *= /= %=
> < >= <= && || ! == != === !==
== just checks value ("5.0" == 5 is true)=== also checks type ("5" === 5 is false)"2" * 3 is 6, 5 < "7" is true
// single-line comment
/* multi-line comment */
<!-- comment -->/* comment */// commentfor loop
(same as Java)
for (initialization; condition; update) { statements; }
var sum = 0;
for (var i = 0; i < 100; i++) {
sum += i;
}
String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
charAt,
indexOf,
lastIndexOf,
replace,
split,
substring,
toLowerCase,
toUpperCase
charAt returns a one-letter String (there is no char type)length property (not a method as in Java)" " or ' ' (useful later)String\' \" \& \n \t \\String
var s1 = String(myNum);var s2 = count + " bananas, ah ah ah!";String
var firstLetter = s[0];var lastLetter = s.charAt(s.length - 1);if/else statement
(same as Java)
if (condition) { statements; } else if (condition) { statements; } else { statements; }
if/else statementvar iLike190M = true; var ieIsGood = "IE6" > 0; // false
Boolean
if ("Marty is great") { // true, of course!
"falsey" values: 0, 0.0, NaN, "", null, and undefined
Boolean explicitly
var boolValue = Boolean(otherValue);var boolValue = !!(otherValue);while loop
(same as Java)
while (condition) { statements; }
do {
statements;
} while (condition);
break and continue keywords also behave as in Javafunction 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 = count * 10;
}
function f2() { count++; }
f2(); // this is "main"
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?)undefined and null
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson is 9
// caroline is undefined
undefined : has not been declared, does not existnull : exists, but was specifically assigned a null valuevar name = []; // empty array var name = [value, value, ..., value]; // pre-filled name[index] = value; // store element
var ducks = ["Huey", "Dewey", "Louie"]; var stooges = []; // stooges.length is 0 stooges[0] = "Larry"; // stooges.length is 1 stooges[1] = "Moe"; // stooges.length is 2 stooges[9] = "Curly"; // stooges.length is 10
length property (grows as needed when elements added)
var a = ["Stef", "Amit"]; // Stef, Amit
a.push("Brian"); // Stef, Amit, Brian
a.unshift("Kenneth"); // Kenneth, Stef, Amit, Brian
a.pop(); // Kenneth, Stef, Amit
a.shift(); // Stef, Amit
a.sort(); // Amit, Stef
split 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"
for (var i = 0; i < a.length; i++) {
alert(a[i]);
}
split breaks apart a string into an array using a delimiterjoin merges an array of strings into a single string, placing the delimiter between themMy program does nothing.(most errors produce no output)
It just prints undefined. (many typos lead to undefined variables)alert at the top of it and make sure it appears.
Check the bottom-right corner of Firefox for syntax errors.