Section 2.1. The JavaScript Language


2.1. The JavaScript Language

The JavaScript language is loosely based on C, so programmers coming from a C/C++, C#, or Java background can usually learn the syntax in a short amount of time. There are some aspects of JavaScript that make it quite accessible. It is not strongly typed, for examplethe programmer doesn't assign data types; instead, JavaScript assigns data types at runtime. In addition, JavaScript supports object-oriented programming to some extent, but does not rely on it, unlike languages such as C# or Java.

JavaScript can be embedded in web pages in three ways: in scripts, in event handlers, and in URLs. The syntax used in each case is different.


Embedding a script in a web page

Scripts are typically embedded in an HTML page using the HTML <script> element. You can also use the src attribute of the <script> element to point to the URL of an external script file to load.

The major browsersincluding Internet Explorer, Firefox, and Safari/Konquerorall assume that JavaScript is the default language whenever they encounter a <script> tag on a web page. However, to satisfy W3C standards and the needs of less-used or older browsers (including outdated versions), it's always best to specify the language using the following syntax:

 <script language="JavaScript" type="text/javascript">   ... </script> 


Using a script to handle an event

JavaScript code can be used as the value of an event handler attribute of an HTML tag, e.g., <input type="button" onclick="doSomething( );" />.


Using JavaScript in a URL

JavaScript can appear in a URL that uses the special javascript: pseudoprotocol, making it, for instance, easy to use JavaScript in hyperlinks.

The first two options are the most commonly used and are illustrated in the following sections, while introducing you to the key elements of the Java-Script language.

When Browsers Don't Support JavaScript

Years ago, the <script> element was used in the following fashion:

 <script language="JavaScript" type="text/javascript"><!--   ... //--></script> 

