Mark Volkmann's JavaScript Page

Topics

Firebug JSON "The Good Parts" XML classes closures conditional processing constructors Engines exceptions from HTML functions Influences in HTML iteration module pattern names prototypal inheritance regular expressions semicolons truthy/falsy values type cohersion

Keywords

Infinity NaN break case catch default delete do else eval false for function if in new nil return switch ternary (?:) throw true try typeof undefined var while with

Operators

&& || == === != !==

Types

Array (an Object) Boolean Date (an Object) Math Number Object RegExp (an Object) String

Major Characteristics

Quotes

"JavaScript is not a bug that needs fixing." - Alex Russell
"JavaScript is the world's most misunderstood programming language." - Douglas Crockford
"It's the only language that I'm aware of that people feel they don't need to learn before they start using it." - Douglas Crockford
"It amazes me the lengths that people will go to to avoid having to learn JavaScript. But it's learnable and you can actually write good programs in it." - Douglas Crockford
"It's basically Scheme with C syntax." - Douglas Crockford

Books

Libraries

References

Tools

Origin

LiveScript was invented by Brendan Eich at Netscape in 1995. The name was changed to JavaScript by agreement between Netscape and Sun Microsystems to help them compete against Microsoft. In 1996 Microsoft created an implementation of JavaScript named JScript (to avoid trademark issues) and embedded it in Internet Explorer. In order to avoid fragmentation of the language, Netscape asked the European Computer Manufacturers Association (ECMA) to create a specification for it. The "ECMAScript Language Specification" specifies the syntax and rules of the language.

Influences

Language Features
Self prototypal inheritance, dynamic objects
Scheme functional, lambda (closures?), loose typing
Java syntax, conventions
Perl regular expressions

Bad Parts

Good Parts

Prototypal Inheritance

Prototypal inheritance is specified using objects instead of classes. An object can inherit directly from one other object (called its "prototype"), which itself can inherit from one other object to form a hierarchy. When an attempt is made to access a non-existent property in an object, it delegates to its prototype.

To create a new object that inherits from an existing one:

      // Old way
      function ClassName() {} // constructor
      ClassName.prototype = oldObj;
      var newObj = new ClassName(); // new operator required to call constructors

      // New way (in ECMAScript 5?)
      var newObj = Object.create(oldObj);

      // Can define Object.create for older JavaScripts.
      if (typeof Object.create !== 'function') {
        Object.create = function (oldObj) {
          function F() {} // constructor
          F.prototype = oldObj;
          return new F();
        };
      }
      

Closures

Closures are blocks of code that have access to variables that are in their scope at the time they are defined. For example:

      var publicFunction = function() {
        var privateVariable = some-value;

        function privateFunction(params) {
          // Can access privateVariable here.
        }

        return function (params) {
          // Can access privateVariable and call privateFunction here.
        }
      }();

      // Can call publicFunction here, but not privateFunction
      // and privateVariable isn't accessible.
    

Instead of returning a single function, an object literal containing several functions can be returned. This is similar to a singleton object since only one is ever created from this definition. For example, the return statement above could be replaced with:

        return {
          methodName1: function (params) {
            // Can access privateVariable and call privateFunction here.
          },
          methodName2: function (params) {
            // Can access privateVariable and call privateFunction here.
          }
        };
    

Object Creation

There are four ways to create a JavaScript object.

  1. object literal - { name: value, ... }
  2. new operator on a constructor function
  3. Object.create (new way to create an object from another)
  4. "power constructor"

Here's a template for writing power constructors:

      function myConstructor(params) {
        var privateAttr = some-value;
        var privateFunc = function (params) { ... }
        // Note that "this" is a reserved word.
        var that = {}; // or some other way to create an object
        that.publicAttr = some-value;
        that.methodName = function () {
          // can access private attributes and call private functions here
        };
        // Define more methods here.
        return that;
      }
    

Brace Placement

K&R brace placement (open brace at end of line of code instead of on a new line) must be used because otherwise semicolon insertion will add a semicolon to the end of the line before the open brace and the code in the braces will be ignored.

Engines

Name Vendor Notes
JavaScriptCore Apple used in WebKit applications including current versions of Safari
JScript Microsoft used in Internet Explorer
Rhino Mozilla implemented in Java
SpiderMonkey Mozilla used in Gecko applications including Firefox
SquirrelFish (a.k.a. Nitro) Apple replacement for JavaScriptCore in WebKit applications including future versions of Safari
Taramin Adobe supports ActionScript and ECMAScript
TraceMonkey Mozilla next version of SpiderMonkey
V8 Google used in Chrome

Rhino

