Special Operators


JavaScript also contains a number of operators that don't fit into any other category, and it calls them special operators . I'll take a look at them here.

Two of these operators, new and this , are ones that most JavaScript programmers use a lot, but the others are not in such common use. Feel free to skim over these operators and come back to them when you actually need them in your code.

The Conditional Operator: ?:

So far, the operators we've looked at have taken either one or two operands, but there is a JavaScript operator, the conditional operator, that takes three operands (making it JavaScript's only tertiary operator). Here's the syntax for this operator, which uses both a question mark (?) and a colon (:):

  condition  ?  expression1  :  expression2  

If condition evaluates to true, the operator returns the value of expression1 ; otherwise , it returns the value of expression2 . In other words, this operator provides you with a quick, each way to make a selection based on whether a certain condition is true. Here's an example: In this case, suppose a family is voting for pizza or hamburgers for dinner. I'll use the conditional operator to display the results:

(Listing 02-12.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With the Conditional Operator          </TITLE>      </HEAD>      <BODY>          <H1>Working With the Conditional Operator</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--              var votesForPizza = 5               var votesForHamburgers = 6  var result = votesForPizza > votesForHamburgers ? "Pizza wins!" : "Pizza graphics/ccc.gif didn't win."  document.write(result)          // -->          </SCRIPT>       </BODY>  </HTML> 

Figure 2.9 shows the result.

Figure 2.9. Using the conditional operator.

graphics/02fig09.gif

Tip

The conditional operator can be useful as a quick, one-line replacement for the if statementsee that statement later in this chapter.


The Comma Operator: ,

The comma operator enables you to specify two expressions to evaluate. This operator returns the value of the second operand. You use the comma operator when you want to include multiple expressions in a place that usually takes only one single expression.

It turns out that the most common place this operator is used is somewhere we won't cover until the next chapter: for loops . (If you've never seen for loops before, it's a good idea to wait until we do cover them, because I'll mention the comma operator there too.) The for loop enables you to repeat a series of statements a number of times; here's an example of the kind we'll decipher in the next chapterthe statements to be executed go between the curly braces, { and }:

 for (loop_index = 0; loop_index < 100; loop_index++)  {          .          .          .  } 

The expressions separated by semicolons enable you to initialize the loop, terminate it, and perform some operation each time through the loop, as we'll see in the next chapter. Normally, only one expression can be used in each position here, unless you use the comma operator, as in this case, where I'm using that operator to initialize both a variable named loop_index and a variable named total to 0 in the initialization part of the loop:

  for (loop_index = 0, total = 0; loop_index < 100; loop_index++)  {          .          .          .  } 

More on this exampleand the comma operatorin the next chapter, when we cover the for loop.

The delete Operator

The delete operator deletes an object, a property of an object, or an element at a particular index in an array. Here's how you use this operator:

 delete  object  delete  object  .  property  delete array[index] 

When you delete an element in an array, the length of the array doesn't change. In fact, no element in the array is affected except the one you've deleted. Here's an example; in this case, I'll create an array named sandwiches with the elements " turkey " , "cheddar" , "ham" , "tuna" , and "egg" . Next, I'll delete element 2, "ham" (remember that array indices start at 0, so element 2 is "ham" here) via the delete operator. Then I will check whether that element is really gone using the in operator, which is coming up next. In this case, if the expression 2 in sandwiches is false, element 2 was indeed deleted. I'll check that with an if statement of the kind we've already seen; in this case, the if statement will display the text Still here! if the element is still in the array; otherwise, the code in the else part of the if statement will be executed, displaying Sorry, that element is gone! :