The HTML comment (<!-- and -->) was used to force browsers with no Java- Script capabilities at all to ignore the JavaScript code. (The two slashes before the end of the HTML comment (//-->) denote a JavaScript comment, which caused JavaScript to ignore the closing HTML comment tag.)

However, this is all history. Even browsers that do not support JavaScript now know to ignore <script> elements.


2.1.1. Common JavaScript Methods

JavaScript provides two methods that we will use repeatedly in the short examples presented in this chapter. They are:


document.write("Text")

Writes the given text to the browser window


window.alert("Text")

Opens up a modal window to display an informational message

Example 2-1 shows markup for a page that uses the second method to display an alert.

Example 2-1. Using JavaScript

 JavaScript.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   window.alert("Hello from JavaScript!");   </script> </head> <body> </body> </html> 

Figure 2-1 shows the result you can expect when Example 2-1 executes. In Internet Explorer 6 SP 2 onward, you might get a security warning for running active content in the browser from the local filesystem. This message will not appear if the script resides on a web server.

Figure 2-1. The modal window created by JavaScript


2.1.2. Variables

JavaScript variables are defined using the var keyword. They do not require a prefix to specify their type (as Perl or PHP variables do). By default, variables are global unless they are defined in a function. Variables do not have a fixed data type, but can change their type at runtime. However, JavaScript provides a few built-in data types that you're likely to use repeatedly. Here are four of them:

  • Number (1, -2, 3.14159)

  • String ("Hello", 'World')

  • Boolean (true, false)

  • RegEx (/d+/)

There are other data type objects as well. For instance, Date is used for date values; however, this is not an actual data type, but a class that can be used to access the current date and perform calculations with it.


You assign a value to a variable using the = operator. Here are some examples:

 var i = 0; //Create variable, set its value to 0 i = "JavaScript"; //Set variable value to a string i = false; //Set variable value to a Boolean 

Unlike other languages such as PHP or Perl, there is no functional difference between single and double quotes in Java-Script. Also, note that the terminal (;) is optional, but recommended to avoid side effects.


Depending on their current type, JavaScript variables support the class methods associated with that type. For instance, every string you create supports the substring() method, which can locate parts of the string, and the indexOf() method, which can find the occurrence of a substring in the current string.

An array is a variable containing a list of values. But because JavaScript is not strongly typed, an array can contain different data types. There are two ways to create an array. One is to use new Array() and provide some values. Array indexes are zero-based, so the following code snippet adds a seventh element to a list:

 var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"); days[6] = "Saturday"; 

Alternatively, today's browsers also let you create an array using the following shortcut:

 var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; 

2.1.3. Control Structures

JavaScript supports the standard set of control structures, including switch, if...else, and various loops (for, for...in, foreach, while, do...loop, and do...until). Let's begin with the if statement. Example 2-2 generates a random number (something that we'll use again later on in this book) using Math.random(), which is a built-in function you can use to create a new random number between 0 (inclusive) and 1 (exclusive). Multiplying the 26alue by 6 leads to a random number between 0 (inclusive) and 6 (exclusive). By rounding the number up using the Math.ceil() method, the roll of a die is simulated, generating a value between 1 and 6 (both inclusive).

Example 2-2. Using if...else and Math.random

 JavaScript-if.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   var rand = Math.random();   rand = Math.ceil(6 * rand);   if (rand % 2 == 1) {     document.write("Odd number: ");   } else {     document.write("Even number: ");   }   document.write(rand);   </script> </head> <body> </body> </html> 

Figure 2-2 shows the results of running the script.

Figure 2-2. Rolling a (virtual) die with JavaScript


Example 2-2 makes use of some additional JavaScript elements, including:


Boolean operators

! (exclamation point) the logical negation operator in JavaScript; || is the logical or operator; && is the logical and operator.


Comparison operators

== checks for equality (wheras = is the assignment operator); other comparison operators include >=, >, <, <=, and !=.

JavaScript supports a tertiary operator that is a very convenient shortcut for performing an if...else operation. This expression:

 var output = (rand % 2 == 1) ? "odd" : "even"; is equivalent to: if (rand % 2 == 1) {   var output = "odd"; } else {   var output = "even"; } 


Rather than using a series of if statements to check the same expression over and over, you can use the switch statement. Have a look at Example 2-3 to see how it works.

Example 2-3. Using switch

 JavaScript-switch.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   var rand = Math.random();   rand = Math.ceil(6 * rand);     switch (rand) {       case 1:       case 3:       case 5:       document.write("Odd number: ");       break;     default:       document.write("Even number: ");   }   document.write(rand);   </script> </head> <body> </body> </html> 

As you can see, only a break statement exits the switch statement. Without the break statement, after the switch expression matches one of the case values, the JavaScript interpreter runs through the remaining statements.

Loops are quite convenient for repeating code a fixed number of times. The for loop can be used for iterating through arrays, for instance. Each array 28as a property (length) that retrieves the number of elements in the array. The for loop in Example 2-4 displays all data in an array.

Example 2-4. Using a for loop

 JavaScript-for.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];   for (var i=0; i < days.length; i++) {     document.write(days[i] + "<br />");   }   </script> </head> <body> </body> </html> 

Figure 2-3 shows the result of running the script in Example 2-4.

Figure 2-3. The for loop iterates through the array elements


Example 2-4 uses some additional language features: the expression i++ used to iterate the for loop is a short form for i = i + 1 (i-- is a related expression), and the + operator can be used not only to add numbers but to concatenate strings as well.

JavaScript also provides a for...in loop, which works like a foreach statement in C# and related languages. Example 2-5 demonstrates its use. At 29ach iteration, the loop variable reads the current element. If you use a foreach statement to retrieve objects, you receive all object properties and methods. For arrays, you receive the individual array indexes. Therefore, with the days array from the preceding example, the values during an iteration over the array are 0 to 6, not "Sunday" through "Saturday".

Example 2-5. Using a for...in loop

 JavaScript-for-in.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];   for (var day in days) {     document.write(days[day] + "<br />");   }   </script> </head> <body> </body> </html> 

