JavaScript

JavaScript, in its more modern form, is an object-based scripting programming language based on the concept of prototypes. The language is best known for its use in websites, but is also used to enable scripting access to objects embedded in other applications. It was originally developed by Brendan Eich of Netscape Communications Corporation under the name Mocha, then LiveScript, and finally renamed to JavaScript. Some are of the opinion that JavaScript has a syntax close to that of Sun MicrosystemsJava programming language. Other than its name and syntax, the language has more in common with the Self programming language than with Java.

As of 1999, the latest revision of the standard is JavaScript 1.5, which corresponds to ECMA-262 Edition 3. ECMAScript, in simple terms, is a standardized version of JavaScript. The latest beta version of Mozilla (1.8 Beta 1) has partial support of E4X, which is a language extension dealing with XML, defined in the ECMA-357 version of ECMAScript.

Contents

Java, JavaScript, and JScript

The change of name from LiveScript to JavaScript happened at roughly the time that Netscape was including support for Java technology in its Netscape Navigator web browser. JavaScript was first introduced and deployed in the Netscape browser version 2.0B3 in December of 1995. The choice of name proved to be a source of much confusion. There is no real relation between Java and JavaScript; their similarities are mostly in syntax (that is, both derived from C); their semantics are quite different, notably their object models are unrelated and largely incompatible.

Due to the de facto success of JavaScript as a web page enhancement language, Microsoft developed a compatible language known as JScript. JScript was first supported in the Internet Explorer browser version 3.0 released in August, 1996. When web developers talk about using JavaScript in the IE browser, they silently mean JScript in the IE browser. The need for common specifications for that language was the basis of the ECMA 262 standard for ECMAScript (see external links below), three editions of which have been published since the work started in November 1996 (and which in turn set the stage for the standardization of C# a few years later). One term often related to JavaScript, the Document Object Model, is actually not part of the ECMAScript standard; it's rather a standard on its own, and based on XML.

Usage

JavaScript is a prototype-based scripting language with a syntax loosely based on C. Like C, it has the concept of reserved keywords, which (being executed from source) means it is almost impossible to extend the language without breakage.

Also like C, the language has no input or output constructs of its own. Where C relies on standard I/O libraries, a JavaScript engine relies on a host program into which it is trivially (or more complexly) embedded. There are many such host programs, of which web technologies are the most well known examples. These are examined first.

JavaScript embedded in a web browser connects through interfaces called Document Object Models (DOMs) to applications, especially to the server side (web servers) and the client side (web browsers) of web applications. Many web sites use client-side JavaScript technology to create powerful dynamic web applications. It may use unicode and can evaluate regular expressions (introduced in version 1.2 in Netscape Navigator 4 and Internet Explorer 4). JavaScript expressions contained in a string can be evaluated using the eval function.

One major use of web-based JavaScript is to write functions that are embedded in HTML pages and interact with the DOM of the browser to perform tasks not possible in static HTML alone, such as opening a new window, checking input values, changing images as the mouse cursor moves over, etc. Unfortunately, the DOMs of all browsers are not standardized. Different browsers expose different objects or methods to the script. It is therefore often necessary to write different variants of a JavaScript function for the various browsers.

Outside of the Web, JavaScript interpreters are embedded in a number of tools. Adobe Acrobat and Adobe Reader support JavaScript in PDF files. The Mozilla platform, which underlies several common web browsers, uses JavaScript to implement the user interface and transaction logic of its various products. JavaScript interpreters are also embedded in proprietary applications that lack scriptable interfaces. Microsoft's WSH technology supports JavaScript (via JScript) as an operating system scripting language. JScript .NET is a CLI-compliant language that is very similar to JScript, but has further object oriented programming features.

Each of these applications provides its own object model which provides access to the host environment, with the core JavaScript language remaining mostly the same in each application.

Core language elements

Whitespace

Spaces, tabs, newlines and comments used outside string constants are called whitespace. Unlike C, whitespace in JavaScript source can directly impact semantics. Because of a technique called "semicolon insertion", any statement that is well formed when a newline is parsed will be considered complete (as if a semicolon were inserted just prior to the newline).Programmers are advised to supply statement terminating semicolons explicitly to enhance readability and lessen unintended effects of the automatic semicolon insertion.

Unnecessary whitespace, whitespace characters that are not needed for correct syntax, can increase the amount of wasted space, and therefore the file size of .js files. Where file compression techniques that remove unnecessary whitespace are used, performance can be improved if the programmers have included these so-called 'optional' semicolons.

Comment syntax is the same as in C++. That is, either blocked comments as /* ... */ or "rest of line" comments delimited by "//" .

Variables

Variables are generally dynamically typed. Variables are defined by either just assigning them a value or by using the var statement. Variables declared outside of any function, and variables declared without the var statement, are in "global" scope, visible in the entire web page; variables declared inside a function with the var statement are local to that function. To pass variables from one page to another, a developer can set a cookie or use a hidden frame or window in the background to store them.

Objects

For convenience, Types are normally subdivided into primitives and objects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values, ("slots" in prototype-based programming terminology). That is, an object is an associative array similar to hashes in the Perl programming language, arrays in PHP, or dictionaries in Python, PostScript and Smalltalk.

JavaScript has several kinds of built in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Other objects are "host objects", defined not by the language but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links etc.).

