Javascript Introduction

Lecture Notes for CS 142
Fall 2010
John Ousterhout

  • Readings 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 objects:
      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;
    • Constructor: 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: prototypes
      • Define methods on a "prototype" object.
      • 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).
    • Summary of how object-oriented constructs are implemented in Javascript:
      • Class: a constructor function; there is no other notion of class.
      • Method: a function property on the prototype property of the constructor.
      • Instance variable: a property on an object; must be created explicitly for each object (e.g., by constructor).
      • Class variable: a property on the constructor function.
      • Static variable: a property on the function.
      • Static method: a function property on the constructor function.
    • This object system is very simple, yet very flexible:
      • Can add new properties and methods at any time.
      • "Duck typing": if it looks like a duck and walks like a duck....
  • 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>