CSSE 290 Web Programming

Lecture 14: JavaScript Language Featurees

Reading: 8.1 - 8.4

Attribution:Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Otherwise noted: Claude Anderson was given permission to modify the slides for CSSE 290 at Rose-Hulman by author Jessica Miller. The authors' original slides, based on Web Programming Step by Step, can be seen at http://webstepbook.com.
Some of the examples in some days' slides are from David Fisher at Rose-Hulman, who was kind enough to allow me to use them. My intention is to mark these examples with [DSF].

Valid HTML Valid CSS!

Announcements

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 = sum + i;
}
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
	s2 += s1[i] + s1[i];
}
// s2 stores "hheelllloo"

Math object

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

Logical operators

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
if ("web dev is great") {  /* true */ }
if (0) {  /* false */ }

Special values: null and undefined

var ned = null;
var benson = 9;
var caroline;

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

while loops (same as Java)

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

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[4] = "Curly";    // stooges.length is 5
stooges[4] = "Shemp";    // stooges.length is 5

Array methods

var a = ["Stef", "Jason"];   // Stef, Jason
a.push("Brian");             // Stef, Jason, Brian
a.unshift("Kelly");          // Kelly, Stef, Jason, Brian
a.pop();                     // Kelly, Stef, Jason
a.shift();                   // Stef, Jason
a.sort();                    // Jason, 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"

Document Object Model (DOM)

a set of JavaScript objects that represent each element on the page

DOM

DOM element objects

dom object

Accessing elements: document.getElementById

var name = document.getElementById("id");
<button onclick="changeText();">Click me!</button>
<input id="output" type="text" value="replace me" />
function changeText() {
	var textbox = document.getElementById("output");
	textbox.value = "Hello, world!";
}

More advanced example

<button onclick="swapText();">Click me!</button>
<span id="output2">Hello</span>
<input id="textbox2" type="text" value="Goodbye" />
function swapText() {
	var span = document.getElementById("output2");
	var textBox = document.getElementById("textbox2");
	var temp = span.innerHTML;
	span.innerHTML = textBox.value;
	textBox.value = temp;
} 

More about JavaScript functions

For this excursion, many of the ideas and much of the code come from Chapter 3 of Secrets of the JavaScript Ninja by John Resig and Bear Bibeault, ©2013 by Manning Publications.

Download and unZIP the code, linked from today's session on the schedule page.

JavaScript functions are "first-class" data, unlike Java methods.

An advantage of first class functions -

Simplicity of expression. Example: sort an array into reverse order.
First, in Java:

Integer[] values = {213, 16, 297, 34, 10, 512, 57};
java.util.Arrays.sort(values, new Comparator(){
  public int compare(Integer value1, Integer value2) {
	return value2 - value1;
  }
});

Now, in JavaScript:

var values = [213, 16, 297, 34, 10, 512, 57];
values.sort(function(value1, value2) { return value2 - value1; });

We'll see more about how this works in JavaScript later. Which appears to be more straightworward?

Will Java 8 have first-class functions? One opinion (http://stackoverflow.com/questions/15221659/java-8-lambda-expression-and-first-class-values)

Parts of a JavaScript function literal

  • the function keyword
  • an optional name. If specified, must be a valid JavaScript identifier
  • a parenthesized, comma-separated, possibly empty list of parameter names
    • each must be a valid JavaScript identifier
  • the body, a list of zero or more JavaScript statements, enclosed in curly braces

An anonymous function is not given a name; its name is the empty string.

Let's examine and run the listing-3.1.html file from Ninja Chapter 3

JavaScript Scope Rules

  • the function (not the { ... } block as in C and Java) is the smallest "scoping" unit" in JavaScript.
  • variable declarations are in scope from where they are declared to end of function declaration
  • named functions are in scope within the entire function within which they are declared
  • for applying the above rules to global declarations, pretend that all global code (outside of all function declarations) is inside one "big" function

An anonymous function is not given a name; its name is the empty string.

Example (from Ninja book)

	function outer(){
       var a = 1;
        function inner(){ /* does nothing */ }
        var b = 2;
        if (a == 1) {
          var c = 3;
		}
     }

    outer();

Let's examine and run listing-3.2.html from Ninja Chapter 3 <\div>