By defining a constructor function it is possible to define objects. JavaScript is a prototype based object-based language. This means that inheritance is between objects, not between classes (JavaScript has no classes). Objects inherit properties from their prototypes.

One can add and remove properties or methods to individual objects after they have been created. To do this for all instances created by a single constructor function, one can use the prototype property of the constructor to access the prototype object. Object deletion is not mandatory as the scripting engine will garbage collect any variables that are no longer being referenced.

Example: Manipulating an object

// constructor function
function MyObject(attributeA, attributeB) {
  this.attributeA = attributeA
  this.attributeB = attributeB
}

// create an Object
obj = new MyObject('red', 1000);

// access an attribute of obj
alert(obj.attributeA);

// access an attribute with the associative array notation
alert(obj["attributeA"]);

// add an new attribute
obj.attributeC = new Date();

// remove an attribute of obj
delete obj.attributeB;

// remove the whole Object
delete obj;

JavaScript supports inheritance hierarchies through prototyping. For example:

function Base() {
  this.Override = function() {
    alert("Base::Override()");
  }

  this.BaseFunction = function() {
    alert("Base::BaseFunction()");
  }
}

function Derive()
{
   this.Override = function() {
     alert("Derive::Override()");
   }
}

Derive.prototype = new Base();

d = new Derive();
d.Override();
d.BaseFunction();
d.__proto__.Override(); // mozilla only

will result in the display:

Derive::Override()
Base::BaseFunction()
Base::Override()  // mozilla only

Object hierarchy may also be created without prototyping:

function red() {
  this.sayRed = function () {
    alert ('red wine')
  }
}

function blue() {
  this.sayBlue = function () {
    alert('blue sky')
  }

  this.someName = black // inherits black
  this.someName()       // inherits black
}

function black () {
  this.sayBlack = function () {
    alert('black night')
  }
}

function anyColour() {
  this.anotherName = red // inherits red
  this.anotherName()     // inherits red
  this.sayPink = function() {
    alert('"Any Colour You Like" is a song of Pink Floyd')
  }
  this.anotherName = blue // inherits blue ( + black )
  this.anotherName()      // inherits blue ( + black )
  this.anotherName = 'released 1973' // now it's a string - just for fun
}

var hugo = new anyColour()
hugo.sayRed()
hugo.sayBlue()
hugo.sayBlack()
hugo.sayPink()
alert(hugo.anotherName)

Data structures

A typical data structure is the Array, which is a map from integers to values. In JavaScript, all objects can map from integers to values, but Arrays are a special type of objects that has extra behavior and methods specializing in integer indices (e.g., join, slice, and push).

Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length property will remove larger indices. This length property is the only special feature of Arrays that distinguishes it from other objects.

Elements of Arrays may be accessed using normal object property access notation:

  myArray[1]
  myArray["1"]

