Quick JavaScript — Code Section Inventory

1.1 Hello, World!1 fragment

Fragment 1 of 1
alert("Hello, World!");

1.2 JavaScript in the Browser1 fragment

Fragment 1 of 1
<!DOCTYPE html>
<html>
  <head>
    <title>Using JavaScript</title>
  </head>
  <body>
    <script>
      alert("Hello, World!");
    </script>
  </body>
</html>

2.2.2 User-Defined Objects1 fragment

Fragment 1 of 1
let friend = { givenName: "Anna",
               surname: "Lang" };
alert("Hello, " + friend.givenName);

2.2.7 Dates1 fragment

Fragment 1 of 1
let date = new Date();
let day_of_month = date.getDate();
date.setDate(day_of_month + 100);

2.2.8 Regular Expressions2 fragments

Fragment 1 of 2
a = "Call 1-800-555-1212 today!"
b = /1-800-((\d\d\d)-(\d\d\d\d))/
//  0      12        3
c = a.match(b)
Fragment 2 of 2
c[0] = "1-800-555-1212"
c[1] = "555-1212"
c[2] = "555"
c[3] = "1212"

2.4 let and const3 fragments

Fragment 1 of 3
let x = 5, y, z = 3;  // leaves y undefined
Fragment 2 of 3
const zero = 0;
const RED = "#FF0000";
Fragment 3 of 3
const card = {suit: "clubs", pips: 2};
card = {suit: "clubs", pips: 10}; // illegal
card.pips = 10; // legal

2.9.3 Function Definitions2 fragments

Fragment 1 of 2
function average(x, y) {
  let sum = x + y; // x, y, and sum are local
  return sum / 2;
} 
Fragment 2 of 2
let avg = average(5, 10); // 7.5

2.9.4.1 Assignment Statements2 fragments

Fragment 1 of 2
x = 5;
Fragment 2 of 2
x = "abc";

2.9.4.4 If Statements3 fragments

Fragment 1 of 3
if (x < 0) {
  x = 0;
}
Fragment 2 of 3
if (x % 2 == 0) {
  x = x / 2;
}
else {
  x = 3 * x + 1;
} 
Fragment 3 of 3
if (x % 2 == 0) x = x / 2;
else x = 3 * x + 1;

2.9.4.5 While Loops1 fragment

Fragment 1 of 1
let log = 0;
while (x > 1) {
  x = x / 10;
  log = log + 1;
}

2.9.4.6 Do-while Loops2 fragments

Fragment 1 of 2
let x;
do {
  x = Math.round(1000 * Math.random());
} while (x % 7 != 0);
Fragment 2 of 2
do {
  let x = Math.round(1000 * Math.random());
} while (x % 7 != 0); // error

2.9.4.7 Traditional For Loops1 fragment

Fragment 1 of 1
let ary = [3, 1, 4, 1, 6];
for (let i = 0; i < ary.length; i += 1) {
  console.log(ary[i]);
}

2.9.4.9 Switch Statements1 fragment

Fragment 1 of 1
let v = 123.0;
let kind;
switch (v) {
  case 120 + 3:
    kind = "number";
    break;
  case "123":
    kind = "string";
    break;
  default:
    kind = "other";
}
console.log(v, "is a", kind);

2.9.4.11 Break Statements1 fragment

Fragment 1 of 1
let ary = [7, 30, 9, 20, 3, 5];
let i, j;
id: for (i = 0; i < ary.length; i += 1) {
    for (j = 0; j < ary.length; j += 1) {
      if (ary[i] == 10 * ary[j]) {
        break id;
      }
    }
  }
console.log(ary[i] + ", " + ary[j]);

2.9.4.12 Continue Statements1 fragment

Fragment 1 of 1
let ary = [3, true, 4, false, 10, "hello"];
let sum = 0;
for (let i = 0; i < ary.length; i += 1) {
  if (typeof(ary[i]) == "string") continue;
  sum = sum + ary[i];
}

2.9.5.4 Try-catch-finally1 fragment

Fragment 1 of 1
try {
  throw "I am an exception";
}
catch (v) {
  alert(v);
}

