Working with Values

[ LiB ]

Working with Values

JavaScripts and JScripts store information as values . For example, if you were to create a form for your users to fill out, each entry in the form would contain a separate value. Your scripts can store these values in variables and then use the variables throughout your script.

Table 2.1 shows the list of the types of values supported by JavaScript and JScript.

Table 2.1. JAVASCRIPT AND JSCRIPT VALUES

Value

Description

Boolean

A value that indicates a condition of either true or false

Null

An empty value

Numbers

A numeric value such as 99 or 3.142

Strings

A string of text such as "Welcome" or "Click here to visit ptpmagazine.com"


Declaring Variables

To use a variable in your script, that variable must first be declared. You have two ways of doing this. The first option is to use the var keyword as demonstrated in the following example:

 var firstName = "Alexander"; 

This example creates a variable named firstName and assigns it the value of Alexander. Your scripts would probably contain other variables that also contain information such as last names , phone numbers, and so on.

Optionally, you can also declare a variable by simply referencing it for the first time as shown in the following example:

 firstName = "Alexander"; 

NOTE

USE THE <NOSCRIPT> TAG TO TALK TO NON-JAVASCRIPT BROWSERS

Although more than 95 percent of the browsers being used today support JavaScript, there are still many that do not. In addition, both the Netscape and Internet Explorer browsers enable users to turn off JavaScript support. What can you do to make your JavaScript-enhanced pages available to those visitors who want to view them while still making basic information available to visitors who do not have JavaScript-enabled browsers?

One option you can explore is to create both JavaScript and non-JavaScript ver sions of your HTML pages and display the appropriate set of pages based on an inspection of the user 's browser. I will talk more about this option later today.

A simpler solution is to display an HTML page that provides two links with an instruction to your visitors to click on one link if their browser supports JavaScript and to click on the other if it does not. However, you may be taking a big risk by assuming that all your visitors even know what JavaScript is and that their browsers support it.

A really simple alternative is to use the <NOSCRIPT> tags. Every browser, even those with JavaScript support disabled, will recognize these HTML tags. Their purpose is to display a message for browsers that do not process your JavaScript. JavaScript-enabled browsers will ignore everything within the <NOSCRIPT> tags.

The following example demonstrates how to set up a page that can provide infor mation to browsers, regardless of their level of JavaScript support.

 <HTML>   <HEAD>     <TITLE>Script 2.2 - The NOSCRIPT tag</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!--Start hiding JavaScript statements       document.write("Non-JavaScript browsers will not see this message " +          "but JavaScript-enabled browsers will.");     // End hiding JavaScript statements -->     </SCRIPT>     <NOSCRIPT>       JavaScript-enabled browsers will not see this message but       JavaScript handicapped browsers will see it.     </NOSCRIPT>   </BODY> </HTML> 

In this example, a value of Alexander is assigned to a variable named firstName (if the variable exists), thereby changing its value. If the referenced variable does not yet exist, it is created and assigned a value.

Whether you choose to use the var keyword or not when creating variables is really just a matter of personal preference. The main benefit of using var is that it makes your scripts easier to read and also lets you declare variables for later use in your scripts without assigning them an initial starting value.

Working with Variables

I have to go over a few more things relating to variables before we move on. These important aspects of variables include the rules that govern the naming of variables and how to define variable scope.

Rules for Variable Names

Keep the following rules in mind when creating variables:

  • Variable names can consist only of uppercase and lowercase letters , the underscore character, and the numbers 0 through 9.

  • Variable names cannot begin with a number.

  • JavaScript and JScript are case sensitive. If you declare a variable with the name totalCount , you must refer to it using the exact same case throughout your script.

  • Variable names cannot contain spaces.

  • You cannot use any reserved words as variable names. Refer to Appendix C, "JavaScript and JScript Reserved Words," for a list of JavaScript and JScript reserved words.

The following list is not a set of rules but is a set of guidelines you may want to follow when working with variables:

  • JavaScript and JScript are considered to be a loosely typed languages because they do not force you to define variables before using them. However, using the var keyword makes your code easier to understand.

  • You should create variable names that describe their contents. For example, lastName is a much better variable name than ln . Variable names of only a few characters may be easier to type and may seem quite obvious when you are writing your scripts, but they may not be so obvious to you a year later or to someone else who is trying to read your script.