These two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:

  myArray.1 (syntax error)
  myArray["01"] (not the same as myArray[1])

Declaration of an array can use either an Array literal or the Array constructor:

 myArray = [0,1,,,4,5]; (array with length 6 and 4 elements)
 myArray = new Array(0,1,2,3,4,5); (array with length 6 and 6 elements)
 myArray = new Array(365); (an empty array with length 365)

Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements, just like any other object. The length of the array will still be reported as 58.

Control structures

       if (theForm.mail.value == "" || /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(theForm.mail.value))
       {
               alert("++ Invalid E-mail address! Please re-enter. ++")
               return false;
       }
       if (theForm.request.value == "")
       {
                 alert("++ Please enter your request ! ++");
                 return false;
       }
       return true;

If ... else (shorthand)

  condition ? statement : statement;

While loop

  while (condition) {
     statements
  }

Do ... while

  do {
     statements
  } while (condition);

For loop

  for ([initial-expression]; [condition]; [increment-expression]) {
     statements
  }

For ... in loop

This loop goes through all properties of an object (or elements of an array).

  for (variable in object) {
     statements
  }

Switch statement

  switch (expression) {
     case label1 :
        statements;
        break;
     case label2 :
        statements;
        break;
     default :
        statements;
  }

Functions

A function is a block with a (possibly empty) argument list that is normally given a name. A function may give back a return value.

  function function-name(arg1, arg2, arg3) {
     statements;
     return expression;
  }

Example: Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the shorter segment from the longer):

  function gcd(segmentA, segmentB)
  {
     while(segmentA!=segmentB)
        if(segmentA>segmentB)
           segmentA -= segmentB;
        else
           segmentB -= segmentA;
     return(segmentA);
  }

The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined. Within the function the arguments may also be accessed through the arguments array; this provides access to any actual arguments beyond the number of named arguments.

Every function is an instance of Function, a type of base object. Functions can be created and assigned like any other objects, and passed as arguments to other functions. Thus JavaScript supports higher-order functions. For example:

   Array.prototype.fold =
   function (value, functor) {
       var result = value;
       for (var i = 0; i < this.length; i++) {
           result = functor(result, this[i]);
       }
       return result;
   }
   var sum = [1,2,3,4,5,6,7,8,9,10].fold(0, function (a, b) { return a + b })

results in the value:

   55

The function keyword is overloaded as both class and method, as illustrated here:

   function Point( x, y )
   {
       this.x = x;
       this.y = y;
   }
   
   Point.prototype.alert = function()
   {
       window.alert( "(" + this.x + "," + this.y + ")" );
   }
   
   var pt = new Point( 1, 0 );
   pt.alert();

Methods can also be added within the constructor:

   function Point( x, y )
   {
       this.x = x;
       this.y = y;
       this.alert = function()
       {
           window.alert( "(" + this.x + "," + this.y + ")" );
       }
   }
   
   var pt = new Point( 1, 0 );
   pt.alert();

In fact, there is no need to create a class first, as members can be added directly to a variable:

   var pt = {
       x: 1,
       y: 0,
       alert: function()
       {
           window.alert( "(" + this.x + "," + this.y + ")" );
       }
   }
   pt.alert();

By default, all members of an object are public. There are no private or protected members (though these can be emulated). For detailed control of member access, getters and setters can be used (e.g. to create a read only property or a property that the value is generated):

   function Point( x, y )
   {
       this.x = x;
       this.y = y;
   }
   
   Point.prototype.__defineGetter__(
       "dimensions",
       function() { return [this.x, this.y]; }
   );
   
   Point.prototype.__defineSetter__(
       "dimensions",
       function( dimensions ) { this.x = dimensions[0]; this.y = dimensions[1]; }
   );
   
   var pt = new Point( 1, 0 );
   window.alert( pt.dimensions.length );
   pt.dimensions = [2,3];

The functions '__defineSetter__' and '__defineGetter__' are implementation-specific and not part of the ECMAScript standard.

Error handling

Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch error handling statement.

