Introduction to JavaScript

CSE 190 M (Web Programming) Spring 2008

University of Washington

Reading: Chapter 3 sections 3.2 - 3.3

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.

Valid XHTML 1.1 Valid CSS!

What is JavaScript?

Differences between JavaScript and Java

Java + marijuana = JavaScript

Linking to a JavaScript file (example)

<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>

Popup boxes

alert("message");     // message
confirm("message");   // returns true or false
prompt("message");    // returns user input string
alert confirm prompt

JavaScript keywords

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


Variables and types

var name = expression;
var clientName = "Connie Client";
var age = 32;
var weight = 137.4;

Number type

var enrollment = 99;
var median142Grade = 2.8;

Operators and expressions

var credits = 5 + 4 + (2 * 3);

Comments (same as Java)

// single-line comment

/* multi-line comment */

for 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

More about String

Math object

var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);

if/else statement (same as Java)

if (condition) {
	statements;
} else if (condition) {
	statements;
} else {
	statements;
}

Boolean type

var iLike190M = true;
var ieIsGood = "IE6" > 0;   // false

while loop (same as Java)

while (condition) {
	statements;
}
do {
	statements;
} while (condition);

Defining functions

function name(parameterName, ..., parameterName) {
	statements;
}
function quadratic(a, b, c) {
	return -b + Math.sqrt(b * b - 4 * a * c) / (2 * a);
}

Calling functions (same as Java)

name(parameterValue, ..., parameterValue);
var root = quadratic(1, -3, 2);

Scope: global and local variables

var count = 1;

function f1() { 
	var x = 999;
	count = count * 10;
}
function f2() { count++; }

f2();   // this is "main"
f1();

Special values: undefined and null

var ned = null;
var benson = 9;

// at this point in the code,
//   ned is null
//   benson is 9
//   caroline is undefined

Arrays

var 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

Array methods

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

Splitting Strings: 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]);
}

Common JavaScript errors

Debugging JS code in Firebug

Firebug JS

JSLint

JSLint