Defining Variable Scope

You can create variables that can be accessed by JavaScripts located throughout an HTML page or from any location within a JScript. Alternatively, you can create variables that can only be accessed within the constraints of a small section of code known as a function . Defining the space in which the variable is effective is known as defining the variable's scope . A variable can be either local or global in scope.

Local Variables

A local variable is one that is declared explicitly using the var statement inside a function. A function is a collection of script statements that can be called by another script statement to perform a specific action.

For example, the following code shows a function called ShowNotice() that displays a message every time it is called. This function uses the alert method belonging to the window object to display a text message specified by a local variable named textMessage , which has been set to "Are you sure you want to quit?" . Because this variable is local in scope, any statements located outside the function where it is defined cannot reference it.

 function ShowNotice() {   var textMessage = "Are you sure you want to quit?";   window.alert(textMessage); } 

You'll learn more about functions in just a few minutes.

NOTE

The window.alert(textMessage) statement in the preceding example is one of many types of pop-up dialogs that JavaScript and JScript can display. This particular example works only for JavaScripts because it relies on the browser's window object. I will go over how to display text messages using other options in greater detail later today.

Global Variables

A global variable is any variable defined outside of a function. Such a variable is global because any script statement located in the Web page or script file can refer to it. You can create a global variable in several ways, including:

  • Creating the variable by referencing it inside a function without first declaring it using the var keyword.

  • Creating the variable anywhere else in a JavaScript with or without the var keyword.

The following example demonstrates the differences between local and global variable scope. Three variables are created with a global scope. The first is glVarMsg1 in the head section of the page. The second and third variables are glVarMsg2 and glVarMsg3 in the body section of the page. The glVarMsg2 variable is global in scope even though it is located within a function because it was not created using the var keyword. The lcVarMsg1 variable is local in scope because it is in a function and was created with the var keyword.

 <HTML>   <HEAD>     <TITLE>Script 2.3 - A demonstration of variable scope</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       glVarMsg1 = "Global variables created in the HEAD section can be " +         "referenced anywhere in this page.";       function CreateVariables()       {       var lcVarMsg1 = "Local variables created inside a function cannot " +         "be referenced anywhere else.";       glVarMsg2 = "Global variables created inside functions in the HEAD " +         "section can be referenced anywhere in this page.";       }     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       CreateVariables();       glVarMsg3 = "Global variables created in the BODY section can be " +         "referenced anywhere in this page.";        document.write(glVarMsg1 + "<BR>");       document.write(glVarMsg2 + "<BR>");       document.write(glVarMsg3 + "<BR>");       document.write(lcVarMsg1 + "<BR>");     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

NOTE

TIP

Note the use of the + character in the previous example. It provides the ability to break up lengthy strings and spread them out over multiple lines.

NOTE

TIP

You may have noticed that I embedded the <BR> tag inside the document.write() statement. Doing so provides me with one way of controlling line breaks with JavaScripts. To make this work, I placed the <BR> tag in parentheses and concatenated it with the rest of the text in the document.write() statement using the + operator.

NOTE

TIP

You may also have noticed that the JavaScript in the head section contains a function named CreateVariables() .This line and the statements following it are part of a function.This function does not execute until it is called by the CreateVariables() statement in the body section of the page. Don't worry if this seems a bit confusing; I'll explain functions in greater detail later this morning.You might want to bookmark this example to come back and look at again after reading the material on functions.

Figure 2.1 shows what happens when the preceding script executes. The four document.write() statements attempt to display the value of each variable. However, because lcVarMsg1 is not global in scope, it is not displayed. Instead, only three of the document.write() statements execute correctly. The fourth statement, which attempts to display the value assigned to lcVarMsg1 , generates an error.

Figure 2.1. Only global variables or those local in scope to the document. write() statements will appear when the page is displayed.

graphic/02fig01.gif


NOTE