The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:

  try {
     // Statements in which exceptions might be thrown
  } catch(error) {
     // Statements that execute in the event of an exception
  } finally {
     // Statements that execute afterward either way
  }

Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. Once the catch block finishes, or the try block finishes with no exceptions thrown, then the statements in the finally block execute. This is generally used to free memory that may be lost if a fatal error occurs--though this is less of a concern in JavaScript. This figure summarizes the operation of a try...catch...finally statement:

  try
  {
     // Create an array
     arr = new Array();
     // Call a function that may not succeed
     func(arr);
  }
  catch (...)
  {
     // Recover from error
     logError();
  }
  finally
  {
     // Even if a fatal error occurred, we can still free our array
     delete arr;
  } 

The finally part may be omitted:

  try {
     statements
  }
  catch (err) {
     // handle error
  }

Error Scope

Scripting languages are especially susceptible to bugs, and since JavaScript has varying implementations it is common to spend a great deal of time debugging. Each script block is parsed separately. On pages where JavaScript in script blocks is mixed with HTML, syntax errors can be identified more readily by keeping discrete functions in separate script blocks, or (for preference), using many small linked .js files. This way, a syntax error will not cause parsing/compiling to fail for the whole page, and can enable a dignified die.

Offspring

The programming language used in Macromedia Flash (called ActionScript) bears a strong resemblance to JavaScript due to their shared relationship with ECMAScript. ActionScript has nearly the same syntax as JavaScript, but the object model is dramatically different.

JavaScript OSA (JavaScript for OSA, or JSOSA), is a Macintosh scripting language based on the Mozilla 1.5 JavaScript implementation, SpiderMonkey. It is a freeware component made available by Late Night Software. Interaction with the operating system and with third-party applications is scripted via a MacOS object. Otherwise, the language is virtually identical to the core Mozilla implementation. It was offered as an alternative to the more commonly used AppleScript language.

See also

References

  • Nigel McFarlane: Rapid Application Development with Mozilla, Prentice Hall Professional Technical References, ISBN 0131423436
  • David Flanagan, Paula Ferguson: JavaScript: The Definitive Guide, O'Reilly & Associates, ISBN 0596000480
  • Danny Goodman, Scott Markel: JavaScript and DHTML Cookbook, O'Reilly & Associates, ISBN 0596004672
  • Danny Goodman, Brendan Eich: JavaScript Bible, Wiley, John & Sons, ISBN 0764533428
  • Andrew H. Watt, Jinjer L. Simon, Jonathan Watt: Teach Yourself JavaScript in 21 Days, Pearson Education, ISBN 0672322978
  • Thomas A. Powell, Fritz Schneider: JavaScript: The Complete Reference, McGraw-Hill Companies, ISBN 0072191279
  • Scott Duffy: How to do Everything with JavaScript, Osborne, ISBN 0072228873
  • Andy Harris, Andrew Harris: JavaScript Programming, Premier Press, ISBN 0761534105
  • Joe Burns, Andree S. Growney, Andree Growney: JavaScript Goodies, Pearson Education, ISBN 0789726122
  • Gary B. Shelly, Thomas J. Cashman, William J. Dorin, Jeffrey Quasney: JavaScript: Complete Concepts and Techniques, Course Technology, ISBN 0789562332
  • Nick Heinle, Richard Koman: Designing with JavaScript, O'Reilly & Associates, ISBN 1565923006
  • Sham Bhangal, Tomasz Jankowski: Foundation Web Design: Essential HTML, JavaScript, CSS, PhotoShop, Fireworks, and Flash, APress L. P., ISBN 1590591526

Specifications

History

Template:Major programming languages smallcs:JavaScript de:JavaScript es:JavaScript fr:JavaScript hi:जावास्क्रिप्ट ia:JavaScript is:JavaScript it:JavaScript he:JavaScript lv:JavaScript hu:JavaScript nl:Javascript ja:JavaScript pl:JavaScript pt:JavaScript ru:JavaScript sk:JavaScript sl:JavaScript sv:JavaScript th:ภาษาจาวาสคริปต์ tr:JavaScript uk:Джава сценарій zh:JavaScript