2.10 Example: Prime Numbers1 fragment

Fragment 1 of 1
<!DOCTYPE html>
<html>
<title>Using JavaScript</title>
<head>
<script>
  function isPrime(n) {
    let divisor = 2;
    while (divisor * divisor <= n) {
      if (n % divisor == 0) {
        return false;
      }
      divisor += 1;
    }
    return true;
  }
  </script>
</head>

<body>
Here are some prime numbers:
<script>
  for (let n = 2; n <= 100; n = n + 1) {
    if (isPrime(n)) {
      console(n);
    }
  }
</script>
</body>
</html>

2.11.3 Testing Example3 fragments

Fragment 1 of 3
<!DOCTYPE html>
<html>
<head>
  <title>Testing primes with Mocha and Chai</title>

  <!-- Load Mocha, Chai, and some CSS formatting -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/8.0.1/mocha.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/8.0.1/mocha.js"></script>
  <script>mocha.setup('bdd');</script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.js"></script>

  <!-- The function to be tested -->
  <script>
    function isPrime(n) {
      let divisor = 2;
      while (divisor <= n / divisor) {
        if (n % divisor == 0) {
          return false;
        }
        divisor += 1;
      }
      return true;
    }
  </script>

  <!-- The test code; here we load it from a file -->
  <script
    src='isPrimeMochaTest.js'>
  </script>

</head>
<body>
  This text goes before the results.

  <!-- The test results will be displayed here -->
  <div id="mocha"></div>

  This text goes after the results.

  <!-- Run the tests and put the result in the "mocha" div -->
  <script>
    mocha.run();
  </script>
  
</body>
</html>
Fragment 2 of 3
describe("isPrime", function() {
  let assert = chai.assert;
  it("Tests if n is a prime number", function() {
    assert(isPrime(2));
    assert.isTrue(isPrime(3));
    let x = 4;
    assert.isFalse(isPrime(x));
    assert.equal(isPrime(5), true);
  });
});
Fragment 3 of 3
isPrime
   √ Tests if n is a prime number

3.3 Destructuring11 fragments

Fragment 1 of 11
let p = { givenName: "Sally",
          familyName: "Willis",
          occupation: "doctor" };
Fragment 2 of 11
let givenName = p.givenName;
let familyName = p.familyName;
let occupation = p.occupation;
Fragment 3 of 11
let {givenName, familyName, occupation} = p;
Fragment 4 of 11
let {givenName, familyName, occupation} = p2;
// SyntaxError: Identifier 'givenName' has already been declared
Fragment 5 of 11
{givenName, familyName, occupation} = p2;
// SyntaxError: Unexpected token '='
Fragment 6 of 11
({givenName, familyName, occupation} = p2);
Fragment 7 of 11
let {familyName: name, occupation: occ} = p;
// name = "Willis", occ = "doctor"
Fragment 8 of 11
({givenName: name, country = "USA"} = p);
// name = "Sally", country = "USA"
Fragment 9 of 11
({givenName: name="Joe", age=40} = p);
// name = "Sally", age = 40
Fragment 10 of 11
function f({familyName, occupation: occ,
            age=40, gender: g="male"}) {
  // When called with f(p), familyName =
  // "Willis", occ = "doctor", age = 40,
  // and g = "male"
}
Fragment 11 of 11
let a = [11, 22, 33, 44];
let [, x, , y] = a;
// x = 22, y = 44

3.4.4 Symbols9 fragments

Fragment 1 of 9
let sym1 = Symbol();
let sym2 = Symbol("secret");
Fragment 2 of 9
let sun_dist = {"Venus": 108.2, "Earth": 149.6, "Mars": 227.9};
Fragment 3 of 9
let unit = Symbol("mkm");
sun_dist[unit] = "millions of kilometers";
Fragment 4 of 9
for (let e in sun_dist) {
  console.log(e + " = " + sun_dist[e]);
}
Fragment 5 of 9
Venus = 108.2
Earth = 149.6
Mars = 227.9
Fragment 6 of 9
console.log(unit.toString());
Fragment 7 of 9
"Symbol(mkm)"
Fragment 8 of 9
console.log(sym2.description);
Fragment 9 of 9
"secret"

3.4.7 Sets1 fragment

Fragment 1 of 1
function union(a, b) {
  return new Set([...a, ...b]);
}

function intersection(a, b) {
  return new Set([...a].filter(x => b.has(x)));
}

function difference(a, b) {
  return new Set([...a].filter(x => !b.has(x)));
}

function symmetricDifference(a, b) {
  return difference(union(a, b), intersection(a, b));
}

3.4.9 WeakMaps1 fragment

Fragment 1 of 1
let car = {make: "Suburu", year: 2018};
car = {make: "Toyota", color: "white"};

3.4.10 Promises4 fragments

Fragment 1 of 4
function yes(r) {
  console.log("yes, " + r);
}

function no(e) {
  console.log("no, " + e);
}

function doSomething(resolve, reject) {
  let r = Math.random(); 
  if (r > 0.50) resolve(r); // succeed
  throw r + " is too low";  // fail
}
Fragment 2 of 4
let promise = new Promise(doSomething);
// other work
promise.then(yes, no);
console.log("END");
Fragment 3 of 4
"END"
"no, 0.18252962330109224 is too low"

"END"
"yes, 0.938714265780423"
Fragment 4 of 4
let promise2 = new Promise(
  someFun => { return someFun(Math.random());
  }).then(function(result) { return 100 * result;
  }).then(function(result) { return 1000 + result;
  }).then(function(result) { console.log(result);
  });

3.10.1 Defining Functions1 fragment

Fragment 1 of 1
function hypotenuse(x, y) {
  function square(x) { return x * x }
  return Math.sqrt(square(x) + square(y));
}

3.10.2 Parameters and Arguments6 fragments

Fragment 1 of 6
function foo(a, b = 10, c = a * b) {
  return a + b + c;
}
console.log(foo(3)); // result is 43
Fragment 2 of 6
function foo(x, y, ...z) {
  console.log(`x is ${x}`);
  console.log(`y is ${y}`);
  console.log(`z is ${z}`);
}
Fragment 3 of 6
foo(1, 2, 3, 4, 5);
Fragment 4 of 6
"x is 1"
"y is 2"
"z is 3,4,5"
Fragment 5 of 6
let ary = [2, 7, 1, 3];
let m = Math.max(...ary);
Fragment 6 of 6
let ary2 = [...ary];

3.10.3 Functions Are Data2 fragments

Fragment 1 of 2
function square(x) {
  return x * x;
}

let square2 = square;
let result = square2(5); // 25

let myArray = new Array();
myArray[10] = square;
result = myArray[10](7); // 49
Fragment 2 of 2
myArray.sort(function(a,b) { return a - b });

3.10.4 Functions Are Objects3 fragments

Fragment 1 of 3
let square = (x) => x * x;
Fragment 2 of 3
let factorial = function f(n) {
  if (n == 0) return 1;
  return n * f(n - 1);
};
Fragment 3 of 3
nextInt.counter = 0;
function nextInt() {
  nextInt.counter += 1;
  return nextInt.counter;
}

3.10.5 Function Methods1 fragment

Fragment 1 of 1
let car = { make: "Subaru", year: 2018,
    age(now) { return now - this.year; } };
let fn = car.age;

3.10.6 Closures2 fragments

Fragment 1 of 2
function make_counter() {
  let n = 0;
  let count = function() {
    n += 1;
    return n;
  }
  return count;
}

let counter = make_counter();
console.log(counter()); // 1
console.log(counter()); // 2
Fragment 2 of 2
let v; // outside the block
{ let n = 0;
  let count = function() {
    n += 1;
    return n;
  }
  v = count;
}

console.log(v()); // 1
console.log(v()); // 2

3.10.7 Generators3 fragments

Fragment 1 of 3
function* half(n) {
  yield n;
  while (n > 1) {
    n = Math.floor(n / 2);
    yield n;
  }
}
Fragment 2 of 3
let gen = half(10);
for (i of gen) {
  console.log(i);
}
Fragment 3 of 3
gen = half(10);
let obj = gen.next();
while (! obj.done) {  
  console.log(obj.value);
  obj = gen.next();
}