(Listing 02-13.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With the delete Operator          </TITLE>      </HEAD>      <BODY>          <H1>Working With the delete Operator</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--  sandwiches = new Array("turkey", "cheddar", "ham", "tuna", "egg")   delete sandwiches[2]   if (2 in sandwiches) {   document.write("Still here!")   } else {   document.write("Sorry, that element is gone!")   }  // -->          </SCRIPT>       </BODY>  </HTML> 

You can see the results of this code in Figure 2.10; element 2 was indeed deleted. We'll see more on the in operator in the next topicand more on the if statement at the end of this chapter.

Figure 2.10. Using the delete operator.

graphics/02fig10.gif

The in Operator

The in operator returns true if a given element is in an array or a given property is in an object. We already saw the in operator in the preceding example using delete . In that example, we deleted an element from an array named sandwiches and checked to see whether it was really gone using in :

  if (2 in sandwiches) {  document.write("Still here!")  } else {        document.write("Sorry, that element is gone!")  } 

You also can check for properties in objects using in the in operator. For example, all arrays contain a length property, so the expression length in sandwiches would return true here.

The instanceof Operator

The instanceof operator returns true if a given object is of a particular object type. This operator is useful when you start working with different types of objects in JavaScripta JavaScript variable can hold any type of object, so how do you know what kind of object you're dealing with? One way to check is with the instanceof operator.

To use this operator, you use this syntax: object instanceof objectType . This expression will return true if object is an object of type objectType . Here's an example; in this case, I'm creating a string object named actor using the new operator (the new operator is coming up next), and then checking whether actor is indeed a string object, using the instanceof operator:

 <HTML>      <HEAD>          <TITLE>              Working With the instanceof Operator          </TITLE>      </HEAD>      <BODY>          <H1>Working With the instanceof Operator</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--  var actor = new String("Cary Grant")   if (actor instanceof String) {   document.write("It's a string.")   }  // -->          </SCRIPT>       </BODY>  </HTML> 

As you might expect, this example works as expected, displaying the text It's a string .

The new Operator

The new operator is a useful one; you use this operator to create new objects from a predefined object type such as string or array. Object types offer us a great deal of functionality, as we'll see throughout this book. For example, the string object type includes many built-in properties and methodsand to use those properties and methods , you use the new operator to create objects you can work with in your code from the various object types available.

Here's how you use this operator:

  object  = new  objectType  (  param1  [,  param2  ] ...[,  paramN  ]) 

In this case, you're creating a new object, object , of a particular type, objectType . The values param1 , param2 , and so on are parameter values you use when you create a new object, specifying, for example, the number of items in an array or the text you want in a string.

Let's see an example. We've seen this operator at work already when we've created new string and array objects; here's how we created a new string object in the example in the preceding topic, using new :

  var actor = new String("Cary Grant")  if (actor instanceof String) {      document.write("It's a string.")  } 

That's all it takes. When you create simple variables , you don't need to use new :

 var taxes = 1000000        //Too much!! 

But when you create an object from an object type , such as string or array, you do need to use new :

 var myString = new String("Now is the time!") 

Although we've only created objects of the built-in JavaScript object types array and string so far, the new operator works for any object type, whether that type is built in to JavaScript already, or whether it's an object type you've defined yourself (as we'll do in Chapter 23, "Cookies and Creating Your Own Objects").

The typeof Operator

Like instanceof , the typeof operator give you information about an operand's type. The instanceof operator enables you to compare an object's type to a known type, but the typeof operator tells you the object's type directly by returning a text string.

Here's an example; in this case, I'll declare a variable, store a number in it, and then check that variable's type:

(Listing 02-14.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With the typeof Operator          </TITLE>      </HEAD>      <BODY>          <H1>Working With the typeof Operator</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--  var value = 5   document.write("That item is a " + typeof value + ".")  // -->          </SCRIPT>       </BODY>  </HTML> 

As you can see in Figure 2.11, the typeof operator returned a string indicating that this variable holds a number.

Figure 2.11. Using the typeof operator to check a variable's type.

graphics/02fig11.gif

The void Operator

The void operator is the last of the special operators, and its use is pretty specialized. All this operator does is to discard the value returned by an expression when that expression is evaluated. This proves useful when you want to evaluate an expression but don't want to do anything with the value the expression returns. Suppose, for example, that you have a function named checkData that performs some calculations you want performed, but it also returns a value that you want to discard. You can do that like this:

 void(checkData) 

Tip

We're not going to have a lot of use for the void operator, but I'm including it here for the sake of completeness; it does have occasional uses. One place it's sometimes used is in inline scripts that call functions that normally return values, because some browsers handle such values badly in inline scripts.




Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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