Computer Science 15-237
Class Notes:  Getting Started with Javascript


Note: Grayed-out portions are not part of this week's core material (so, do not use those techniques on hw1, and they will not appear on quiz1).


  1. Required Reading
    1. MDN (Mozilla Developer Network) JavaScript Guide
    2. MDN (Mozilla Developer Network) JavaScript Reference
    3. w3schools Javascript tutorial (though not without its critics...)
    4. MDN Introduction to Object Oriented Javascript
       
  2. Javascript is...
    1. Interpreted
    2. Garbage Collected
    3. Dynamically Typed
    4. Object-Based (nearly all values are objects)
    5. Prototype-Based
    6. Optionally Functional
    7. Fast (if written correctly)
    8. EcmaScript (basically)
    9. The default scripting language of the browser
    10. But also used outside the browser!
       
  3. Running Javascript (the bare minimum)
     
    1. Place Javascript directly in HTML file

      <html>
      <script>
          // your script here
      </script>
      </html>
       
    2. Place Javascript in its own file

      <html>
      <script src="myCode.js">
      </script>
      </html>
       
    3. Simple Input/Output (without forms)
       
      1. "Print" with alert(msg)

        alert("This will pop up in an alert box");
         
      2. "Print" with document.write(msg)

        document.write("This will be added to the document itself.");
         
      3. "Print" with println(msg) function

        function println(msg) { document.write(msg + "\n<br>"); }
        println("Here we are calling our own println function!");
        println("What fun!");
         
      4. "Print" with console.log(msg)

        alert("View console to see the log line.");
        alert("For example, in opera, open DragonFly.");
        console.log("This will appear in the web console. Good for debugging!");

         
      5. Read with prompt(msg)

        name = prompt("What is your name?");
        document.write("Howdy, " + name + "!!!");
         
    4. How to Write a Function
       
      1. Named

        function f(x) { return 2*x; }
        document.write("f(3) = " + f(3));
         
      2. Unnamed (anonymous)

        var f = function(x) { return 3*x; };
        document.write("f(4) = " + f(4));
         
  4. Types
     
    Type Examples / Comments
    number (typeof 42) == (typeof 3.14) // "number"
    boolean (typeof true) == (typeof false) // "boolean", lowercase
    string 'use single quotes' + "or double quotes"
    function function f() { } alert(typeof f); // "function"
    object alert(typeof document); // "object"
    alert(typeof [2,3]); // an array is an "object"
    var x = null;  alert(typeof x); // null is also an "object"
    undefined var x;  alert(typeof x); // "undefined"

     

  5. Scope
    1. Declared with "var" --> local or global
    2. Declared without "var" --> always global!  (don't do this)
    3. No block scope!
      1. Variables are local to function, not block

        var x = 5;
        { var x = 3; }
        alert(x); // surprised?
         
      2. Hoisting: local variables all visible regardless of where they are defined (so define them at the top of each function)

        alert("At first x is " + x);  // does not crash!
        var x = 5;
        alert("And now x is " + x);
         
  6. Type Conversions
    1. Explicit:  parseInt(s), parseFloat(s)

      alert(parseInt("25.2")*3);   // 75
      alert(parseFloat("25.2")*3); // 75.6
       
    2. Explicit:  Number(obj), String(obj)

      alert(Number("123") + 45); // 168
      alert(123 + String(45)); // "12345"
       
    3. Implicit: numeric expressions, string -> number

      alert("4" * 3); // 12
      alert("4" - 3); // 1
      alert(42 / "3"); // 14

       
    4. Implicit: concatenation (+), number -> string

      alert("4" + 3); // "43", not 7
       
    5. Explicit: + operator (string to number)

      alert("4" + 3); // "43"
      alert((+"4") + 3); // 7
       
    6. Implicit: Boolean false equivalents ("falsy" values)
      • false, undefined, null, 0, NaN, the empty string ("")
         
  7. Operators
     
    Category Operators
    Arithmetic +, -, *, /, %, ++ (pre/post), -- (pre/post), - (unary), + (unary)
    Relational ==, !=, === (strict equal / same type), !==, <. <=, >=, >
    Bitwise <<, >>, >>>, &, |, ^, ~
    Assignment +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=
    Logical &&, ||, !
    Conditional ?:   (condition ? trueValue : falseValue)
    Comma ,  (A,B) evaluates A and B, returns result of B
    Special delete, in, instanceof, new, this, typeof, void
    (Deferred until we cover objects...)

     

  8. Short-Circuit Evaluation
     
    1. &&

      function f(x) { alert("f, x=" + x); return x; }
      alert(f(5) && f(false) && f("wow"));
       
    2. ||

      function f(x) { alert("f, x=" + x); return x; }
      alert(f(false) || f(5) || f("amazing"));
       
  9. Approximate values of floating-point numbers
    alert(0.1 + 0.1 + 0.1); // 0.30000000000000004
  10. Statements
     
    Type Examples / Comments
    block { s1; s2; s3; }
    conditional if (condition) { trueBlock; } else { falseBlock; }
    switch // As in C or Java
    switch (expression) {
        case labell:
            statements1;
        case label2:
            statements2;
        default:
            statementsN;
    }
    for loop for (initializer ; condition ; incrementer)
        statement
    for (var x = 3; x < 6; x++) {
        document.write(x);
        document.write("<br>"); // newline
    }
    document.write("Finally, x =", x);
    while loop As in most languages
    do...while loop do
        statement
    while (condition);


    As in some languages.
    Same as while loop, but tests at the end of each pass.
    break/continue As in most languages
    for...in
    for each ... in
    (Deferred until we cover objects...)
    throw As in most languages (but you can throw most anything)
    try ... catch try {
        alert("nothing wrong yet!");
        alert(x); // x is undefined!
        alert("this will never happen!");
    }
    catch (e) {
        alert("caught: " + e);
    }
    finally {
        alert("do stuff like close files here");
    }

     

  11. Functions
    1. Functions as first-class values

      function map(fn, list) {
          var result = [ ]
          for (var i=0; i<list.length; i++)
              result[i] = fn(list[i])
          return result;
      }
      function add1(x) { return x+1; }
      function add2(x) { return x+2; }
      alert(map(add1, [1,2,3]));
      alert(map(add2, [1,2,3]));
       
    2. Function callbacks

      function f(){
          alert("hi");  // this may be annoying...
      }
      setInterval(f, 2000);
       
    3. Anonymous Functions (Function Expressions)

      alert(map(function(x){return x+3;}, [1,2,3]));
       
    4. Optional Parameters

      function f(msg, priority) {
          priority = priority || 42;
          alert(msg + ", priority=" + priority);
      }
      f("urgent", 1);
      f("not so urgent");
      f("Was this priority 0?", 0);

      // OR....

      function f(msg, priority) {
          if (priority === undefined)
              priority = 42;
          alert(msg + ", priority=" + priority);
      }
      f("urgent", 1);
      f("not so urgent");

       
    5. arguments Object

      function f() {
          alert("argument count: " + arguments.length);
          for (var i=0; i<arguments.length; i++)
              alert(i + ": " + arguments[i]);
      }
      f("wow", 42, true);
       
    6. Dynamic Invocation (apply and call)

      var numbers = [2, 3, 5, 1, 4];
      x = Math.max.apply(null, numbers);
      y = Math.min.apply(null, numbers);
      alert([x,y]);

      // Once again, using call

      x = Math.max.call(null, 2, 3, 5, 1, 4);
      y = Math.min.call(null, 2, 3, 5, 1, 4);
      alert([x,y]);
       
    7. Closures

      function makeAdder(delta) {
          function adder(n) {
              return n + delta;
          }
          return adder;
      }
      var add1 = makeAdder(1);
      var add42 = makeAdder(42);
      alert(add1(100) + "," + add42(100));

       
  12. More Predefined Functions
     
    Function Examples / Comments
    eval(expr) Evaluate the expr in the current scope
    isFinite(number) true except for NaN, +Infinity, -Infinity
    isNaN(value) false except for NaN
    encodeURI(s)
    decodeURI(s)
    Make a string safe for including in a URI

     

  13. Arrays
    1. Creating Arrays

      var a1 = [2, 3, 4];          // preferred
      var a2 = Array(2, 3, 4);     // ok
      var a3 = new Array(2, 3, 4); // ditto

      var arrayLen = 10;
      var a4 = Array(arraylen);     // ok
      var a5 = new Array(arrayLen); // ditto
      var a6 = [ ];
      a6.length = arrayLen;         // yuck!

      var a7 = [ ];
      a7[arrayLen-1] = false;       // also pretty yucky!
      alert(a7.length);
       
    2. Array Length

      var a = [2, 3, 4];
      alert(a.length);
       
    3. Array forEach Loop

      var a = [2, 3, 5, 7];
      a.forEach(function(x) {
          alert(x);
      });
       
    4. Multidimensional Arrays

      // Javascript 2d arrays are like
      // Python 2d lists (just lists of lists...)
      var a = [[2, 3],
               [5, 7],
               [11, 13]];
      var rows = a.length;
      var cols = a[0].length;
      alert("dimensions: " + [rows,cols]);

       
  14. Predefined Object Properties and Methods
     
    1. Number Properties
       
      Property Examples / Comments
      MAX_VALUE The largest number. About 1.8e+308.
      MIN_VALUE The smallest number.  About 5e-324.
      NaN Special "not a number" value
      NEGATIVE_INFINITY Special negative infinite value; returned on overflow
      POSITIVE_INFINITY Special positive infinite value; returned on overflow

       

    2. Math Properties
       
      Property Examples / Comments
      PI About 3.14
      E About 2.718

       

    3. Math Methods
       
      Method Examples / Comments
      abs Absolute value.
      acos Inverse trig.  Arccosine in radians.
      asin Inverse trig.  Arcsine in radians.
      atan Inverse trig.  Arctangent in radians.
      atan2 Like atan, but takes a point to preserve quadrant.
      ceil smallest integer n >= arg
      cos cosine of angle in radians.
      exp exp(b) returns eb
      floor largest integer n <= arg
      log natural log (base e)
      max maximum of two args
      min minimum of two args
      pow pow(a,b) returns ab
      random random float between 0 and 1.
      round nearest integer
      sin sine of angle in radians.
      sqrt square root of arg.
      tan tangent of angle in radians.

       

    4. String Methods
       
      Method Examples / Comments
      charAt s.charAt(i) returns char at index i
      charCodeAt s.charCodeAt(i) returns ascii of char at index i
      indexOf finds index of first occurrence of substring
      lastIndexOf finds index of last occurrence of substring
      concat creates new string concatenating the two
      split split string into array based on delimiter
      slice a.slice(i,j) returns substring from index i to index j,
      where j can be negative (from the end) or omitted.
      substring (substr) similar to slice (see documentation for details)
      match, replace, search Deferred until we cover regular expressions.
      toLowerCase returns lowercase string
      toUpperCase returns uppercase string

       

    5. Array Methods
       
      Method Examples / Comments
      concat returns a copy of the joined arrays
      indexOf finds index of first occurrence of element
      join joins all the elements of the array into a string
      lastIndexOf finds index of last occurrence of element
      pop removes and returns the last element of the array
      push adds new element to end of array and returns new length
      reverse reverses the order of the array
      shift removes and returns the first element of the array
      slice returns a new array that is a copy of part of the array
      sort sorts the elements in the array
      splice adds/removes elements from the array
      unshift adds new elements to the front of the array and returns new length

     

  15. Objects
    1. Creating Objects and Accessing Properties
      1. With explicit properties (dot notation)

        function printInfo(dog) {
            document.write(dog.name + " is " + dog.age + "<br>\n");
        }

        var dog1 = new Object();
        dog1.name = "Fido";
        dog1.age = 7;
        printInfo(dog1);

         
      2. With named properties (square-bracket notation)

        var dog2 = new Object();
        dog2["name"] = "Spot";
        dog2["age"] = 5;
        printInfo(dog2);

        dog2["You can use spaces in strings?"] = 42;
        alert(dog2["You can use spaces in strings?"]); // 42

        // Be careful...!
        var obj = new Object();
        var x = "y";
        var y = 42
        obj.x = x;
        obj[x] = y;
        alert(obj["x"]);
        alert(obj["y"]);

         
      3. With object literals (ie, object initializers)

        var dog3 = { "name" : "Rover", "age" : 6 };
        printInfo(dog3);

         
      4. With a constructor (using this)

        function Dog(name, age) {
            this.name = name;
            this.age = age;
        }

        var dog4 = new Dog("Buddy", 2);
        printInfo(dog4);
         
      5. With explicit prototype assignment

        var protoDog = { "name": "Cooper", "age": 5 };
        function Dog(){}
        Dog.prototype = protoDog;
        var d = new Dog();
        printInfo(d);

         
    2. Prototype properties (shared by all instances)

      function Dog(name, age) {
          this.name = name;
          if (age != undefined) { this.age = age; }
      }

      Dog.prototype.age = 1;

      printInfo(new Dog("Oscar")); // Oscar is 1
      printInfo(new Dog("Mia")); // Mia is 1
      printInfo(new Dog("Zeus", 2)); // Zeus is 2
       
    3. Changing builtin prototypes (bad idea!)

      var obj = new Object();
      alert(obj.foo === undefined);     // true
      Object.prototype.foo = "no way!";
      alert(obj.foo);                   // "no way!"

       
    4. Using typeof, constructor, and instanceof

      function Dog(name, age) {
          this.name = name;
          this.age = age;
      }

      var d = new Dog("Cody", 13);
      alert(typeof d); // object
      alert(d.constructor); // function Dog...
      alert(d.constructor.name); // "Dog"
      alert(d instanceof Dog); // true
       
    5. The global object (window, in the browser environment)

      alert(window.x); // undefined
      var x = 42;
      alert(window.x); // 42
       
    6. Object Parameters (Passed by reference)

      function Dog(name, age) {
          this.name = name;
          this.age = age;
      }

      function changeName(dog, newName) {
          dog.name = newName;
      }

      var d = new Dog("Zoe", 12);
      alert(d.name);
      changeName(d, "Abby");
      alert(d.name);  // it changed!

       
    7. Writing Methods
      1. In the constructor

        function Dog(name, age) {
            this.name = name;
            this.age = age;
            this.sayName = function(times) {
                for (var i=0; i<times; i++)
                    document.write(this.name + "! ");
                document.write("<br>\n");
            };
        }

        var d = new Dog("Rocky", 8);
        d.sayName(4);
         
      2. After defining the constructor (using prototype)

        function Dog(name, age) {
            this.name = name;
            this.age = age;
        }

        var d = new Dog("Maggie", 9);
        d.sayName(4); // No such method! Crash!

        Dog.prototype.sayName = function(times) {
            for (var i=0; i<times; i++)
                document.write(this.name + "! ");
            document.write("<br>\n");
        };

        d.sayName(4); // works now!
         
    8. Writing (overriding) toString Method
      1. In the constructor (works, but bad idea)

        function Dog(name, age) {
            this.name = name;
            this.age = age;
            this.toString = function() {
                return "Dog<name=" + this.name + ",age=" + this.age + ">";
            };
        }
        alert(new Dog("Max", 1));
         
      2. After the constructor, in the prototype

        function Dog(name, age) {
            this.name = name;
            this.age = age;
        }
        Dog.prototype.toString = function() {
            return "Dog<name=" + this.name + ",age=" + this.age + ">";
        };
        alert(new Dog("Max", 1));
         
    9. Getters and Setters

      function Dog(name, age) {
          this.name = name;
          this.age = age;
      }

      Dog.prototype._iq = 5;

      Dog.prototype.__defineGetter__("isSmart",
          function() { return this._iq > 10; });

      Dog.prototype.__defineSetter__("iq",
          function(iq) {
              if (iq < 0) throw("Impossible!");
              this._iq = iq;
          });

      var dog = new Dog("Skippy", 2);

      alert(dog.isSmart); // false
      dog.iq = 20;
      alert(dog.isSmart); // true
      dog.iq = -3; // throws exception!

       
    10. Inheritance

      function Animal(){}

      Animal.prototype.speak = function() {
          alert("random animal sound!");
      };

      Animal.prototype.sleep = function() {
          alert("quiet, animal sleeping!");
      };

      function Dog() {
          // Call the parent constructor on "this"
          Animal.call(this);
      }

      // Set up inheritance
      Dog.prototype = new Animal();

      // correct the constructor
      Dog.prototype.constructor = Dog;

      // override the speak method
      Dog.prototype.speak = function() {
          alert("Woof! Woof!");
      }

      var a = new Animal();
      a.speak(); // "random animal sound!"
      a.sleep(); // "quiet, animal sleeping!"

      var d = new Dog();
      d.speak(); // "Woof! Woof!"
      d.sleep(); // "quiet, animal sleeping!"

      alert(a instanceof Dog); // false
      alert(d instanceof Animal); // true
      alert(d instanceof Dog); // true
      alert(d instanceof Animal); // true

       
    11. More Clever, More Efficient, More Robust Inheritance
      Not yet....
       
  16. Gotchas!
    1. Forgotten var

      function f(a) {
          var sum = 0;
          for (i=0; i<a.length; i++)
              sum += a[i];
          return sum;
      }
      i = 10;
      alert("At the start, i =" + i);
      alert("And this should be 9: " + f([2,3,4]));
      alert("But now i =" + i);

       
    2. There is no block scope

      var x = 5;
      { var x = 3; }
      alert(x); // surprised?
       
    3. Dangling else!

      var x = 15;
      if (x > 0)
          if (x < 10)
              alert(x + " is between 0 and 10");
      else
          alert(x + " is negative");

       
    4. Assignment in a conditional

      var x = 5;
      if (x = 3) alert("x is " + x);


      // or...

      var b = false;
      if (b = false) alert(b + " is false!");
      else alert(b + " is true!");
       
    5. Boolean false object

      var b = new Boolean(false);
      if (b) alert(b + " is TRUE!!!");
       
    6. Equality operator blues (Don't use ==)

      alert("true" == true) //false
      alert(1 == true) //true
      alert("1" == 1) //true
      alert("0" == 0) //true
      alert("" == 0) //true
      alert(" " == 0) //true
      alert("Something" == true) //false
      alert("Something" == false) //false

       
    7. Non-Integer Indexes

      var a = [2,3,5,7,9,11,13];
      var i = a.length / 3;
      a[i] = 42;
      alert(a);
      alert(a[i]);
       
    8. Comparing Objects

      var d1 = { "name": "fred", "age": 3 };
      var d2 = { "name": "fred", "age": 3 };
      alert(d1 == d2); // false!
       
    9. Using shared prototype object (instead of new instance)

      // In the Animal/Dog inheritance example, replace this line:
      Dog.prototype = new Animal();
      // with this line:
      Dog.prototype = Animal.prototype;

       
  17. Maybe coming soon...
    1. Intermediate OOP (eg, intermediate temporary constructor to disconnect superclass/subclass prototypes)
    2. Debugging (Firebug, etc)
    3. Date
    4. Regular Expressions
    5. Array Generic Methods on Array-Like Objects
    6. Array Comprehensions
    7. Iterators and generators
    8. Efficient Inheritance

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem