Javascript Introduction

Lecture Notes for CS 142
Spring 2012
John Ousterhout

  • Additional reading for this topic:
    • Skim over pages 1-146 of Javascript, The Definitive Guide to get a sense of the general facilities provided by the language: types, expressions, statements, object model, arrays, etc. You can read portions of this material in more detail as you work through the projects.
  • Javascript: object-oriented scripting language.
  • Basic syntax similar to Java and C:
    sum = 0;
    for (i = 1; i < 10; i++) {
        sum += i*i;
  • Javascript is a scripting language: dynamic, interpreted. Simple object system based on prototypes.
  • Variables:
    • Untyped: types associated with values, not with variables
      • Any variable can hold any value.
    • No need for declarations: variables created when assigned
    • Scope is either local (within a function) or global.
    • Default is global (careful!) use var to declare a local variable.
    • No block-level scoping within a function.
  • Basic data types:
    • Numbers (everything is floating-point, no integers)
    • Strings (variable-length); no char type.
    • Booleans
    • null
    • Undefined
  • Statements are similar to those in Java or C.
  • Arrays:
    • Ordered collections of values.
    • Indexed by integers.
    • Creation:
      x = new Array();
      y = ["a", 123, 65]
    • May be sparse.
    • Length: array.length
    • Lots of methods, such as push, pop, and sort.
  • Objects:
    • Unordered collections of name-value pairs called properties.
    • Creation:
      x = new Object()
      y = {name: "Alice", age: 23, state: "California"}
    • Referenced either like a structure or like a hash table with string keys:
      o = new Object(); = "Alice";
      o["age"] = 23;
    • Can define new properties on-the-fly.
    • Global object: all global variables are actually properties of a distinguished object called the global object. You will hear more about the global object later.
  • Functions:
    • Simple example:
      function fac(x) {
          if (x <= 1) {
              return 1;
          return x*fac(x-1);
    • Can have variable number of arguments:
      • arguments variable
      • Unspecified arguments have value undefined
    • All functions return a value (default is value of the last statement).
  • eval: interpret a string as Javascript code, execute on the fly.
  • Classes:
    • Functions are first-class values:
      plus1 = function(value) {
          return value + 1;
      plus1(24) returns 25
    • A property of an object can be a function; if so, it can be invoked using method notation:
      Object o = new Object();
      o.count = 0;
      o.increment = function(inc) {
          if (inc == undefined) {
              inc = 1;
          this.count += inc;
          return this.count;
      o.increment() returns 1
      o.increment(3) returns 4
    • Use this to refer to instance variables
    • There is no difference between a method and a function except for this:
      • In method invocation this refers to the object.
      • In function invocation this refers to the global object.
    • A function can also have properties, just like Objects:
      function plus1(value) {
          if (plus1.invocations == undefined) {
              plus1.invocations = 0;
          return value + 1;
    • A constructor is a function named after the class
      function Rectangle(width, height) {
          this.width = width;
          this.height = height;
      r = new Rectangle(26, 14);
    • How do new objects acquire methods?
    • Approach #1: add methods in the constructor:
      function Rectangle(width, height) {
          this.width = width;
          this.height = height;
          this.area = function() {
              return this.width*this.height;
    • Approach #2: Define methods on a prototype objects
      • Associate each instance with a particular prototype
      • Automatically apply methods from the prototype to the instance.
      • The prototype property on the constructor function serves this purpose:
        Rectangle.prototype.area = function() {
            return this.width*this.height;
      • When Javascript looks up a property (e.g. a method), if it can't find it on the object itself, it looks for it in the prototype property of its class (constructor function).
    • Inheritance: create prototype as instance of parent class
      Rectangle.prototype = new Shape(...);
      If desired property is not in Rectangle.prototype then Javascript will look in Shape.prototype and so on.
    • What Javascript features correspond to the following constructs in Java?
      • Class?
      • Method?
      • Instance variable?
      • Class variable?
      • Static variable?
      • Static method?
  • How to get Javascript into a Web page:
    • By including a separate file:
      <script type="text/javascript" src="code.js"></script>
    • Inline in the HTML:
      <script type="text/javascript">
      Javascript goes here...
    • Event handlers:
      <p onclick="alert('Hello world!');">
      Click here.</p>