3.10.8 Iterators4 fragments

Fragment 1 of 4
let range = {start:10, step: 5, end: 25};
Fragment 2 of 4
range[Symbol.iterator] =
  function* next() {
    n = this.start;
    while (n < this.end) {
      yield n;
      n += this.step;
    }
  };
Fragment 3 of 4
for (let e of range) {
  console.log(e);
}
Fragment 4 of 4
{start:12, step: 5, end: 30,
 [Symbol.iterator]: function* next() {…} }.

3.11.1 Objects13 fragments

Fragment 1 of 13
let car = {make: "Subaru", year: 2018}
Fragment 2 of 13
console.log(car.make + " " + car.year);
Fragment 3 of 13
alert(car.make + " " + car.year);
Fragment 4 of 13
car.mileage = 25041;
Fragment 5 of 13
delete car.mileage;
Fragment 6 of 13
let nums = {2: "two", 3.1416: "pi"}
Fragment 7 of 13
car.mileage = 25300;
car["mileage"] = 25300;
Fragment 8 of 13
let property = "make";
let make = "Subaru";
let age = 2;
car = {[property]: [make], year: 2020 - age}
Fragment 9 of 13
let make = "Subaru";
let year = 2018;
Fragment 10 of 13
let car = {make, year}
Fragment 11 of 13
let car = {make: "Subaru", year: 2018}
Fragment 12 of 13
for (prop in car) {
  console.log(prop + " is " + car[prop])
}
Fragment 13 of 13
"make is Subaru"
"year is 2018"

3.11.2 Creating Objects6 fragments

Fragment 1 of 6
let car = Object();  // or let car = {};
car.make = "Subaru"; // don't use 'let' here
car.year = 2018;
Fragment 2 of 6
function Car(make, year) {
  this.make = make;
  this.year = year;
  return this;
}
Fragment 3 of 6
let car = Car("Subaru", 2018);
Fragment 4 of 6
function Car(make, year) {
  this.make = make;
  this.year = year;
}
Fragment 5 of 6
let car = new Car("Subaru", 2018);
Fragment 6 of 6
let car2 = Object.create(car);
car2.make = "VW";
car2.color = "blue";

3.11.4 Methods2 fragments

Fragment 1 of 2
let now = new Date().getFullYear();
let car = { make: "Subaru",
            year: 2018,
            age: function() {
                   return now - this.year;
                 }
          }
Fragment 2 of 2
age() { return now - this.year; }

3.11.5 Optional Chaining1 fragment

Fragment 1 of 1
let cust = {
  name: "Jones",
  address: { number: 29, street: "main" }
}

3.11.7 Higher-order Functions4 fragments

Fragment 1 of 4
let nums = [12, 43, 115, 9, 65, 1001, 902];

nums.sort((a, b) => a - b);
// nums is [9,  12,  43, 65, 115, 902, 1001]

nums.sort((a, b) => b - a);
// nums is [1001, 902, 115, 65,  43,  12,  9]

nums.sort((a, b) => a % 10 - b % 10);
// nums is [1001, 902, 12, 43, 115, 65,  9]
Fragment 2 of 4
a = [1, 2, 3, 4, 5];
asq = a.map(e => e ** 2);
// asq = [1, 4, 9, 16, 25]
Fragment 3 of 4
 a = [87, -1, 92, -1, -1, 98];
afil = a.filter(x => x >= 0);
// afil = [87, 92, 98]
Fragment 4 of 4
a = [1, 2, 3, 4, 5];
asum = a.reduce((x, y) => x + y);
// asum = 15

3.11.8 Prototypes2 fragments

Fragment 1 of 2
let proto = Object.getPrototypeOf(myCar);
Fragment 2 of 2
proto.style = "sedan";

proto.toString = function() {
  return this.year + " " + this.make; };

3.11.9 Descriptors6 fragments