JavaScript provides several other loop statements, but they each perform similar operations: they run either while a particular condition exists or until a condition is met. The most commonly used of these loops is the while loop. Example 2-6 shows the statement in use.

Example 2-6. Using a while loop

 JavaScript-while.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];   var i = 0;   while (i < days.length) {     document.write(days[i] + "<br />");     i++;   }   </script> </head> <body> </body> </html> 

2.1.4. Built-in Methods, Custom Functions, and Event Handling

JavaScript comes with a set of built-in objects, but you can create custom functions (and objects), as well. A function is identified with the function keyword. Because you cannot specify a data type for the return value (and as a consequence, there is no void keyword), a function does not necessarily have to return a value. If you do wish to return a value, however, use the return statement.

Example 2-7 demonstrates the replace() method available for all strings, which provides regular expression support. As you can see, the script makes several calls to replace(), one after the other. First, the & character is replaced by its associated HTML entity, &amp;. Then, other special HTML characters (<, >, ", and ') are escaped in a similar fashion. In the end, any string handled by the script will be transformed into its associated HTML markup, just as the ASP.NET method Server.HtmlEncode() would do.

Example 2-7. Writing a custom function

 JavaScript-function.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title> </head> <body>   <script language="JavaScript" type="text/javascript">   function HtmlEscape(s) {     var result = s.replace(/&/g, "&amp;")                   .replace(/</g, "&lt;")                   .replace(/>/g, "&gt;")                   .replace(/"/g, "&quot;")                   .replace(/'/g, "&apos;");     return result;   }   document.write(HtmlEscape("<hr />"));   </script> </body> </html> 

When it executes, Example 2-7 outputs &lt;hr /&gt;, which is displayed as <hr /> in the browser, but does not create a horizontal rule.

JavaScript does not support function overloading; however, the number of arguments in a function is not fixed. If more arguments are provided in the function signature than are submitted by the caller, the extra arguments are assigned the value null.

On the other hand, if more arguments are submitted than expected, the arguments property (short for <Functionname>.arguments) provides access to all of them, as demonstrated in Example 2-8.

Example 2-8. Writing a custom function with a variable number of arguments

 JavaScript-function-arguments.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title> </head> <body>   <script language="JavaScript" type="text/javascript">   function OutputList() {     document.write("<ul>");     for (var i=0; i < arguments.length; i++) {       document.write("<li>" +                      arguments[i] +                      "</li>");     }     document.write("</ul>");   }   OutputList("one", "two", "three");   </script> </body> </html> 

Figure 2-4 shows the output that results when Example 2-8 executes.

Figure 2-4. The custom function generates the bulleted list


JavaScript also supports so-called anonymous functions, which are functions with no name. Anonymous functions are sometimes used in Java-Script to handle events. For instance, the onload attribute of the <body> tag can be assigned JavaScript code that is executed once the HTML of the page has been completely loaded (this is, by the way, possible for all events tied to HTML markup). This is JavaScript's built-in event handling.

There are several events (for instance, load), and by concatenating on and the event name you can provide code to be executed when the event occurs. There are other ways to bind code to events, but anonymous methods and HTML attributes are the two most popular choices.

Here's a snippet that displays a window with the word "Loaded" when a page is loaded:

 <body onload="alert('Loaded.');"> 

Or, more generically stated, here's the syntax:

 <body onload="Functionname();"> 

You can also bind an event to a handler in code. The base object of a page is called window, so you can set window.onload to a function, as in the following example:

 function Functionname() {   // do stuff } window.onload = Functionname: 

If you do not need to use the function for any other reason, you can assign an anonymous function to the event name directly. The preceding example can be shortened in the following fashion:

 window.onload = function() {   // do stuff } 

The following is an example of an anonymous function that includes parameters:

 window.onload = function(a, b) {   // do stuff with a and b } 

This approach is quite convenient and, as you will see, and is used frequently by the Atlas framework.




Programming Atlas
Programming Atlas
ISBN: 0596526725
EAN: 2147483647
Year: 2006
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net