Navigation

  • Art and Cultures
    • Art (https://academickids.com/encyclopedia/index.php/Art)
    • Architecture (https://academickids.com/encyclopedia/index.php/Architecture)
    • Cultures (https://www.academickids.com/encyclopedia/index.php/Cultures)
    • Music (https://www.academickids.com/encyclopedia/index.php/Music)
    • Musical Instruments (http://academickids.com/encyclopedia/index.php/List_of_musical_instruments)
  • Biographies (http://www.academickids.com/encyclopedia/index.php/Biographies)
  • Clipart (http://www.academickids.com/encyclopedia/index.php/Clipart)
  • Geography (http://www.academickids.com/encyclopedia/index.php/Geography)
    • Countries of the World (http://www.academickids.com/encyclopedia/index.php/Countries)
    • Maps (http://www.academickids.com/encyclopedia/index.php/Maps)
    • Flags (http://www.academickids.com/encyclopedia/index.php/Flags)
    • Continents (http://www.academickids.com/encyclopedia/index.php/Continents)
  • History (http://www.academickids.com/encyclopedia/index.php/History)
    • Ancient Civilizations (http://www.academickids.com/encyclopedia/index.php/Ancient_Civilizations)
    • Industrial Revolution (http://www.academickids.com/encyclopedia/index.php/Industrial_Revolution)
    • Middle Ages (http://www.academickids.com/encyclopedia/index.php/Middle_Ages)
    • Prehistory (http://www.academickids.com/encyclopedia/index.php/Prehistory)
    • Renaissance (http://www.academickids.com/encyclopedia/index.php/Renaissance)
    • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
    • United States (http://www.academickids.com/encyclopedia/index.php/United_States)
    • Wars (http://www.academickids.com/encyclopedia/index.php/Wars)
    • World History (http://www.academickids.com/encyclopedia/index.php/History_of_the_world)
  • Human Body (http://www.academickids.com/encyclopedia/index.php/Human_Body)
  • Mathematics (http://www.academickids.com/encyclopedia/index.php/Mathematics)
  • Reference (http://www.academickids.com/encyclopedia/index.php/Reference)
  • Science (http://www.academickids.com/encyclopedia/index.php/Science)
    • Animals (http://www.academickids.com/encyclopedia/index.php/Animals)
    • Aviation (http://www.academickids.com/encyclopedia/index.php/Aviation)
    • Dinosaurs (http://www.academickids.com/encyclopedia/index.php/Dinosaurs)
    • Earth (http://www.academickids.com/encyclopedia/index.php/Earth)
    • Inventions (http://www.academickids.com/encyclopedia/index.php/Inventions)
    • Physical Science (http://www.academickids.com/encyclopedia/index.php/Physical_Science)
    • Plants (http://www.academickids.com/encyclopedia/index.php/Plants)
    • Scientists (http://www.academickids.com/encyclopedia/index.php/Scientists)
  • Social Studies (http://www.academickids.com/encyclopedia/index.php/Social_Studies)
    • Anthropology (http://www.academickids.com/encyclopedia/index.php/Anthropology)
    • Economics (http://www.academickids.com/encyclopedia/index.php/Economics)
    • Government (http://www.academickids.com/encyclopedia/index.php/Government)
    • Religion (http://www.academickids.com/encyclopedia/index.php/Religion)
    • Holidays (http://www.academickids.com/encyclopedia/index.php/Holidays)
  • Space and Astronomy
    • Solar System (http://www.academickids.com/encyclopedia/index.php/Solar_System)
    • Planets (http://www.academickids.com/encyclopedia/index.php/Planets)
  • Sports (http://www.academickids.com/encyclopedia/index.php/Sports)
  • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
  • Weather (http://www.academickids.com/encyclopedia/index.php/Weather)
  • US States (http://www.academickids.com/encyclopedia/index.php/US_States)

Information

  • Home Page (http://academickids.com/encyclopedia/index.php)
  • Contact Us (http://www.academickids.com/encyclopedia/index.php/Contactus)

  • Clip Art (http://classroomclipart.com)
Toolbox
Personal tools