Fragment 1 of 6
let car = {
  make: "Subaru", year: 2018,
  toString() { return this.year + " " + this.make; }
}
Fragment 2 of 6
for (let e in car) {
  console.log(e + "=" + car[e]);
}
Fragment 3 of 6
make=Subaru
year=2018
toString=toString() {
           return this.year + " " + this.make;
         }
Fragment 4 of 6
Object.getOwnPropertyDescriptor(car, "year");
Fragment 5 of 6
[object Object] {
  configurable: true,
  enumerable: true,
  value: 2018,
  writable: true
}
Fragment 6 of 6
Object.defineProperty(car, "toString",
                      {enumerable: false,
                       configurable: false});

3.11.10.1 Classes4 fragments

Fragment 1 of 4
class Car {
  fuel = "gasoline"; // note: no "let"
  constructor(make, year) {
    this.make = make;
    this.year = year;
  }
}

let myCar = new Car("Subaru", 2018);
Fragment 2 of 4
set make(value) {
  this.make = value; // bad!
}
Fragment 3 of 4
set make(value) {
  this._make = value; // okay
}
Fragment 4 of 4
class Car {
  fuel = "gasoline";

  constructor(make, year) {
    this._make = make;
    this._year = year;
  }
  
  set make(arg) { this._make = arg; }
  
  get make() { return this._make; }
  
  set year(arg) {
    if (arg < 1903 ||
        arg > new Date().getFullYear()) {
      alert("Bad year: " + arg);
    }
    else {
      this._year = arg;
    }
  }
  
  get year() { return this._year; }
      
  age() { // method
    let now = new Date().getFullYear();
    return now - this._year;
  }
  
  toString() {
    return this._year + " " + this._make;
  }
}

3.11.10.2 Inheritance5 fragments

Fragment 1 of 5
class Person {}  // extends Object

class Customer extends Person {}
Fragment 2 of 5
constructor(...args) { super(...args); }
Fragment 3 of 5
let friend = new Person();
friend.name = "Sally";
Fragment 4 of 5
class Person {
  constructor(name) {
    this._name = name;
  }

  set name(value) {
    if (typeof value == "string") {
      this._name = value;
    } else {
      alert(value + " is not a string.");
    }
  }

  get name() { return this._name; }
}

class Customer extends Person {
  constructor(name, id) {
    super(name);
    this.id = id;
  }
}
Fragment 5 of 5
let person = new Person("Sally");
let cust = new Customer("Bill", 123);
cust.name = "William";

3.11.10.3 Overriding Methods and Fields2 fragments

Fragment 1 of 2
toString() {
  return "My name is " + this.name;
}
Fragment 2 of 2
class Over {
  value = 100;
  show() {
    return "value is " + this.value;
  }
}

class Under extends Over {
  value = 50;
}

let under = new Under();
console.log(under.show());

3.11.10.4 Class Prototypes2 fragments

Fragment 1 of 2
class Person {…}
class Customer extends Person {…}
let sally = new Customer(…);
Fragment 2 of 2
Person.prototype.initial = function() {
  return this.name[0];
}

4.1 Essential HTML1 fragment

Fragment 1 of 1
<!DOCTYPE html>
<html>
  <head>
    <title>Example HTML Page</title>
  </head>
  <body>
    <p id="p1">The user sees this part.</p>
  </body>
</html>

4.4.3 Buttons2 fragments

Fragment 1 of 2
<input type="button" value="Click me" onclick="alert('Hello')">

<button onclick="alert('Hello')">Click me
</button>
Fragment 2 of 2
<button onclick="alert('Ouch!')">
  <img src="band-aid.png"></button>

4.4.5 Text Fields4 fragments

Fragment 1 of 4
<input type="text" size="12" value="Initial text">
Fragment 2 of 4
<input id='tx1' type="text">
<br>
<input type="button"
       value="Look in text field"
       onclick="alert('You entered: ' +
         document.getElementById('tx1').value)">
Fragment 3 of 4
 <script>
   function showText(id) {
     var field = document.getElementById(id);
     alert('You entered: ' + field.value);
   }
 </script>
Fragment 4 of 4
<input type="button" value="Look in text field"
       onclick="showText('tx1')">

4.4.6 Buttons and Forms3 fragments