Depending on how you have configured your browser, the error message may or may not be displayed. For example, if you are using Internet Explorer to load the HTML page that contains the script and you have not configured it to display all error messages, the only indication of an error will be a small yellow icon and an error message displayed on the browser's status bar.

Manipulating Variables

You can alter the value of a variable by simply assigning it a new value as follows :

 variableName = 100; 

JavaScript also provides a number of other operators you can use to modify the value of variables. These are outlined in Table 2.2.

Table 2.2. JAVASCRIPT AND JSCRIPT OPERATORS

Operator

Description

Example

x + y

Adds the value of x to the value of y

total = 2 + 1

x - y

Subtracts the value of y from x

total = 2 - 1

x * y

Multiplies the value of x and y

total = x * 2

x / y

Divides the value of x by the value of y

total = x / 2

-x

Reverses the sign of x

count = -count

x++

Post-increment (returns x, then increments x by one)

x = y++

++x

Pre-increment (increments x by one, then returns x)

x = ++y

x

Post-decrement (returns x, then decrements x by one)

x = y

x

Pre-decrement (decrements x by one, then returns x)

x = y


I'll bet you are wondering what's going on with the last four operators in Table 2.2. I will take a moment to explain them a little further.

Both x++ and ++x operators increment the value of x by 1. The difference between them is when the update occurs. I can best demonstrate this difference with an example. Suppose that I have a script with two variables, totalCount and noUnitsSold . Suppose that noUnitsSold is equal to 10 and that I added the following line of code somewhere further down in my script:

 totalCount = ++noUnitsSold; 

What happens here is that first noUnitsSold would be incremented by 1 to a value of 11 . Then totalCount would be set to 11 . Now suppose that I rewrote the assignment statement to be the following:

 totalCount = noUnitsSold++; 

What happens here is totally different than in the preceding example. This time, totalCount is first set to the value of noUnitsSold , which is 10 . Then the value of noUnitsSold is incremented by 1 to 11 .

The x and x operators work the same way, only they decrease the value of the variables by 1.

Assigning Values

As I have already alluded to, you assign values to variables using an assign ment operator . For example, the following statement assigns a value of 44 to a variable named totalCount:

 totalCount = 44 

In this example, the assignment operator is the old-fashioned equals sign. JavaScript and JScript provide many ways to assign values to variables, as outlined in Table 2.3.

Table 2.3. ASSIGNMENT OPERATORS (ASSUME THAT Y = 5)

Operator

Description

Examples

Result

=

Sets a variable value equal to some value

x = y + 1

6

+=

Shorthand for writing x = x + y

x += y

11

-=

Shorthand for writing x = x - y

x -= y

6

*=

Shorthand for writing x = x * y

x *= y

30

/=

Shorthand for writing x = x / y

x /= y

6

%=

Shorthand for writing x = x % y

x %= y

1


The following example demonstrates the use of each of these operators. In this example, the script establishes two variables, x and y , and assigns a value of 10 to x and 5 to y . The next statements then test the five assignment operators listed in Table 2.3 to make sure they work as advertised. The first two of these statements set x = y + 1 and then use the document.write() statement to display the results. The remaining statements duplicate this methodology, changing only the mathematical formula each time. Figure 2.2 shows the result of running this script.

Figure 2.2. A demonstration of JavaScript and JScript operators

graphic/02fig02.gif


 <HTML>   <HEAD>     <TITLE>Script 2.4 - A demonstration of JavaScript opera tors</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var y = 5;       var x= y + 1;       document.write("x = y + 1 ...Result = " + x);       x += y;       document.write("<BR>x += y ...Result = " + x);       x -= y;       document.write("<BR>x -= y ...Result = " + x);       x *= y;       document.write("<BR>x *= y ...Result = " + x);       x /= y;       document.write("<BR>x /= y ...Result = " + x);     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Comparing Values

One of the things you will find yourself doing in your scripts is comparing the values of variables. For example, you might take one action if a variable has a value less than 10 and a different action when the variable is greater than 10. Table 2.4 provides a list of JavaScript and JScript comparison operators you can use in your scripts.

