Composite Types


In contrast to primitive types like numbers and strings , composite types are made up of heterogeneous data as one unit. A composite type can contain not only strings, numbers, Booleans, undefined values, and null values, but even other composite types. JavaScript supports three composite types: objects, arrays, and functions. In Chapters 6 and 7 you will find that arrays and functions are really just special kinds of objects, but we ll ignore the subtleties of JavaScript s object-oriented aspects and just cover the basics for now.

Arrays

An array is an ordered set of values grouped together under a single identifier. There are many ways to create arrays, but the simplest is to define it like a standard identifier and then just group the values within brackets. The following statement defines an array called myArray with four numeric values:

 var myArray = [1,5,68,3]; 

Arrays can contain arbitrary data items, so a definition like

 var myArray = ["Thomas", true, 3, -47.6, "x"]; 

is also valid.

Another way syntactically to define arrays that acknowledges their heritage as objects is to use the keyword new to invoke the Array object s constructor, as shown here:

 var myArray = new Array(); 

This defines myArray as an array with no particular length.

We could easily predetermine the length of the array by passing it a single numeric value. For example,

 var myArray = new Array(4); 

defines an array of length 4.

We can even populate the array using the explicit constructor style syntax, as shown here:

 var myArray = new Array(1,5,"Thomas", true); 

Regardless of how they are defined, the elements of an array are accessed in the same way. To reference a particular piece of the array, we must provide an index value within brackets, so given

 var myArray = new Array(1,5,"Thomas", true); var x = myArray[2]; var y = myArray[0]; 

the value of x would be the string "Thomas", and y would be set to the number 1. The reason for this is that arrays in JavaScript are indexed starting from 0. The following script shows both the definition of an array and assignments using index values.

 var myArray = new Array(4); myArray[0] = 1; myArray[1] = 5; myArray[2] = "Thomas"; myArray[3] = true; 

As briefly mentioned, arrays are actually objects and have a variety of properties and methods that can be used to manipulate them. These features will be discussed at length in Chapter 7. However, let s first take at least a brief look at objects in JavaScript.

Objects

Objects can hold any type of data and are the primary mechanism by which useful tasks are carried out. The browser provides a large number of objects for you to use. For example, you can interact with the user through the Window object or modify the contents of a Web page with the Document object.

Data contained in an object are said to be properties of the object. Properties are accessed with the dot operator, which is simply a period followed by the property name . The syntax is

objectname.propertyname

For example, you would access the lastModified property of the Document object as document.lastModified .

Functions contained in an object are said to be methods of the object. Methods are also accessed with the dot operator:

objectname.methodname()

In fact, we have already used methods in our previous examples. The write() method of the Document object was used to output text to the screen:

 document.write("Hello JavaScript world!"); 

You ll notice that when using objects, the length of the identifier required to access a particular property can get quite long. For example, writing document.write might become tiresome, as would accessing even more deeply nested sub-objects. By using the keyword with , we can avoid referencing the full path to an object s property or method:

 with (document) {    write("this is easier ");    write("than writing out ");    write("the whole path");  } 

Besides using built-in objects such as Document or Window , you can create your own objects using the keyword new . The use of new was briefly demonstrated with the array examples in the previous section. You can also destroy a property or element in an array using the keyword delete . For example, here we define an array element and then quickly destroy it.

 var myArray = new Array(4); myArray[0]="Thomas"; delete myArray[0]; 

At its heart, JavaScript is an object-based language, and everything is derived from the various objects provided by the language or the browser. For example, JavaScript provides objects corresponding to the primitive data types, such as String , Number , and Boolean , which have methods to operate upon the respective kinds of data. More complex data- related objects, such as Array , Math , and Date , are also provided, as are browser-oriented objects such as Navigator and History and the powerful Document object. There is even a generic Object that we can use to build our own objects. Details about the process of creating and using objects require significant explanation that can be found in Chapter 6.

Note  

The instances of objects are typically written all lowercase, while the corresponding object type is written with an initial capital. Do not worry about this distinction for the time being ”it is discussed in depth in Chapters 6 and 7.

Expressions

Expressions are an important part of JavaScript and are the building blocks of many JavaScript statements. Expressions are groups of tokens that can be evaluated; for example,

 var x = 3 + 3; 

is an assignment statement that takes the expression 3 + 3 and puts its value in the variable x . Literals and variables are the simplest kinds of expressions and can be used with operators to create more complex expressions.

Operators

Basic operators include familiar arithmetic symbols: = (assignment), + (addition), (subtraction or unary negation), * (multiplication), / (division), and % ( modulus ); all are used here.

 var x=3, y=6; x = -x; x = y + 2; x  = y  1; x = y * y; x = y  / x; x = y % 4; 

In this example, x is first assigned “3, then 8, then 5, then 36, then 2, and finally 2 once again. Most likely the only unfamiliar operator is modulus (%), which results in the remainder of an integer division.

JavaScript also provides bitwise operators, such as & (AND), (OR), ^ (NOT), ~ (Exclusive OR), <<<< (left shift), and >>>> (right shift). While bitwise operators will seem familiar to some C programmers, given the high-level nature of JavaScript when it is used within the context of Web pages, they may seem a little out of place.

To compare objects, JavaScript provides a rich set of relational operators including == (equal to), != (not equal to), << (less than), >> (greater than), << = (less than or equal to), and >> = (greater than or equal to). Using a relational operator in an expression causes the expression to evaluate as true if the condition holds or false if otherwise . So,

5 << 10

would evaluate as true while

11 << 10

would evaluate as false .

Programmers should be very careful with the meanings of = and == . The first is the assignment operator, while the second is the conditional comparison operator. Mixing the two up is one of the most common mistakes found in JavaScript programs. For example,

 x = 5; 

assigns a value to x , while

 x == 5; 

compares the value of x with the literal 5. When these operators are misused within an if statement, a frustrating bug occurs.

Once comparisons are made, the logical operators && (AND), (OR), and ! (NOT) can be used to create more complex conditionals. For example,

 if ((x >>= 10) && (y << 3)) {    z = z + 1; } 

increments z if x is greater than or equal to 10 and y is less than 3.

Given the usefulness of incrementing and decrementing values, JavaScript provides, as do other languages, a shorthand notation. The operator ++ adds one to a value, while “ subtracts one. So, with

 var x=4; x++; 

the value of x at the end of execution is 5.

Note  

There is a subtle difference in the effect of positioning the ++ or “ “ operator before a value or after a value, as discussed in Chapter 4.

One very useful operator is the string operator (+), which is used to join strings together. The following script,

 document.write("JavaScript is " + "great."); 

outputs the joined string shown here:

click to expand

When operators are combined with variables as well as HTML, it is possible to create more complex output.

 var myName="Thomas"; document.write("Hello <<i>>"+myName+" <</i>>"); 
click to expand

Operator Precedence

When using operators, we must be careful about the order of evaluation. Given that different operators may have stronger precedence than others, the evaluation order may not be what is expected. For example, consider the following:

 var x = 4 + 5 * 8; 

Is the value of x set to 72 or to 44? The answer is 44, because the multiplication operator has higher precedence than addition. We can use parentheses to group expressions and force execution a certain way. So, to get the example to set x to 72 we would use

 var x = (4+5)*8; 

While this example was very easy, sometimes the order of execution is more ambiguous, so when in doubt add parentheses. The subtleties of all forms of operators are discussed in the first part of Chapter 4.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

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