Fragment 1 of 3
<input type="button" value="Click me">
<input type="submit" value="Send it">
<input type="reset" value="Forget it">
Fragment 2 of 3
<button type="button">Click me</button>
<button type="submit">Send it</button>
<button type="reset">Forget it</button>
Fragment 3 of 3
<form>
  <input name='tx1' type="text">
  <input type="button"
     value="Look in text field"
     onclick="alert('You entered: ' + tx1.value)">
</form>

4.4.7 Form Verification1 fragment

Fragment 1 of 1
<form onsubmit="return validate()">
  Type a number:
  <input name='num' type="text">
  <br>
  <input type="submit">
</form>

4.4.11 Events1 fragment

Fragment 1 of 1
<input type="button" value="Wow!" id="bait"
 onclick="console.log(event.type +
                      event.target.id);">

4.5.1.3 Window Example2 fragments

Fragment 1 of 2
"use strict";
let win2, timer;

function display(str) {
  let e = document.getElementById("para");
  e.innerHTML = str;
}

function google(str) {
  console.log(window);
  win2 = window.location =
    "https://google.com" + "?q=" + str;
}

function googleIt() {
  display("Going to Google in 5 seconds.");
  let term =
    document.getElementById("search").value;
  timer = setTimeout(google, 5000, term);
}

function cancel() {
  display("");
  clearTimeout(timer);
}
Fragment 2 of 2
<button onclick="googleIt()">Google</button>
<input type="text" id="search">
<button onclick="cancel()">Cancel</button>
<br>
<p id="para"></p>

4.5.2.1 Document Properties1 fragment

Fragment 1 of 1
document.body.style.backgroundColor = "#EEEEEE"
document.body.style.color = "#999999"
document.body.style.border = "thick solid #0000FF";
document.body.style.borderColor = "#00ff00";
document.body.style.fontFamily = "Courier New, Impact"
document.body.style.fontSize = "24pt"

4.5.6 Example: showTree2 fragments

Fragment 1 of 2
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <title>showTree Example</title>
 5 
 6   <script>
 7   function abbreviate(str) {
 8     let oneLine = str.replaceAll(/\s+/g, " ").trim();
 9     if (oneLine.length <= 45) return oneLine;
10     return "'" + oneLine.substr(0, 30) +
11        " ... " + oneLine.substr(-8, 10) + "'";
12   }
13   
14   function onlyWhitespace (str) {
15     return /^\s+$/.test(str);
16   }
17   
18   function showTree(e, indent="") {
19     let s = indent + e.nodeName + " ";
20     if (e instanceof CharacterData) {
21       if (onlyWhitespace(e.textContent)) {
22         s += "[whitespace] ";
23       } else {
24         s += abbreviate(e.textContent);
25       }
26     }
27     if (e.hasAttributes) {
28       let attrs = e.attributes;
29       for (let i = 0; i < attrs.length; i += 1) {
30         if (attrs[i].value != null) {
31           s += attrs[i].name  + ":" +
32                attrs[i].value + " ";
33         }
34       }
35     }
36     if (e.innerHTML) {
37       s += abbreviate(e.innerHTML);
38     }
39     console.log(s);
40     for (node of e.children) {
41       showTree(node, indent + "|  ");
42     }
43   }
44   </script>
45 </head>
46 
47 <body>
48   <!-- Steve Jobs quote -->
49   <p><i>Everyone</i> should learn how to program
50   a computer because it teaches you how to think.</p>
51   <button onclick="showTree(document)">Show Tree</button>
52 </body>
53 </html>
Fragment 2 of 2
#document 
|  HTML '<head> <title>showTree Example ...  </body>'
|  |  HEAD '<title>showTree Example</title ... /script>'
|  |  |  TITLE showTree Example
|  |  |  SCRIPT 'function abbreviate(str) { let ...  "); } }'
|  |  BODY '<!-- Steve Jobs quote --> <p>< ... /button>'
|  |  |  P '<i>Everyone</i> should learn h ... o think.'
|  |  |  |  I Everyone
|  |  |  BUTTON onclick:showTree(document) Show Tree