Table 2.4. JAVASCRIPT AND JSCRIPT COMPARISON OPERATORS

Operator

Description

Example

Result

==

Equal to

x == y

true if both x and y are the same

!==

Not equal to

x !== y

true if x and y are not the same

>

Greater than

x > y

true if x is greater than y

<

Less than

x < y

true if x is less than y

>=

Greater than or equal to

x >= y

true if x is greater than orequal to y

<=

Less than or equal to

x <= y

true if x is less than or equal to y

!x

Not

!x

true if x is false

&&

Both true

x && y

true if x and y are both true

Either true

x y

true if either x or y is true


The following JavaScript demonstrates the use of the greater-than operator. In this example, the two variables x and y are initialized with values of 12 and 5, respectively. Next, the script tests to see whether x is greater than 10. This condition is true , so the script writes a message to the browser window. Then the script tests the value of y to see whether it is greater than 10. This test is false , so no action is taken.

 <HTML>   <HEAD>     <TITLE>Script 2.5 - Example of a Value Comparison</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript"> <!-- Start hiding JavaScript statements   var x = 12;   var y = 5;   if (x > 10);   {     document.write("x is greater than 10!");   }        if (y > 10)       {         document.write("y is greater than 10!");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Writing Text with Strings

We have spent a lot of time already this morning learning about how to work with values. One object in particular, the String object, you will find yourself using over and over again in your scripts. I thought I'd spend a little time going over the String object now, even though the lesson on JavaScript and JScript objects isn't until this later this morning. Consider this a sneak preview.

The String object is made up of a collection of text characters. You create an instance of a String object using the new keyword, as shown in the following example:

 MyString = new String("This is an example of a text string."); 

This statement creates a String object called MyString and assigns text to it. The new keyword is used to create objects. However, you are not required to use it. You can also create a String object by simply referring to it as in the following example:

 MyString = "This is an example of a text string."; 

You can change the value assigned to a String object by assigning it a new value. The following example changes the value of the MyString string:

 MyString = "This is a second example of a text string."; 

String Properties

Because a String object is a built-in JavaScript and JScript object, it has properties. In the case of the String object, there is just one property, its length. You can refer to an object's property by typing the name of the object, followed by a period and the name of the property. In the case of the MyString object's length property, you'd use MyString.length. The length property contains the number of characters in the string. The following example demonstrates how to display the value of this property, which is 40.

 document.write("The length of MyString is " + MyString.length); 

String Methods

Although the String object has only one property, it has many methods. A method is an action that can be taken against the object. For example, you can use the String object's bold() method to display the string in bold, as shown in this example:

 document.write(MyString.bold()); 

When referencing an object's methods, the correct syntax to use is the name of the object, a period, the name of the method, and the left and right parentheses. In this example, the parentheses did not contain anything. Some methods enable you to pass arguments to the method by placing them inside the parentheses.

For example, you can display strings in all uppercase characters using the toUpperCase() method:

 document.write(MyString.toUpperCase()); 

Similarly, there is a toLowerCase() method. Other methods enable you to set the string's font color and font size or to display it in italic, blinking, or strikethrough text. A particularly useful method is substring() . This method enables you to extract a portion of a string's text.

For example, you might create a string that contains people's names and addresses. You could reserve the first 15 character positions of the string for the person's name, the next 20 characters for his street address, and the last 17 characters for the city, state, and ZIP code information. Below you will find three examples of this type of string.

 cust1Info = "Bobby B Jones  9995 Park Place Ct  Richmond VA 23232  "; cust2Info = "Sue K Miller   1112 Rockford Lane  Richmond VA 23232  "; cust3Info = "Bobby B Jones  9995 Richland Drive Richmond VA 23223  "; 

Now, using the String object's substring() method, you can extract just the name portion of any string, as shown in the following example:

 <HTML>   <HEAD>     <TITLE>Script 2.6 - Substring Method Example</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements     var cust1Info = "Bobby B Jones  9995 Park Place Ct Richmond VA 23232";      var cust2Info = "Sue K Miller   1112 Rockford Lane Richmond VA 23232";      var cust3Info = "Bobby B Jones  9995 Richland Drive Richmond VA 23223";      document.write(cust1Info.substring(0,14),"<BR>");      document.write(cust2Info.substring(0,14),"<BR>");      document.write(cust3Info.substring(0,14),"<BR>");     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

