scripting again hope you are available

User Generated

havdhrylzr

Computer Science

Description

Scripting lab.docx        this is the task info.


COP 2840 - Content Generation Scripting Languages Chapter 2.pdf


As is the norm if you need anything else, let me know.

Unformatted Attachment Preview

Scripting lab In this assignment, you will write a web page, and have a user enter data. The web page should have code calculating per the requirements. You will use all the concepts in Chapters 1-2. • Chapter 2, Working with Functions, Data Types, and Operators, Discovery Project 2-2, page 133. Instructors instructions: Lab Work for Week 2: This week’s Lab Work will give you hands-on experience with writing JavaScript. Since Chapter 2 covers functions, data types, and operators, you will get practice with these concepts in the Lab Work. You will need a text editor to create your Web pages that have JavaScript code. I like Notepad++ which is free. You can download it from this link: http://notepad-plus-plus.org/download/v6.5.5.html For the Week 2 Lab Work, you will complete: Chapter 2, Working with Functions, Data types, and Operators, Discovery Project 2-2, page 133. CHAPTER 2 Working with Functions, Data Types, and Operators In this chapter, you will:  Learn how to use functions to organize your JavaScript code  Study data types  Use expressions and operators  Study operator precedence Working with Functions So far, the code you have written has consisted of simple statements placed within script sections. However, almost all programming languages, including JavaScript, allow you to group programming statements in logical units. In JavaScript, groups of statements that you can execute as a single unit are called functions. You’ll learn how to use functions in this chapter. In addition to functions, one of the most important aspects of programming is the ability to store values in computer memory and to manipulate those values. In the last chapter, you learned how to store values in computer memory using variables. The values, or data, contained in variables are classified into categories known as data types. In this chapter, you will learn about JavaScript data types and the operations that can be performed on them. Working with Functions In Chapter 1, you learned that procedures associated with an object are called methods. In JavaScript programming, you can write your own procedures, called functions, which refer to a related group of JavaScript statements that are executed as a single unit. Functions are virtually identical to methods except that they are not associated with an object the way the write() method is associated with the Document object. Functions, like all JavaScript code, must be contained within a element. In the following section, you’ll learn more about incorporating functions in your scripts. Defining Functions Before you can use a function in a JavaScript program, you must first create, or define, it. The lines that make up a function are called the function definition. The syntax for defining a function is: function name_of_function(parameters) { statements; } Parameters are placed within the parentheses that follow a function name. A parameter is a variable that is used within a function. Placing a parameter name within the parentheses of a function definition is the equivalent of declaring a new variable. However, you do not need to include the var keyword. For example, suppose that you want to write a function named calculate_square_root() that calculates the square root of a number contained in a parameter 73 CHAPTER 2 74 Functions do not have to contain parameters. Many functions only perform a task and do not require external data. For example, you might create a function that displays the same message each time a user visits your Web site; this type of function only needs to be executed and does not require any other information. Working with Functions, Data Types, and Operators named number. The function name would then be written as calculate_square_root(number). In this case, the function declaration is declaring a new parameter (which is a variable) named number. Functions can contain multiple parameters separated by commas. To add three separate number parameters to the calculate_square_root() function, you would write the function name as calculate_square_root(number1, number2, number3). Note that parameters (such as the number1, number2, and number3) receive their values when you call the function from elsewhere in your program. (You will learn how to call functions in the next section.) Following the parentheses that contain the function parameters is a set of curly braces (called function braces) that contain the function statements. Function statements are the statements that do the actual work of the function (such as calculating the square root of the parameter, or displaying a message on the screen) and must be contained within the function braces. The following is an example of a function that prints the names of several students using the write() methods of the Document object. (Recall that functions are very similar to the methods associated with an object.) function printStudentNames(student1, student2, student3) { document.write("" + student1 + ""); document.write("" + student2 + ""); document.write("" + student3 + ""); } A JavaScript program is composed of all the sections within a document; each individual section is not necessarily its own individual JavaScript program (although it could be if there are no other sections in the document). Notice how the preceding function is structured. The opening curly brace is on the same line as the function name, and the closing curly brace is on its own line following the function statements. Each statement between the curly braces is indented one-half inch. This structure is the preferred format among many JavaScript programmers. However, for simple functions it is sometimes easier to include the function name, curly braces, and statements on the same line. (Recall that JavaScript ignores line breaks, spaces, and tabs.) The only syntax requirement for spacing in JavaScript is that semicolons separate statements on the same line. Always put your functions within the document head, and place calls to a function within the body section. As you recall, the document head is always rendered before the document body. Thus, placing functions in the head section and function calls in the body section ensures that functions are created before they are actually called. If your program does attempt to call a function before it has been created, you will receive an error. Working with Functions Next, you will work on an existing Web site for a wedding-hosting company named CV Wedding Hall. You can find the CV Wedding Hall files in a folder named CVWeddingHall in your Chapter folder for Chapter 2. The Web site contains two pages: a page that can be used to estimate wedding costs and a guest book page. First, you will work on the guest book page. You won’t actually be able to save the guest list by submitting it to a server-side script. Instead, you will just use the page in order to practice some of the techniques that are taught in this chapter. To start working on the guest book page: 1. Open the guestbook.html file, located in a folder named CVWeddingHall in your Chapter folder for Chapter 2, in your text editor. 2. Locate the text [Add code here] and replace it with the following form. You will use this form to add guests to the element. Guest   Relationship 3. Add the following script section to the document head: /* */ 4. Add the following function definition to the script section. The statements within the function definition build a text variable named guestInfo, which contains the guest name and relationship. This string is then assigned as the value of the element. 75 CHAPTER 2 Working with Functions, Data Types, and Operators function addGuest(){ var guestInfo = document.newGuest.guestName.value + ", "; guestInfo += document.newGuest.relationship.value; document.newGuest.guests.value = guestInfo; } 76 5. Save the guestbook.html file and leave it open in your text editor. Calling Functions A function definition does not execute automatically. Creating a function definition only names the function, specifies its parameters, and organizes the statements it will execute. To execute a function, you must invoke, or call, it from elsewhere in your program. The code that calls a function is referred to as a function call and consists of the function name followed by parentheses, which in turn contains any variables or values to be assigned to the function parameters. The variables or values that you place in the parentheses of the function call statement are called arguments or actual parameters. Sending arguments to the parameters of a called function is called passing arguments. When you pass arguments to a function, the value of each argument is then assigned to the value of the corresponding parameter in the function definition. (Again, remember that parameters are simply variables that are declared within a function definition.) Next, you will add a function call to the onclick event handler of the Add Guest button. To call the addGuest() function: 1. Return to the guestbook.html file in your text editor. 2. Locate the button control in the form and add the following onclick event handler: onclick="addGuest()" 3. Save the document as guestbook.html file, and open it in your Web browser. Add a name and relationship to the Guest and Relationship fields, and click the Add Guest button. Figure 2-1 shows how the page appears after adding a guest. Working with Functions 77 After you learn how to work with strings, later in this chapter, you will be able to add multiple guests to the guest book page. Figure 2-1 4. Guest book page after adding a guest Close your Web browser window. In many instances, you may want your program to receive the results from a called function and then use those results in other code. For instance, consider a function that calculates the average of a series of numbers that are passed to it as arguments. Such a function would be useless if your program could not print or use the result elsewhere. As another example, suppose that you have created a function that simply prints the name of a student. Now suppose that you want to alter the program so that it uses the student name in another section of code. You can return a value from a function to a calling statement by assigning the calling statement to a variable. The following statement calls a function named averageNumbers() and assigns the return value to a variable named returnValue. The statement also passes three literal values to the function. var returnValue = averageNumbers(1, 2, 3); To actually return a value to a returnValue variable, the code must include a return statement within the averageNumbers() function. A return statement is a statement that returns a value to the statement that called the function. To use a return statement, you use the return keyword with the variable or value you want to CHAPTER 2 Working with Functions, Data Types, and Operators send to the calling statement. The following script contains the averageNumbers() function, which calculates the average of three numbers. The script also includes a return statement that returns the value (contained in the result variable) to the calling statement: 78 A function does not necessarily have to return a value. function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } Next, you will add a function call to the onclick event handler of the Add Guest button. You will also modify the addGuest() function so that the guest name and relationship are passed to it as arguments, and so it returns a string to the function call. To call the addGuest() function: 1. Return to the guestbook.html file in your text editor. 2. Modify the addGuest() function definition so that it includes two parameters: name and relationship. Then, modify the statements that build the guestInfo variable so that they reference the parameters instead of the form values. Also, replace the last statement that assigns the guestInfo variable to the element with a statement that returns the variable to the function. Your modified function should appear as follows: function addGuest(name, relationship) { var guestInfo = name + ", "; guestInfo += relationship; return guestInfo; } 3. Be sure to type the string to the right on a single line. Modify the onclick event handler in the button control so it includes two statements. The first statement in the event handler calls the addGuest() function and passes to it the values of the name and relationship fields. The second statement then assigns the returned value to the field. The modified event handler should appear as follows: onclick="var newGuest=addGuest( document.newGuest.guestName.value, document.newGuest.relationship.value); document.newGuest.guests.value=newGuest" 4. Save the guestbook.html file, and open it again in your Web browser. The script should function the same as it did before you modified the function and event handler. 5. Close your Web browser window. Working with Functions Understanding Variable Scope When you use a variable in a JavaScript program, particularly a complex JavaScript program, you need to be aware of the variable’s scope—that is, you need to think about where in your program a declared variable can be used. A variable’s scope can be either global or local. A global variable is one that is declared outside a function and is available to all parts of your program. A local variable is declared inside a function and is only available within the function in which it is declared. Local variables cease to exist when the function ends. If you attempt to use a local variable outside the function in which it is declared, you will receive an error message. You must use the var keyword when you declare a local variable. However, when you declare a global variable, the var keyword is optional. For example, you can write the statement var myVariable = "This is a variable."; as myVariable = "This is a variable.";. If you declare a variable within a function and do not include the var keyword, the variable automatically becomes a global variable. However, it is considered good programming technique to always use the var keyword when declaring variables because it makes it clear in your code when and where you intend to start using the variable. It is also considered poor programming technique to declare a global variable inside of a function by not using the var keyword because it makes it harder to identify the global variables in your scripts. Using the var keyword forces you to explicitly declare your global variables outside of any functions and local variables within a function. The following script includes a global variable named salesPrice and a function containing two variable declarations. The first variable declaration in the function, for the shippingPrice variable, is a global variable because it does not include the var keyword. The second variable declaration in the function, for the totalPrice variable, is a local variable because it does include the var keyword. Both the global variable and the function are contained in a script section in the document head. When the function is called from the document body, the global variables and the local variable print successfully from within the function. After the call to the function, the global variables again print successfully from the document body. However, when the script tries to print the local variable from the document body, an error message is generated because the local variable ceases to exist when the function ends. The parameters within the parentheses of a function declaration are local variables. 79 CHAPTER 2 80 Remember that it is considered poor programming practice to intentionally declare a global variable inside of a function by eliminating the var keyword. The only intention of the shippingPrice variable in the preceding example is to illustrate variable scope. If the example really needed the shippingPrice variable to be a global variable, then it should be declared at the global level with the salesPrice variable. Working with Functions, Data Types, and Operators ... Calculate Sales Price /* */ /* */ When a program contains a global variable and a local variable with the same name, the local variable takes precedence when its function is called. However, the value assigned to a local variable of the same name is not assigned to a global variable of the same name. In the following code, the global variable pitcher is assigned a value of “Josh Beckett” before the function that contains a local variable of the same name is called. Once the function is called, the local pitcher variable is assigned a value of “Tim Lincecum”. After the function ends, “Tim Lincecum” is still the value of the global pitcher variable. Figure 2-2 shows the output in a Web browser. var pitcher = "Josh Beckett"; function duplicateVariableNames() { var pitcher = "Tim Lincecum"; document.write("" + pitcher + ""); // value printed is Tim Lincecum } Working with Functions duplicateVariableNames(); document.write("" + pitcher + ""); // value printed is Josh Beckett Figure 2-2 Output of a program that contains a global variable and a local variable with the same name Next, you will add global variables to the index.html page of the CV Wedding Hall site. The index.html page will contain a calculator for estimating the cost of a wedding reception. The global variables you add will store the number of guests who will be attending, the number of required limousines, the cost of live music, flowers, and an open bar, and, finally, the total estimate. You will complete the index. html page later in this chapter. To add global variables to the index.html page of the CV Wedding Hall site: 1. Open the index.html file, located in a folder named CVWeddingHall in your Chapter folder for Chapter 2, in your text editor. 2. Add the following script section to the document head: /* */ 3. Save the index.html file and leave it open in your text editor. Using Built-in JavaScript Functions In addition to custom functions that you create yourself, JavaScript allows you to use the built-in functions listed in Table 2-1. Although the code that displays the output shown in Figure 2-2 is syntactically correct, it is poor programming practice to use the same name for local and global variables because it makes your scripts confusing, and it is difficult to track which version of the variable is currently being used by the program. 81 CHAPTER 2 82 Working with Functions, Data Types, and Operators Function Description decodeURI(string) Decodes text strings encoded with encodeURI() decodeURIComponent(string) Decodes text strings encoded with encodeURIComponent() encodeURI(string) Encodes a text string so that it becomes a valid URI encodeURIComponent(string) Encodes a text string so that it becomes a valid URI component eval(string) Evaluates expressions contained within strings isFinite(number) Determines whether a number is finite isNaN(number) Determines whether a value is the special value NaN (Not a Number) parseFloat(string) Converts string literals to floating-point numbers parseInt(string) Converts string literals to integers Table 2-1 Built-in JavaScript functions In this book, you will examine several of the built-in JavaScript functions as you need them. For now, you just need to understand that you call built-in JavaScript functions in the same way you call a custom function. For example, the following code calls the isNaN() function to determine whether the socialSecurityNumber variable is not a number. Because the Social Security number assigned to the socialSecurityNumber variable contains dashes, it is not a true number. Therefore, the isNaN() function returns a value of true to the checkVar variable. var socialSecurityNumber = "123-45-6789"; var checkVar = isNaN(socialSecurityNumber); document.write(checkVar); Short Quiz 1 1. What is the difference between arguments and parameters? 2. How do you execute a function? 3. Why would you want to return a value from a function? 4. What is variable scope? Working with Data Types Working with Data Types Variables can contain many different kinds of values—for example, the time of day, a dollar amount, or a person’s name. A data type is the specific category of information that a variable contains. The concept of data types is often difficult for beginning programmers to grasp because in real life you don’t often distinguish among different types of information. If someone asks you for your name, your age, or the current time, you don’t usually stop to consider that your name is a text string and that your age and the current time are numbers. However, a variable’s specific data type is very important in programming because the data type helps determine how much memory the computer allocates for the data stored in the variable. The data type also governs the kinds of operations that can be performed on a variable. Data types that can be assigned only a single value are called primitive types. JavaScript supports the five primitive data types described in Table 2-2. Data type Description Number Positive or negative numbers with or without decimal places, or number written using exponential notation Boolean A logical value of true or false String Text such as “Hello World” Undefined A variable that has never had a value assigned to it, has not been declared, or does not exist Null An empty value Table 2-2 Primitive JavaScript data types The null value is a data type as well as a value that can be assigned to a variable. Assigning the value “null” to a variable indicates the variable does not contain a usable value. A variable with a value of “null” has a value assigned to it—null is really the value “no value.” You assign the “null” value to a variable when you want to ensure that the variable does not contain any data. In contrast, an undefined variable is a variable that has never had a value assigned to it, has not been declared, or does not exist. The value undefined indicates that the variable has never been assigned a value—not even the null value. One use for an undefined variable is to determine whether a value is being used by another part of your script. As an example of an undefined variable, the following code declares a variable named stateTax variable without a value. When the second statement uses the document.write() method to print the stateTax variable, a 83 CHAPTER 2 Working with Functions, Data Types, and Operators value of “undefined” is printed because the variable has not yet been assigned a value. The variable is then assigned a value of 40, printed to the screen, and then a value of “null”, which is also printed to the screen. Figure 2-3 shows the output in a Web browser. var stateTax; document.write("Your state tax is $" + stateTax + "."); stateTax = 40; document.write("Your state tax is $" + stateTax + "."); stateTax = null; document.write("Your state tax is $" + stateTax + "."); 84 The JavaScript language also supports a more advanced type, Object, which is used for creating a collection of properties. You will learn about the Object type in Chapter 6. Figure 2-3 Variable assigned values of “undefined” and “null” Many programming languages require that you declare the type of data that a variable contains. Programming languages that require you to declare the data types of variables are called strongly typed programming languages. Strong typing is also known as static typing, because data types do not change after they have been declared. Programming languages that do not require you to declare the data types of variables are called loosely typed programming languages. Loose typing is also known as dynamic typing because data types can change after they have been declared. JavaScript is a loosely typed programming language. In JavaScript, you are not required to declare the data type of variables and, in fact, are not allowed to do so. Instead, the JavaScript interpreter automatically determines what type of data is stored in a variable and assigns the variable’s data type accordingly. The following code demonstrates Working with Data Types how a variable’s data type changes automatically each time the variable is assigned a new literal value: diffTypes diffTypes diffTypes diffTypes diffTypes = = = = = "Hello World"; // String 8; // Integer number 5.367; // Floating-point number true; // Boolean null; // null 85 The next two sections focus on two especially important data types: numeric and Boolean data types. Understanding Numeric Data Types Numeric data types are an important part of any programming language and are particularly useful for arithmetic calculations. JavaScript supports two numeric data types: integers and floatingpoint numbers. An integer is a positive or negative number with no decimal places. Integer values in JavaScript can range from -9007199254740990 (-253) to 9007199254740990 (253). The numbers -250, -13, 0, 2, 6, 10, 100, and 10000 are examples of integers. The numbers -6.16, -4.4, 3.17, .52, 10.5, and 2.7541 are not integers; they are floating-point numbers because they contain decimal places. A floating-point number is a number that contains decimal places or that is written in exponential notation. Exponential notation, or scientific notation, is a shortened format for writing very large numbers or numbers with many decimal places. Numbers written in exponential notation are represented by a value between 1 and 10 multiplied by 10 raised to some power. The value of 10 is written with an uppercase or lowercase E. For example, the number 200,000,000,000 can be written in exponential notation as 2.0e11, which means “two times ten to the eleventh power.” Floating-point values in JavaScript range from approximately ±1.7976931348623157 x 10308 to ± 5 x 10—324. Next, you will create a script that uses variables containing integers, floating-point numbers, and exponential numbers to print the 20 prefixes of the metric system. A metric prefix, or SI prefix, is a name that precedes a metric unit of measure. For example, the metric prefix for centimeter is centi; it denotes a value of 1/100th. In other words, a centimeter is the equivalent of 1/100th of a meter. To create a script that prints metric prefixes: 1. Create a new document in your text editor. 2. Type the declaration, element, header information, and the element. Use the strict DTD and “Metric Prefixes” as the content of the element. Floating-point values that exceed the largest positive value of ±1.7976931348623157 × 10308 result in a special value of Infinity. Floating-point values that exceed the smallest negative value of ±5 × 10−324 result in a value of –Infinity. CHAPTER 2 Working with Functions, Data Types, and Operators Include a element that links to the js_styles.css style sheet in your Chapter folder. Your document should appear as follows: Metric Prefixes 86 3. Add the following heading element to the document body: Metric Prefixes 4. Add the following script section to the end of the document body: /* */ 5. In the script section, add the following variable declarations for the 20 metric prefixes: var var var var var var var var var var var var var var var var var var var var yotta = 1e24; zetta = 1e21; exa = 1e18; peta = 1e15; tera = 1e12; giga = 1e9; mega = 1e6; kilo = 1000; hecto = 100; deca = 10; deci = .1; centi = .01; milli = .001; micro = 1e-6; nano = 1e-9; pico = 1e-12; femto = 1e-15; atto = 1e-18; zepto = 1e-21; yocto = 1e-24; Working with Data Types 6. Add to the end of the script section the following statements to print the value of each metric prefix variable as cells in a table: document.write(" PrefixDecimal Equivalent"); document.write("Yotta" + yotta + ""); document.write("Zetta" + zetta + ""); document.write("Exa" + exa + ""); document.write("Peta" + peta + ""); document.write("Tera" + tera + ""); document.write("Giga" + giga + ""); document.write("Mega" + mega + ""); document.write("Kilo" + kilo + ""); document.write("Hecto" + hecto + ""); document.write("Deca" + deca + ""); document.write("Deci" + deci + ""); document.write("Centi" + centi + ""); document.write("Milli" + milli + ""); document.write("Micro" + micro + ""); document.write("Nano" + nano + ""); document.write("Pico" + pico + ""); document.write("Femto" + femto + ""); document.write("Atto" + atto + ""); document.write("Zepto" + zepto + ""); document.write("Yocto" + yocto + ""); document.write(""); 7. Save the document as MetricPrefixes.html in the Chapter folder for Chapter 2, and then validate it with the W3C Markup Validation Service at http://validator.w3.org/. Once the file is valid, close it in your text editor. 87 CHAPTER 2 Working with Functions, Data Types, and Operators 8. Open the MetricPrefixes.html document in your Web browser. Figure 2-4 shows how the document looks in a Web browser. 88 Most Web browsers automatically display very large numbers, such as the values represented by the zetta and yotta metric prefixes, in exponential format. Figure 2-4 9. MetricPrefixes.html document in a Web browser Close your Web browser window. Using Boolean Values A Boolean value is a logical value of true or false. You can also think of a Boolean value as being yes or no, or on or off. Boolean values are most often used for deciding which parts of a program should execute and for comparing data. In JavaScript programming, you can only use the words true and false to indicate Boolean values. In other programming languages, you can use the integer values of 1 and 0 to indicate Boolean values of true and false—1 indicates true and 0 indicates false. JavaScript converts the values true and false to the integers 1 and 0 when necessary. For example, when you attempt to use a Boolean variable of true in a mathematical operation, JavaScript converts the variable to an integer value of 1. The following shows a simple example of two variables that are assigned Boolean values, Working with Data Types one true and the other false. Figure 2-5 shows the output in a Web browser: var newCustomer = true; var contractorRates = false; document.write("New customer: " + newCustomer + ""); document.write("Contractor rates: " + contractorRates + ""); Figure 2-5 Boolean values Next, you will add Boolean global variables to the index.html page of the CV Wedding Hall site. These variables will determine whether the wedding reception will include live music and flowers. To add five Boolean global variables to the index.html page: 1. Return to the index.html file in your text editor. 2. Add to the script section the following global variables for the number of guests and limousines, the cost of live music, flowers, and the total estimate: var var var var var 3. guestsCost = 0; limousinesCost = 0; liveMusicCost = 0; flowersCost = 0; totalEstimate = 0; Save the index.html file. Working with Strings As you learned in Chapter 1, a text string contains zero or more characters surrounded by double or single quotation marks. Examples of strings you may use in a script are company names, usernames, comments, and other types of text. You can use text strings as literal values or assign them to a variable. 89 CHAPTER 2 Working with Functions, Data Types, and Operators Literal strings can also be assigned a zero-length string value called an empty string. For example, the following statement declares a variable named customerName and assigns it an empty string: var customerName = ""; 90 Empty strings are valid values for literal strings and are not considered to be null or undefined. Why would you want to assign an empty string to a literal string? Think for a moment about the prompt() method, which displays a dialog box with a message, a text box, an OK button, and a Cancel button. You can pass two string arguments to the prompt() method. The first argument displays an instruction to the user, while the second argument is the default text that appears in the prompt dialog box text box. If you do not include the second argument, then the value “undefined” appears as the default text of the prompt dialog box. To prevent “undefined” from displaying as the default text in the prompt dialog text box, you pass an empty string as the second argument of the prompt() method. When you want to include a quoted string within a literal string surrounded by double quotation marks, you surround the quoted string with single quotation marks. When you want to include a quoted string within a literal string surrounded by single quotation marks, you surround the quoted string with double quotation marks. Whichever method you use, a string must begin and end with the same type of quotation marks. For example, you can use either document.write("Alexander Rodriguez is called 'A-Rod'.") or document.write('Alexander Rodriguez is called "A-Rod".'). Thus, document.write("This is a text string."); is valid, because it starts and ends with double quotation marks, whereas the statement document.write("This is a text string.'); is invalid, because it starts with a double quotation mark and ends with a single quotation mark. In the second case, you would receive an error message because the Web browser cannot tell where the literal strings begin and end. The following code shows an example of a script that prints strings. Figure 2-6 shows the output. document.write("This is a literal string."); document.write("This string contains a 'quoted' string."); document.write('This is another example of a "quoted" string.'); var firstString = "This literal string was assigned to a variable."; var secondString = 'This literal string was also assigned to a variable.'; document.write(firstString); document.write(secondString); Working with Data Types Figure 2-6 String examples in a Web browser String Operators JavaScript has two operators that can be used with strings: + and +=. When used with strings, the plus sign is known as the concatenation operator. The concatenation operator (+) is used to combine two strings. You have already learned how to use the concatenation operator. For example, the following code combines a string variable and a literal string, and assigns the new value to another variable: var destination = "Honolulu"; var location = "Hawaii"; destination = destination + " is in " + location; The combined value of the location variable and the string literal that is assigned to the destination variable is “Honolulu is in Hawaii.” You can also use the compound assignment operator (+=) to combine two strings. The following code combines the two text strings, but without using the location variable: var destination = "Honolulu"; destination += " is in Hawaii"; Note that the same symbol—a plus sign—serves as the concatenation operator and the addition operator. When used with numbers or variables containing numbers, expressions using the concatenation operator return the sum of the two numbers. As you learned earlier in this chapter, if you use the concatenation operator with a string value and a number value, the string value and the number value are combined into a new string value, as in the following example: var textString = "The legal voting age is "; var votingAge = 18; newString = textString + votingAge; Unlike other programming languages, JavaScript includes no special data type for a single character, such as the char data type in the C, C++, and Java programming languages. 91 CHAPTER 2 Working with Functions, Data Types, and Operators Escape Characters and Sequences 92 You need to use extra care when using single quotation marks with possessives and contractions in strings, because the JavaScript interpreter always looks for the first closing single or double quotation mark to match an opening single or double quotation mark. For example, consider the following statement: document.write('My city's zip code is 94558.'); This statement causes an error. The JavaScript interpreter assumes that the literal string ends with the apostrophe following “city” and looks for the closing parentheses for the document.write() statement immediately following “city’s”. To get around this problem, you include an escape character before the apostrophe in “city’s”. An escape character tells the compiler or interpreter that the character that follows it has a special purpose. In JavaScript, the escape character is the backslash \. Placing a backslash in front of an apostrophe tells the JavaScript interpreter that the apostrophe is to be treated as a regular keyboard character, such as “a”, “b”, “1”, or “2”, and not as part of a single quotation mark pair that encloses a text string. The backslash in the following statement tells the JavaScript interpreter to print the apostrophe following the word “city” as an apostrophe. document.write('My city\'s zip code is 94558.'); You can also use the escape character in combination with other characters to insert a special character into a string. When you combine the escape character with other characters, the combination is called an escape sequence. The backslash followed by an apostrophe \' and the backslash followed by a double quotation mark \" are both examples of escape sequences. Most escape sequences carry out special functions. For example, the escape sequence \t inserts a tab into a string. Table 2-3 describes the escape sequences that can be added to a string in JavaScript. Escape sequence Character \\ Backslash \b Backspace \r Carriage return \" Double quotation mark \f Form feed \t Horizontal tab \n Newline Table 2-3 JavaScript escape sequences (continues) Working with Data Types (continued) Escape sequence Character \0 Null character \' Single quotation mark \v Vertical tab \XX Latin-1 character specified by the XX characters, which represent two hexadecimal digits \XXXXX Unicode character specified by the XXXX characters, which represent four hexadecimal digits Table 2-3 JavaScript escape sequences Notice that one of the characters generated by an escape sequence is the backslash. Because the escape character itself is a backslash, you must use the escape sequence \\ to include a backslash as a character in a string. For example, to include the path “C:\JavaScript_Projects\ Files\” in a string, you must include two backslashes for every single backslash you want to appear in the string, as in the following statement: document.write("My JavaScript files are located in C:\\JavaScript_Projects\\Files\\"); The following code shows an example of a script containing strings with several escape sequences. Figure 2-7 shows the output. /* */ 93 If you place a backslash before any character other than those listed in Table 2-3, the backslash is ignored. CHAPTER 2 94 Several of the escape sequences, including the new line and horizontal tab escape sequences, are only recognized inside a container element such as the element. Working with Functions, Data Types, and Operators Figure 2-7 Output of script with strings containing escape sequences The current version of the guest book page only allows you to add a single guest to the element. In order to add multiple guests on individual lines, you need to add a carriage return escape sequence (\r) to the end of each line. To modify the guest book page so you can add multiple guests: 1. Return to the guestbook.html file in your text editor. 2. Modify the statement in the addGuest() method that assigns the relationship argument to the guestInfo variable so that it also includes a carriage return escape sequence, as follows: guestInfo += relationship + "\r"; 3. Modify the last statement in the button element’s onclick event handler so that it adds the new guest string to the existing value in the element, as follows: onclick="var newGuest=addGuest( document.newGuest.guestName.value, document.newGuest.relationship.value); document.newGuest.guests.value= document.newGuest.guests.value + newGuest" 4. Save the guestbook.html file, and then validate it with the W3C Markup Validation Service at http://validator.w3.org/. Once the file is valid, close it in your text editor. Open it again in your Web browser and test the script to ensure that you can add multiple guests. 5. Close your Web browser window. Using Operators to Build Expressions Short Quiz 2 1. What is the difference between loosely typed and strongly typed programming languages? 2. Explain exponential notation. 3. What are Boolean values and how do you use them? 4. Explain how to use the concatenation and compound assignment operators with strings. 5. What are escape characters and escape sequences? 95 Using Operators to Build Expressions In Chapter 1, you learned the basics of how to create expressions using basic operators, such as the addition operator (+) and multiplication operator (*). In this section, you will learn about additional types of operators you can use with JavaScript. Table 2-4 lists the operator types that you can use with JavaScript. Operator type Operators Description Arithmetic addition (+) Used for performing mathematical calculations subtraction (-) multiplication (*) division (/) modulus (%) increment (++) decrement (--) negation (-) Assignment assignment (=) compound addition assignment (+=) compound subtraction assignment (–=) compound multiplication assignment (*=) Table 2-4 JavaScript operator types (continues) Assigns values to variables CHAPTER 2 Working with Functions, Data Types, and Operators (continued) Operator type Operators Description compound division assignment (/=) 96 compound modulus assignment (%=) Comparison equal (==) Compares operands and returns a Boolean value strict equal (===) not equal (!=) strict not equal (!==) greater than (>) less than (=) less than or equal ( Returns true if the left operand is greater than the right operand Less than < Returns true if the left operand is less than the right operand Greater than or equal >= Returns true if the left operand is greater than or equal to the right operand Less than or equal 4; results in true because the number 5 is numerically greater than the number 4. When 107 CHAPTER 2 108 The comparison operator (==) consists of two equal signs and performs a different function than the one performed by the assignment operator that consists of a single equal sign =. The comparison operator compares values, whereas the assignment operator assigns values. Comparison operators are often used with two kinds of special statements: conditional statements and looping statements. You’ll learn how to use comparison operators in such statements in Chapter 3. Working with Functions, Data Types, and Operators two nonnumeric values are used as operands, the JavaScript interpreter compares them in alphabetical order. The statement arithmeticValue = "b" > "a"; returns true because the letter b is alphabetically greater than the letter a. When one operand is a number and the other is a string, the JavaScript interpreter attempts to convert the string value to a number. If the string value cannot be converted to a number, a value of false is returned. For example, the statement arithmeticValue = 10 == "ten"; returns a value of false because the JavaScript interpreter cannot convert the string “ten” to a number. The comparison operator is often used with another kind of operator, the conditional operator. The conditional operator executes one of two expressions, based on the results of a conditional expression. The syntax for the conditional operator is conditional expression ? expression1: expression2;. If the conditional expression evaluates to true, then expression1 executes. If the conditional expression evaluates to false, then expression2 executes. The following code shows an example of the conditional operator. In the example, the conditional expression checks to see if the intVariable variable is greater than 100. If intVariable is greater than 100, then the text “intVariable is greater than 100” is assigned to the result variable. If intVariable is not greater than 100, then the text “intVariable is less than or equal to 100” is assigned to the result variable. Because intVariable is equal to 150, the conditional statement returns a value of true, the first expression executes, and “intVariable is greater than 100” prints to the screen. var intVariable = 150; var result; (intVariable > 100) ? result = "intVariable is greater than 100" : result = "intVariable is less than or equal to 100"; document.write(result); Next, you will add fields and code to the Wedding Planner form that allow users to select live music and flowers. Conditional operators in associated functions for each field will determine whether to add or subtract the cost of each item. To add fields and code to the Wedding Planner form that allow users to select live music and flowers: 1. Return to the index.html file in your text editor. Using Operators to Build Expressions 2. Add the following elements and fields to the end of the table in the details form. Radio buttons allow users to select whether or not to include live music and flowers. The radio buttons use onchange event handlers to call associated functions for each of the radio buttons. Live music ($500) Yes No Flowers ($400) Yes No 3. Add the following global variables above the calcGuests() function. These variables will be used to determine where the user has selected live music and flowers. var liveMusic = false; var flowers = false; 4. Add the following functions to the end of the script section. The addMusic() function uses a conditional operator to determine whether the liveMusic variable is set to false. If it is, then the liveMusicCost variable is assigned a value of 500. If not, then it is assigned a value of 0. The liveMusicCost variable is then assigned to the totalEstimate variable with an addition assignment operator. The last two statements assign the liveMusic variable a value of true and the value of the totalEstimate variable to the text box in the estimate form. The removeMusic() function uses the exact same syntax as the addMusic() function, except that it assigns a value of -500 to the liveMusicCost variable, which causes the addition assignment expression to subtract the value from the totalEstimate variable. 109 CHAPTER 2 Working with Functions, Data Types, and Operators function addMusic() { (liveMusic == false) ? liveMusicCost = 500 : liveMusicCost = 0; totalEstimate += liveMusicCost; liveMusic = true; document.estimate.cost.value = "$" + totalEstimate; } function removeMusic() { (liveMusic == true) ? liveMusicCost = -500 : liveMusicCost = 0; totalEstimate += liveMusicCost; liveMusic = false; document.estimate.cost.value = "$" + totalEstimate; } 110 5. Add the following addFlowers() and removeFlowers() functions to the end of the script section. These functions are identical to the addMusic() and removeMusic() functions, except they update the total estimate to include flower costs instead of the music cost. function addFlowers() { (flowers == false) ? flowersCost = 400 : flowersCost = 0; totalEstimate += flowersCost; flowers = true; document.estimate.cost.value = "$" + totalEstimate; } function removeFlowers() { (flowers == true) ? flowersCost = -400 : flowersCost = 0; totalEstimate += flowersCost; flowers = false; document.estimate.cost.value = "$" + totalEstimate; } 6. Save the index.html file, and then validate it with the W3C Markup Validation Service at http://validator.w3.org/. Once the file is valid, close it in your text editor and open it in your Web browser. Test the functionality of the Live music and Flowers fields. Figure 2-15 shows how the page appears after adding the Live music and Flowers fields Using Operators to Build Expressions 111 Figure 2-15 Wedding Planner page after adding the Live music and Flowers fields 7. Close your Web browser window and text editor. Logical Operators Logical operators are used for comparing two Boolean operands for equality. For example, a script for an automobile insurance company may need to determine whether a customer is male and under 21 in order to determine the correct insurance quote. As with comparison operators, a Boolean value of true or false is returned after two operands are compared. Table 2-9 lists the JavaScript logical operators. Name Operator Description And && Returns true if both the left operand and right operand return a value of true; otherwise, it returns a value of false Or || Returns true if either the left operand or right operand returns a value of true; if neither operand returns a value of true, then the expression containing the Or || operator returns a value of false Not ! Returns true if an expression is false, and returns false if an expression is true Table 2-9 Logical operators CHAPTER 2 Working with Functions, Data Types, and Operators The Or (||) and the And (&&) operators are binary operators (requiring two operands), whereas the Not (!) operator is a unary operator (requiring a single operand). Logical operators are often used with comparison operators to evaluate expressions, allowing you to combine the results of several expressions into a single statement. For example, the And (&&) operator is used for determining whether two operands return an equivalent value. The operands themselves are often expressions. The following code uses the And operator to compare two separate expressions: 112 var gender = "male"; var age = 17; var riskFactor = gender=="male" && age 4. Add the first function to the script section as follows. This function writes a message to the screen using an argument that will ultimately be passed to it from the calling statement: function printMessage(first_message) { document.write("" + first_message + ""); } 5. Add the second function, which displays a second message, to the end of the script section. In this case, the message (“This message was returned from a function.”) is defined within the function itself. The only purpose of this function is to return the literal string “This message was returned from a function.” to the calling statement. function return_message() { return "This message was returned from a function."; } 6. Add the following script section and function to the document body: /* */ 7. Type the following three statements, which call the functions in the document head. The first statement sends the text string “This message was printed by a function.” This statement does not receive a return value. The second statement assigns the Reinforcement Exercises function call to a variable named return_value but does not send any arguments to the function. The third statement writes the value of the return_value variable to the screen. printMessage("This message was printed by a function."); var return_value = return_message(); document.write(return_value); 8. Save the document as TwoFunctions.html in the Exercises folder for Chapter 2, and then validate it with the W3C Markup Validation Service at validator.w3.org/file-upload. html and fix any errors that it contains. Once the document is valid, close it in your text editor. 9. Open the TwoFunctions.html document in your Web browser. Figure 2-18 shows how the TwoFunctions.html document looks in a Web browser. Figure 2-18 TwoFunctions.html in a Web browser 10. Close your Web browser window. Exercise 2-2 In this exercise, you will create a Web page that uses variables to display information about the five largest islands in the world. 1. Create a new document in your text editor and type the declaration, element, header information, and the element. Use the strict DTD and “Largest Islands” as the content of the element. 123 CHAPTER 2 Working with Functions, Data Types, and Operators 2. Add the following element to the document body: Largest Islands 3. Add the following script section to the end of the document body: /* */ 124 4. In the script section, type the following statements, which declare variables containing the names and sizes of the world’s five largest islands: var var var var var var var var var var 5. island1Name island2Name island3Name island4Name island5Name island1Size island2Size island3Size island4Size island5Size = = = = = = = = = = "Greenland"; "New Guinea"; "Borneo"; "Madagascar"; "Baffin"; 2175600; 790000; 737000; 587000; 507000; Next, add the following statements to the end of the script section that print the values stored in each of the variables you declared and initialized in the last step: document.write("The largest island in the world is " + island1Name + " with " + island1Size + " miles."); document.write("The second largest island in the world is " + island2Name + " with " + island2Size + " miles."); document.write("The third largest island in the world is " + island3Name + " with " + island3Size + " miles."); document.write("The fourth largest island in the world is " + island4Name + " with " + island4Size + " miles."); document.write("The fifth largest island in the world is " + island5Name + " with " + island5Size + " miles."); 6. Save the document as LargestIslands.html in the Exercises folder for Chapter 2, and then open it in your Web browser and examine how the elements are rendered. 7. Close your Web browser window, but leave the LargestIslands.html document open in your text editor. Reinforcement Exercises Exercise 2-3 In this exercise, you will create a script that uses assignment operators. 1. Create a new document in your text editor. 2. Type the declaration, element, header information, and the element. Use the strict DTD and “Assignment Operators” as the content of the element. 3. Add the following element to the document body: Assignment Operators 4. Add the following script section to the document body: /* */ 5. Type the following statements in the script section. These statements perform several compound assignment operations on a variable named dataVar. After each assignment operation, the result is printed. var dataVar = "Don "; dataVar += "Gosselin"; document.writeln("Variable after addition assignment = " + dataVar + ""); dataVar = 70; dataVar += 30; document.writeln("Variable after addition assignment = " + dataVar + ""); dataVar -= 50; document.writeln("Variable after subtraction assignment = " + dataVar + ""); dataVar /= 10; document.writeln("Variable after division assignment = " + dataVar + ""); dataVar *= 9; document.writeln("Variable after multiplication assignment = " + dataVar + ""); dataVar %= 200; document.writeln("Variable after modulus assignment = " + dataVar + ""); 6. Save the document as AssignmentOperators.html in the Exercises folder for Chapter 2. 125 CHAPTER 2 126 Working with Functions, Data Types, and Operators 7. Use the W3C Markup Validation Service to validate the AssignmentOperators.html document and fix any errors that the document contains. Once the document is valid, close it in your text editor and then open it in your Web browser and examine how the elements are rendered. 8. Close your Web browser window. Exercise 2-4 In this exercise, you will create a script that uses comparison operators. 1. Create a new document in your text editor. 2. Type the declaration, element, header information, and the element. Use the strict DTD and “Comparison Operators” as the content of the element. 3. Add the following element to the document body: Comparison Operators 4. Add the following script section and paragraph elements to the document body: /* */ 5. Add the following statements to the script section that perform various comparison operations on two variables. Notice that the first comparison is performed using the conditional operator. var conditionalValue; var value1 = "Don"; var value2 = "Dave"; value1 == value2 ? document.write( "value1 equal to value2: true") : document.write( "value1 equal to value2: false"); value1 = 37; value2 = 26; conditionalValue = value1 == value2; document.write("value1 equal to value2: " + conditionalValue + ""); conditionalValue = value1 != value2; document.write("value1 not equal to value2: " Reinforcement Exercises + conditionalValue + ""); conditionalValue = value1 > value2; document.write("value1 greater than value2: " + conditionalValue + ""); conditionalValue = value1 < value2; document.write("value1 less than value2: " + conditionalValue + ""); conditionalValue = value1 >= value2; document.write("value1 greater than or equal to value2: " + conditionalValue + ""); conditionalValue = value1 128 5. Add the following statements to the script section that use logical operators on two variables: var orderPlaced = true; var orderFilled = false; document.write("Order has been placed: " + orderPlaced + ""); document.write("Order has been filled: " + orderFilled + ""); var orderComplete = orderPlaced && orderFilled; document.write("Order has been placed and filled: " + orderComplete + ""); 6. Save the document as OrderFulfillment.html in the Exercises folder for Chapter 2. 7. Use the W3C Markup Validation Service to validate the OrderFulfillment.html document and fix any errors that the document contains. Once the document is valid, close it in your text editor and then open it in your Web browser and examine how the elements are rendered. 8. Close your Web browser window. Exercise 2-6 In this exercise, you will create a script that displays a portion of a review for a production of the opera Pagliacci, performed by an opera company called Pine Knoll Productions. The review will be rendered using document.write() statements that combine text strings with escape characters. Note that you can create the same document more easily using only XHTML elements. The purpose of this exercise is to demonstrate how text strings can be combined with escape characters. 1. Create a new document in your text editor. 2. Type the declaration, element, header information, and the element. Use the strict DTD and “Pine Knoll Productions” as the content of the element. Reinforcement Exercises 3. Add the following style section to the document head: body { font-family: 'Trebuchet MS', Arial, Helvetica, sans-serif } 4. Add the following script section and paragraph elements to the document body: 129 /* */ 5. Add to the script section the following document.write() statements, which contain combinations of text, elements, and escape characters: document.write("Pine...
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

This question has not been answered.

Create a free account to get help with this and any other question!

Similar Content

Related Tags