Rhino is a JavaScript interpreter written in Java. Here are the steps to obtain and install Rhino.

  1. Download from a zip distribution from http://www.mozilla.org/rhino/.
  2. Unzip the zip file.
  3. Set the RHINO_HOME environment variable to the path of the directory created by unzipping Rhino.
  4. Open a terminal window.
  5. Enter "cd $RHINO_HOME".
  6. Enter "ant" (assumes Ant is installed).
  7. Create the following alias: alias rhino='java -jar $RHINO_HOME/js.jar'

To run Rhino in interactive mode, enter "rhino" in a terminal window. To run Rhino on a source file, enter "rhino {file-path}" in a terminal window.

Browser Support

For a summary of JavaScript versions, the features added in them, and their support in specific browser versions, see the Wikipedia page for JavaScript. As of 12/2009, only Firefox supports JavaScript 1.8 and later.

Firebug

This tool supports editing, debugging and monitoring of HTML, CSS and JavaScript from within Firefox. To install it, run Firefox, browse http://getfirebug.com/, and press the "INSTALL FIREBUG" button.

To open Firebug, select Tools...Firebug...Open Firebug.

To enable JavaScript debugging, click the down triangle on the Script tab and select "Enabled".

To stop on all JavaScript errors, click the down triangle on the Script tab and select "Break on All Errors".

To write messages to the console, see http://getfirebug.com/console.html.

Classes

Classes are defined by a constructor function that begins with an uppercase letter. Objects are created by invoking the new operator on a constructor function. Instance methods are defined by assigning them to a property of the constructor prototype. Instance attributes are defined by assigning them to an object. Class attributes and methods are defined by assigning them to a constructor.

Here's an example of a class for circles.

Properties

Attributes and methods of objects are stored as "properties". To set the value of an object property, obj['pname'] = value; To get the value of an object property, value = obj['pname']; If the object doesn't have the property, undefined is returned. To iterate through the properties of an object, use for...in. This iterates through both direct and inherited properties, so filtering must be done when the inherited properties aren't desired. How?

NaN

NaN stands for "Not a Number". It is the result of undefined or erroneous numeric operations, for example, dividing by zero. If any input to a numeric operation is NaN, the result will be NaN. NaN is not considered equal to itself. Applying the typeof operator to NaN returns "number".

Numeric Types

There is only one numeric type in JavaScript. It is double-precision floating point. This can be an issue for financial applications due to approximations for decimal values.

To convert a value to a number, use Number(value). or +value. If the value cannot be converted to a number then NaN will be returned. To convert a value to an integer number, use parseInt(value, radix). For example, parseInt("19 miles", 10) returns 19. It parses all characters until it reaches a non-digit character.

Math

The Math class defines many constants and class methods. The constants include E (base of natural logs), LN10 (natural log of 10), LN2 (natural log of 2), LOG10E (log base 10 of e), LOG2E (log base 2 of e), PI, SQRT1_2 (square root of 1/2) and SQRT2 (square root of 2). The class methods include abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt and tan.

Conditional Processing

See if/else and switch/case/default.

if/else

if (expression) {
  // then code
} else { // optional
  // else code
}

switch/case/default

switch (expression) {
  case expression:
    statements
    break;
  // more cases
  default: // optional
    statements
}

Unless a break statement appears at the end of a case block, execution flows into the code of the next case block.

JSON

JSON stands for JavaScript Object Notation. It is a lightweight data interchange format that is based on the syntax of JavaScript object literals. It is often used as an alternative to XML. It was specified by Douglas Crockford as RFC 4627 in July 2006.

JSON supports six types of values: boolean, number, string, array, object and null. Boolean values are "true" and "false". Strings appear inside double-quotes. Arrays are sequences of values inside square brackets, separated by commas. Objects are key-value pairs inside curly braces where keys are separated from values with colons and pairs are separated by commas. Keys must be strings surrounded by double-quotes. This is mainly to avoid conflicts with JavaScript keywords which cannot be used as keys in object literals (but this is allowed in ECMAScript 5th Edition).

When sending JSON data using HTTP, the MIME type should be "application/json".

JSON is valid JavaScript syntax. JSON text can be parsed into a JavaScript object using var obj = eval('(' + jsonText + ')');. This can be dangerous because the text could contain malicious code. Using a JSON parser is recommended. One can be found at http://www.json.org/json2.js. Many newer web browsers have added native JSON parsers which are faster.

ECMAScript 5th Edition

Features in the next version of JavaScript, described by the ECMAScript 5 standard include:

Strict mode is enabled (opt-in) by adding use strict; in a script or individual function. In strict mode the following restrictions are enforced:

There are many library extensions. Is a new JSON parser one of them? What are others?

Describe object hardening here. Can make individual properties or all properties read-only. Can prevent properties from being added or deleted (freeze).

Firefox implements ECMAScript 5th Edition features in version 4, but no other popular browsers do yet.

Copyright © 2010 Object Computing, Inc. All rights reserved.