As you can see, the document.write(cust1Info.substring(0,14), "<BR>"); statement copies the contents of the first 15 characters in the string, starting with character 0 and ending with character 14, and writes those characters to the browser window. The script then repeats this logic for the remaining String objects. Figure 2.3 shows the result of loading this page.

Figure 2.3. A demonstration of how to extract portions of a string using the String object's substring() method

graphic/02fig03.gif


String Concatenation

You can do many cool things with strings. For example, you can concatenate two or more of them together using the + operator, as shown in the following example:

 <HTML>   <HEAD>     <TITLE>Script 2.7 - Example of String Concatenation</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var stringOne = "Once upon a time, ";       var stringTwo = "there was a little house on a hill.";       var stringThree = stringOne + stringTwo;       document.write(stringThree);     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

The script first establishes two strings, stringOne and stringTwo, and assigns them some text. Then it concatenates these two strings to create a new object named stringThree . Finally, the script displays the results in the browser window.

Notice that an extra space was added to the end of the stringOne object so that when it was concatenated with stringTwo , the resulting stringThree would read better, as shown in Figure 2.4.

Figure 2.4. This example demonstrates how to concatenate two strings together.

graphic/02fig04.gif


NOTE

In many computer languages, the programmer must specify the type of data that a variable will contain.This is known as the variable's data type. JavaScript and JScript support a range of data types, including numeric, Boolean, and string values. One nice thing about these languages is that they do not require you to specify a data type. In fact, they don't even allow it. Based on the context within which a value is created, JavaScript and JScript know what type of value it is. If you use the + sign with two numeric variables, they will be added together. If you use the + sign with two strings, they will automatically be concatenated. Finally, if you use the + sign with a numeric value and a string, the numeric value is converted automatically to a string and then is concatenated to the other string.

The Math Object

Having introduced you to the String object, it seems only proper at this point in the discussion that I talk a little about the Math object as well. This object is created automatically in every JavaScript and JScript, so you do not have to create an instance of it as you do with the String object. You can simply refer to the Math object when you need to. Like other objects, the Math object has properties and methods associated with it.

The Math object's properties contain mathematical constants. For example, the Math property PI stores the value of pi. The Math object's methods contain built-in mathematical functions. There are methods that round numbers up and down, generate random numbers, and return the absolute value of a number.

The following example demonstrates how to use several of the Math object's properties and methods:

 <HTML>   <HEAD>     <TITLE>Script 2.8 - Example of working with the Math object</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements        //Generate a random number between 0 and 1       document.write("<B>Random number between 0 - 1 = </B>", +         Math.random(), "<BR>");       //Generate a random number between 0 and 10       document.write("<B>Random number between 0 - 10 = </B>", +         Math.random() * 10, "<BR>");       //Rounding a number to the nearest whole number       document.write("<B>Rounding 6.777 = </B>", Math.round(6.777), "<BR>");       //Getting the value of PI       document.write("<B>Value of PI = </B>", Math.PI, "<BR>");       //Getting the absolute value of a number       document.write("<B>Absolute value of -55 = </B>", Math.abs(-55));     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

NOTE

You may have noticed that I slipped the <B> and </B> HTML tags into my JavaScripts to add bold formatting to my text.The key when using HTML tags is to keep them within the quotation marks. I could just as easily have inserted any of the other HTML tags within my script using the same technique.

The first three document.write() statements use the Math object's random() and round() methods. The fourth document.write() statement does not use a Math method. Instead, it accesses the Math PI property as evidenced by the lack of parentheses. The last of the document.write() statements demonstrates the Math abs() method, which returns the absolute value of any given number. Figure 2.5 shows the results of loading this page using Netscape Communicator.

Figure 2.5. An example of how to access the Math object's properties and methods

graphic/02fig05.gif


[ LiB ]


Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84

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