chapter tw o functions, var operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add...

30
In th Doin Java math calle calcu comp math oper temp temp reuse or on Java his chapter A discuss and usag An overv used by comparis How to c An expla ng the Ma Script and hematical a d on to calc ulations, an plete these hematical a rators are porarily sto porary figur e code snip n many pag aScript: you will fin sion of the ge. view of the JavaScript son statem create and nation of v ath other prog and logical t culate grad nd determin tasks, pro and logical c used for th red for futu res. JavaSc ppets to car ges through Ch Functio nd: need for fu various sp to form ma ents. populate va variable and ramming la tasks. With de point ave ne how muc gramming concepts. S is task. Cal ure use wit cript functio rry out repe hout a web hapter Tw ons, Var unctions an ecial punct athematica ariables wit d function s anguages a hin the cont erages, pro ch shipping languages Special pun lculated va hin a script ons allow p etitive calcu b site. wo riables & nd example uation char l, text, ass th data. scope. are frequen text of web ovide month g tax to add must have ctuation ch lues freque t; variables programme ulations or & Operat s of their b racters, or ignment, lo tly used to b pages, Jav hly mortga d to an ord e a way to c haracters, k ently need t s are conta ers to easily tasks on th tors basic syntax operators, ogical, and complete vaScript ca ge paymen er. To communica known as to be ainers for th y use and he same pa x n be nt ate hese age

Upload: others

Post on 11-Mar-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

In th

DoinJava

math

calle

calcu

comp

math

oper

temp

temp

reuse

or on

Java

his chapter

A discuss

and usag

An overv

used by

comparis

How to c

An expla

ng the MaScript and

hematical a

d on to calc

ulations, an

plete these

hematical a

rators are

porarily sto

porary figur

e code snip

n many pag

aScript:

you will fin

sion of the

ge.

view of the

JavaScript

son statem

create and

nation of v

ath other prog

and logical t

culate grad

nd determin

tasks, pro

and logical c

used for th

red for futu

res. JavaSc

ppets to car

ges through

Ch Functio

nd:

need for fu

various sp

to form ma

ents.

populate va

variable and

ramming la

tasks. With

de point ave

ne how muc

gramming

concepts. S

is task. Cal

ure use wit

cript functio

rry out repe

hout a web

hapter Twons, Var

unctions an

ecial punct

athematica

ariables wit

d function s

anguages a

hin the cont

erages, pro

ch shipping

languages

Special pun

lculated va

hin a script

ons allow p

etitive calcu

b site.

wo riables &

nd example

uation char

l, text, ass

th data.

scope.

are frequen

text of web

ovide month

g tax to add

must have

ctuation ch

lues freque

t; variables

programme

ulations or

& Operat

s of their b

racters, or

ignment, lo

tly used to

b pages, Jav

hly mortga

d to an ord

e a way to c

haracters, k

ently need t

s are conta

ers to easily

tasks on th

tors

basic syntax

operators,

ogical, and

complete

vaScript ca

ge paymen

er. To

communica

known as

to be

ainers for th

y use and

he same pa

x

n be

nt

ate

hese

age

Page 2: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

32

Functions Functions were introduced in the previous chapter in order to illustrate best

practices in separating JavaScript code from HTML markup. We now cycle back for

a more formal introduction. A function is a named section of code that is created in

order to be called at a later time in the application. The function does not execute

until it is called, but the function may be called many tmes within a single scriptʼs

execution. Functions allow programmers to create very efficient scripts; repetitive

steps in code can be moved to a function and thus eliminate redundant typing and

create scripts that both run more quickly and are easier to update and maintain.

Writing functions is key to achieve code separation: storing the markup,

presentation, and interactivity in completely separate files.

At first it will seem frustrating to bother with creating functions for just one or two

lines of code, and that the results are not worth the effort. Learning how to create

re-usable bits of code is necessary to become a fluent programmer, however.

Using functions allows code to be reused, which in turn:

Makes page file sizes smaller – the fewer the number of typed characters,

the smaller the file size. The smaller the file size the faster the page

downloads.

Makes scripts execute faster – once a function is read into the script engineʼs

memory it is held there and the lines do not have to be interpreted from

scratch each time the function is executed.

Makes scripts faster to update – changing a script command within a single

function that is called in multiple places on multiple pages is much more

efficient than having to make the same change throughout many different

files within an application.

Basic Placement and Syntax The basic function syntax can be diagrammed as follows:

Page 3: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

33

function name_of_function (argument1,argument2, …)

{

//JavaScript commands which will execute each time the function is called

return output1;

};

A function is created by using the keyword function followed by the desired

function name. All identifiers (programmer-selected names) must follow some

specific naming conventions and should follow a few others. Every function and

variable name in JavaScript must:

Start with a letter or the underscore character or the dollar sign character

Contain only letters, numbers, the underscore character, or the dollar sign

Avoid the use of JavaScript reserved keywords, like var, Date, window,

etc. Reserved keywords are those words already meaningful assigned as

object, property, method, function, or operator names.

Every function and variable name in JavaScript should:

Meaningfully represent the data that it contains

Use a consistent capitalization scheme

Be reasonably short and easy to type

Once the function name is typed, a set of parentheses is included and within these

are placeholder names for any data that will be passed into the function. The

names inside of the parentheses are referred to as the function arguments or

parameters – there should be one argument for each of the pieces of information

that needs to be sent into the function in order for it to run. The lines of code that

should execute each time a function is run are enclosed by braces. If the function

is designed to calculate a value, the return keyword is used to identify that value.

Page 4: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

34

Note that “function” and “return” in the syntax shown are JavaScript keywords.

They must be typed exactly as shown in all lowercase in order for the script to

execute properly. The name of the function is specified by the developer, and can

contain mixed case letters. The arguments are placeholders for bits of data used in

calculations in the function. These arguments are named at the discretion of the

programmer as well, but again must follow good naming conventions. There is no

set number of parameters required for a proper function – programmers will need

to determine if their application needs inputs and if so, how many. If there are no

input values needed then the parentheses after the function name are simply left

empty. A function that does not accept input values would look like:

function name_of_function()

{

//JavaScript commands which will execute each time the function is called

return output1;

};

To put some specifics behind the syntax, suppose we wanted to create a function

that would return a reference to a particular object on a page when provided with

the id attributeʼs value. This particular function is a favorite of mine, since it then

negates the need to type window.document.getElementById excessively

throughout the rest of the script. Consider the following:

/*============================ name: $ desc: returns a reference to an object with a specified id arguments: - theId: text string that is the id attribute value of the desired object return: - object referenced by theId =============================*/ function $(theId) { return window.document.getElementById(theId); };

Page 5: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

35

Functions do not require a return statement in JavaScript. Some functions are

simply used to bundle up related lines of code. Consider a function that is called to

highlight a textbox on a form that contains an invalid value. The function should

clear any previously entered text, change the background color of the textbox, and

place the insertion point inside of the textbox. No return value is necessary. In

order to work, the function must know the id value of the textbox in question. Note

in this example, we are making use of the $ function created in the previous

example to replace window.document.getElementById().

/*============================ name: showError desc: deletes invalid text, highlights textbox, and places insertion point arguments: - theId: text string that is the id attribute value of the desired textbox return: - none =============================*/ function showError(theId) { //delete invalid text $(theId).value = ""; //highlight textbox $(theId).style.backgroundColor = "yellow"; //place insertion point in textbox $(theId).focus(); };

Not every function needs to accept input parameters. Suppose we wanted a

function that would display a thank you message after users submitted a form and

then navigate to the main page. There would be no input values to speak of, and

no output value to return, either. The function could look like:

/*============================ name: formThanks desc: displays thank you alert and navigates to main page arguments: - none return: - none

Page 6: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

36

=============================*/ function formThanks() { //show thank you message window.alert(“Thanks for your feedback!”); //return to main page window.location.href = “main.html”; };

Function Placement Technically, JavaScript functions can be placed anywhere that regular JavaScript

code snippets can: in the head or body section of a page; in an external JavaScript

file; functions can even be completely coded after an event handler attribute inside

of an HTML tag. Best practices dictate that developers should work towards a goal

of code separation – having all JavaScript stored in separate .js files connected to

HTML pages only through a <script> tag with an appropriate src attribute value.

This script tag is often placed at the end of the body of the HTML document.

While this may seem strange, remember that the web browser parsing the HTML

will read and execute line by line from the top of the code to the bottom. Placing

the script tag at the bottom of the body will ensure that all of the HTML objects

referenced in JavaScript will be loaded and available for manipulation when the

script engine starts.

Calling Functions Functions are called, or executed, by referencing their function name and

supplying any input values, if necessary, for the functionʼs arguments. A function

call can be placed as a line of code in a JavaScript section on the page, after an

HTML event handler, or even from within the code for another function as

demonstrated by the showError function above. Weʼll practice functions, but to

make really useful examples we need a little more knowledge about how to make

JavaScript calculate and store data first using operators and variables.

Page 7: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

37

Operators Operators can be divided into five categories: mathematical operators, assignment

operators, text operators, comparison operators, and logical operators. Individuals

who have used spreadsheet programs to create functions are likely already familiar

with a number of the mathematical operators. See the table of operators below for

some of the more common JavaScript operators of each type:

Operator Description

Mathem

atical

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus – returns the whole number remainder of a division

problem. The modulus of 23 and 5 is 4, since 23/5 = 4 with a

remainder of 3.

Assignment

= Basic assignment – stores value on right of assignment operator in

container on left in statements like:

myNum = 14;

+=

Add and assign – adds value on right of the assignment operator to

the original value in the container on the right and stores the result

back in the container. The statement myVariable += myValue is a

shorthand way to express myVariable = myVariable + myValue.

-=

Subtract and assign – subtracts value on the right of the operator

from the value in the container on the left and stores result in

container on the left. The statement myVariable -= myValue is a

shorthand way to express myVariable = myVariable – myValue.

Page 8: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

38

*=

Multiply and assign – multiplies value on right of the assignment

operator with value in container on left and stores the result back in

the container on the left. The statement myVariable *= myValue is a

shorthand way to express myVariable = myVariable * myValue.

/=

Divide and assign – divides the value in the container on the left of

the assignment operator by the value on the left and stores the result

back in the container on the left. The statement myVariable /=

myValue is a shorthand way to express myVariable = myVariable /

myValue.

%=

Modulus and assign – calculates the modulus of the value in the

container on the left of the assignment operator with the value on

the right and stores the result back in the container on the left. The

statement myVariable %= myValue is a shorthand way to express

myVariable = myVariable % myValue.

++ Increment – adds one to the value in the container modified by the

operator. The statement myVariable++ is a shorthand way to

express myVariable = myVariable + 1.

-- Decrement – subtracts one from the value in the container modified

by the operator. The statement myVariable-- is a shorthand way to

express myVariable = myVariable – 1. Text

+ Concatenate – combines two separate text strings into a single

string.

+=

Concatenate and assign – combines the text string contained on

the left of the assignment operator with the new text string on the

right and stores the resulting string back in the container on the left.

The expression myString += mySecondString is a shorthand way of

coding myString = myString + mySecondString.

Page 9: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

39

Comparison

== Is equal to – the compared values must match, although their data

types might be different. The statement 2 == “2” is true.

=== Is identical to – both the value and the data types compared must

match. The statement 2 === “2” is false.

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

!= Is not equal to

!=== Is not identical to

Logical

! Not (aka inverse) – changes a Boolean value to its opposite; from

true to false or from false to true.

&& And – returns true only if both values connected by the operator are

true.

|| Or – returns true if any one or all of the values connected by the

operator are true.

Table 1: JavaScript Operators

Order of Operations When interpreting mathematical statements, the JavaScript script engine will

always apply the order of operations (also known as the order of precedence) to

determine which part of the expression to complete first, second, and so on. This is

the mathematically correct thing to do, of course, but can occasionally cause

surprises for programmers who have temporarily replaced the order of operations

from the top of their mental indices.

Page 10: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

40

Essentially, the order of operations states that

expressions contained within parentheses will be

calculated first, then any exponents, then multiplication

and division, and finally any addition or subtraction.

(You all knew that, right?!) Note that in JavaScript there

is no exponent operator. In order to raise a number to a

certain power the Math.exp(number, power) method is

used. In order to calculate 64 raised to the fifth power, for example, you would

write a statement like:

myResult = Math.exp(64, 5);

JavaScript also adds an additional complication to the traditional order of

operations in the form of the logical and comparison operators. The (still not

complete, but disregarding unnecessary complications)

more complete order of operations for JavaScript looks

like what is shown in the Updated Ord. of Ops table to

the right. When crafting expressions for the script engine

to evaluate, be sure to enclose those portions that must

be calculated first in parentheses. For example, if you

wanted an average of five quiz scores calculated you

would not get the results you wanted from the

JavaScript engine by typing:

window.alert( 16 + 20 + 15 + 17 + 17 / 5 )

In the above line, the script engine would first determine

the result of 17 / 5 and then complete the addition,

resulting in a value of 71.4.

The correct way of directing the script engine to complete the desired calculation

would be:

TRADITIONAL ORD. OF OPS

1. Parentheses

2. Exponents

3. Multiplication & Division

4. Addition & Subtraction

UPDATED ORD. OF OPS

1. Parentheses

2. Logical NOT (!)

3. Multiplication, Division,

& Modulus

4. Addition & Subtraction

5. Less than & greater

than

6. Equality & Inequality

7. Logical AND (&&)

Page 11: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

41

window.alert( (16 + 20 + 15 + 17 + 17) / 5 )

In this case, the script engine would first find the sum of the five scores, and then

divide the result by five resulting in a value of 17. Note in both of these examples

that the spaces between numbers and operators are strictly for aesthetic value.

Spaces may make expressions easier to read to human programmers, but they

make no difference to the script engine calculations.

Variables In programming languages, variables are used to create temporary storage for

data used during code execution. This data typically is either numerical, Boolean,

string, or object data (although the absence of data is also tracked as null or

undefined). Storing data in variables allows for convenient reference to a particular

fact or piece of data throughout a script without having to repeatedly type in

calculated expressions. Using variables enhances code efficiency and, when

properly named, code readability.

Declaring a variable in JavaScript is straightforward. Type the keyword var

followed by an appropriate variable name and then, optionally, assign a value. The

basic syntax looks like:

var myVariableName = myValue;

The var keyword is only used the first time the variable is created. Thereafter, to

use the variable simply use the variable name. Creating and using a JavaScript

variable might look something like:

//Create variable and assign an initial value var myName = window.document.frmLogin.txtUserName.value; window.alert("Welcome, " + myName); //Put a new value into an existing variable myName = window.document.frmUpdateAcct.txtNewUserName.value; window.alert("Your new account name is: " + myName);

Page 12: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

42

The data stored in a variable, as noted above, may be numerical, a Boolean value,

a text string, or another JavaScript object. Variables that have never been assigned

a value return a value of undefined.

JavaScript is not a strongly typed language like Java or Visual Basic. In a strongly

typed language, the type of data to be stored in a variable must be indicated at the

time the variable is declared and only that type of data may be stored in that

variable for the duration of the variable. JavaScript is a loosely typed language,

meaning that programmers do not indicate the data type to be stored in the

variable when it is declared and that any (and all) of the data types may be stored

in that variable throughout its duration in the code.

A loosely typed language obviously provides programmers more flexibility in how

variables are used, but is wasteful of memory resources. Indicating a data type in

a strongly typed language will mean that the computer will only reserve the

maximum amount of storage space needed for that type of data in memory. If a

variable is declared to store only Boolean data, then only one bit of RAM is needed

for that variable. In loosely typed languages the maximum storage needed for the

largest type of data is reserved for each variable that is created during the

program execution. Since JavaScript is designed for creating lightweight, on-the-fly

page interactivity within the browser this isnʼt a serious setback.

Storing data in variables can be done directly – typing in the number, string,

Boolean value or object directly after an assignment operator – or indirectly –

creating an expression for the script engine to calculate or referencing data from a

form element. Consider the following example:

1. Open the chap02ex01.htm file in your text editor and familiarize yourself

with the HTML code. Be sure to note the various span tags, id attributes,

and form elements that make up this file.

Page 13: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

43

2. Begin by adding the following code just before the closing body tag to link

the HTML file to the external JavaScript file: <script language="javascript" type="text/javascript" src="chap02ex01code.js"> </script>

3. Open the chap02ex01code.js file in your text editor. The file contains largely

comments at this point to identify where youʼll be adding code later. The

script that is here defines what will happen once the onload event for the

window object is complete. This is where the majority of our function calls

will go.

4. Start by defining some variables inside of the window.onload event, as

shown: //====== use the window.onload event to call the various functions window.onload = function() { //create variable definitions var myFirstNum = 23; var mySecondNum = 5; var myFourthResult; var myFirstString = "Some text stored in a variable?"; var mySecondString = "Yee haw!"; var myCity = "Springfield"; var myZip = 97000; var myCars = 3;

This is the first time we are defining the variables so they all must start with

the var keyword. Notice that there are no data types specified; JavaScript

uses contextual clues to determine what kind of data is stored in the

variable. Numerical data is typed directly, without any enclosing characters

while text strings are enclosed inside of quotation marks. Each line ends

with the semi-colon to indicate the end of the statement.

These variables are created inside the onload function and thus are local to

that function and unavailable for direct references outside of this function.

5. Scroll back up towards the top of the file and add a function that weʼll use

repeatedly to reduce the number of times we have to type

Page 14: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

44

window.document.getElementById: /* Name: chap02ex01code.js Desc: functions used in chap02ex01.htm demonstrate basic use of operators, variables, and functions Date: Created by: */ /* name: $ desc: gets an object referred to by its unique id value inputs: -theId: textstring representing the id attribute value of the object return: -the object with the designated id */ function $(theId) { return window.document.getElementById(theId); }

Notice that we typed in a relatively extensive comment to document the

name, purpose, input parameters and returned result of our function. While

it may feel tedious to type in more text in comments than in the function,

this type of consistent documentation is what makes code most valuable in

the long run.

The function itself requires one piece of information in order to work and

returns an object. Having this function in our script file means that instead

of writing something like: window.document.getElementById(“txtPrice”).value = 7.99; we can shorten it to simply: $(“txtPrice”).value = 7.99;

6. Create your next function – the first function in the working with numbers

section: //============== calculate results for the "working with numbers" section ====== /* name: getFirstResult desc: completes the first result calculation inputs:

Page 15: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

45

-theFirstNum: the first number -theSecondNum: the second number return: -calculation shown on page */ function getFirstResult(theFirstNum, theSecondNum) { return theFirstNum + theSecondNum / 2; }

7. Call both of these two new functions from inside the window.onload event: //call the number-related functions as part of assignment statements. Pass the local variables in as parameter values $("spnFirstResult").innerHTML = getFirstResult(myFirstNum, mySecondNum);

The $ at the beginning of the assignment statement calls our very first

function. The function is passed “spnFirstResult” in place of theId

parameter. The function returns a reference to the span element within the

HTML document that has id=”spnFirstResult”. Once we have the object, we

can use any of its properties that are useful. In this case, the innerHTML

property which represents the entire contents between the opening and

closing <span> tags is what is needed. We assign the value returned by the

getFirstResult function to the innerHTML property, passing in the specific

data stored in the myFirstNum and mySecondNum variables to the function.

8. Save your changes and test the results on the chap02ex01.htm. You should

see a burgundy calculated value (25.5) appear to the right of the

myFirstResult line.

9. Return to the JavaScript file to repeat this process to create the

getSecondResult, getThirdResult, and getFourth Result functions just below

the definition for the getFirstResult function. (Make sure that you start

outside of the braces {} for any other function!): /* name: getSecondResult desc: completes the second result calculation inputs: -theFirstNum: the first number -theSecondNum: the second number return:

Page 16: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

46

-calculation shown on page */ function getSecondResult(theFirstNum, theSecondNum) { return (theFirstNum + theSecondNum) / 2; } /* name: getThirdResult desc: completes the third result calculation inputs: -theFirstNum: the first number -theSecondNum: the second number return: -calculation shown on page */ function getThirdResult(theFirstNum, theSecondNum) { return theFirstNum % theSecondNum; } /* name: getFourthResult desc: completes the fourth result calculation inputs: -theFirstNum: the first number -theSecondNum: the second number return: -calculation shown on page */ function getFourthResult(theFirstNum, theSecondNum) { return theFirstNum + theFirstNum % theSecondNum; }

10. Call each of these functions from inside of the window.onload event: //call the number-related functions as part of assignment statements. Pass the local variables in as parameter values $("spnFirstResult").innerHTML = getFirstResult(myFirstNum, mySecondNum); $("spnSecondResult").innerHTML = getSecondResult(myFirstNum, mySecondNum); $("spnThirdResult").innerHTML = getThirdResult(myFirstNum, mySecondNum); //update the value in the myFourthResult variable by calling the function myFourthResult = getFourthResult(myFirstNum, mySecondNum); $("spnFourthResult").innerHTML = myFourthResult; //update the value in the myFourth Result variable using the "multiply AND assign" operator myFourthResult *= 2;

Page 17: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

47

$("spnFourthResult2").innerHTML = myFourthResult;

11. Save your changes and check your work in the browser window periodically

to isolate and correct any typos as they occur. Verify the math results

independently on scratch paper and consider how the order of operations

affects each outcome.

12. Move on to working with text and the concatenation operator in the next

section. Create the getFifthResult and getSixthResult functions as follows: //============= calculate results for the "working with text" section /* name: getFifthResult desc: completes the fifth result calculation inputs: -theFirstString: the first string of text -theSecondString: the second string of text return: -calculation shown on page */ function getFifthResult(theFirstString, theSecondString) { return theFirstString + theSecondString; } /* name: getSixthResult desc: completes the sixth result calculation inputs: -theFirstString: the first string of text -theSecondString: the second string of text return: -calculation shown on page */ function getSixthResult(theFirstString, theSecondString) { return theFirstString + " " + theSecondString; }

13. Call these two functions from inside of the window.onload event: //call the text-related functions as part of assignment statements. Pass the local variables in as parameter values $("spnFifthResult").innerHTML = getFifthResult(myFirstString, mySecondString); $("spnSixthResult").innerHTML = getSixthResult(myFirstString, mySecondString);

Page 18: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

48

14. Save your changes and check your work in the browser window periodically

to isolate and correct any typos as they occur.

15. Create the working with logic functions as shown. These functions work with

the logical and comparison operators to return values of true or false (well,

in most cases!): //============ calculate results for the "working with logic" section /* name: getSeventhResult desc: completes the seventh result calculation inputs: -theCityString: the string of text representing the chosen city -theCarsInteger: the integer representing the number of cars return: -Boolean value indicating whether the statement shown evaluates to 'true' or 'false' */ function getSeventhResult(theCityString, theCarsInteger) { return theCityString == "Springfield" && theCarsInteger > 2; } /* name: getEighthResult desc: completes the eighth result calculation inputs: -theCityString: the string of text representing the chosen city return: -Boolean value indicating whether the statement shown evaluates to 'true' or 'false' */ function getEighthResult(theCityString) { return theCityString = "Bend"; } /* name: getNinthResult desc: completes the ninth result calculation inputs: -theCars: the integer representing the number of cars -theZip: the integer representing the zip code return: -Boolean value indicating whether the statement shown evaluates to 'true' or 'false' */ function getNinthResult(theCars, theZip) { return theCars > 3 || theZip < 95000; }

Page 19: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

49

/* name: getTenthResult desc: completes the tenth result calculation inputs: -theZip: the integer representing the zip code -theCars: the integer representing the number of cars -theCity: the text string representing the city name return: -Boolean value indicating whether the statement shown evaluates to 'true' or 'false' */ function getTenthResult(theZip, theCars, theCity) { return (theZip >= 97000 || theCars == 0) && (theCity == "Springfield"); }

16. Call the seventh, eighth, ninth, and tenth functions from inside of the

window.onload event: //call the text-related functions as part of assignment statements. Pass the local variables in as parameter values $("spnSeventhResult").innerHTML = getSeventhResult(myCity, myCars); $("spnEighthResult").innerHTML = getEighthResult(myCity); $("spnNinthResult").innerHTML = getNinthResult(myCars, myZip); $("spnTenthResult").innerHTML = getTenthResult(myZip, myCars, myCity);

17. Save your changes and test in the browser window. Were you surprised by

the results of the getEighthFunction? Note that this function uses the

assignment operator rather than one of the comparison operators. This is a

key mistake made when working with comparisons. The = operator does

NOT do the same thing as the == or === operators.

18. Finish with something just a bit different. Create a function to report the

area of a rectangle with the length and width textboxes are completed on

the form. //======================= calculate the area /* name: getArea desc: calculates the area of a rectangle inputs: -none return: -none */ function getArea()

Page 20: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

50

{ //get data from the form var myWidth = $("txtWidth").value; var myLength = $("txtLength").value; var myArea; //calculate and output result myArea = myWidth * myLength; window.alert(myArea); }

19. In this case, we donʼt want the function to execute as soon as the onload

event for the window is completed. Instead, we want to associate the

function with the onclick event for the btnArea button. Add the following line

of code to the window.onload event: //assign the re-usable functions to event handlers for each form button $("btnArea").onclick = getArea;

20. Test the effect of this function and event association from the browser

window. Calculating the distance traveled and the item subtotal is similar.

Create the functions: //================= calculate the distance /* name: getDistance desc: calculates the distance traveled if traveling at a set speed for a set time inputs: -none return: -none */ function getDistance() { //get data from the form var mySpeed = $("txtSpeed").value; var myTime = $("txtTime").value; //calculate and output result var theDistance = mySpeed * myTime; window.alert(theDistance); } //================= calculate the item subtotal /* name: getSubTotal

Page 21: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

51

desc: calculates the item subtotal for purchasing a certain number of items at a set price inputs: -none return: -none */ function getSubTotal() { //get data from the form var myQuantity = $("txtQuantity").value; var myPrice = $("txtPrice").value; //calculate and output result var theSubTotal = myQuantity * myPrice; window.alert(theSubTotal); }

21. And then associate the function with the onclick event for the btnDist button

inside of the window.onload event function: //assign the re-usable functions to event handlers for each form button $("btnArea").onclick = getArea; $("btnDist").onclick = getDistance; $("btnPrice").onclick = getSubTotal;

22. Test the effect of this function and event association from the browser

window. All three of these functions are very similar, but cannot be used

interchangeably because the functions make a direct reference to specific

form elements from inside of the function. Make a better function that is

more re-usable by creating parameters as placeholders for the specific

values: //=================== calculate the product of two numbers /* name: getProduct desc: calculates the product of two numbers inputs: -theFirstNum: the first number -theSecondNum: the second number return: -theProduct: the product of the first and second numbers */ function getProduct(theFirstNum, theSecondNum) { var theProduct = theFirstNum * theSecondNum;

Page 22: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

52

window.alert(theProduct); }

23. In order to assign a function that requires parameters to an objectʼs event

property, it must be wrapped up inside of an anonymous function, as

follows: //assign the re-usable functions to event handlers for each form button $("btnArea").onclick = getArea; $("btnDist").onclick = getDistance; $("btnPrice").onclick = function() { //call a more generic function, passing in the form values at the time of the function call getProduct($("txtPrice").value, $("txtQuantity").value); }

24. Save all of your changes and test the effects in the browser window. To

challenge your understanding, see if you can change the code so that the

btnDist and btnArea buttons also use the more generic getProduct function.

Function and Variable Scope One last issue to consider when using JavaScript operators, variables and functions

is that of scope. The scope of a variable or a function is the range within the

application that a particular variable or function can be used. Full-blown, object

oriented programming languages like C, Java, or Visual Basic have a much more

complex range of scope possibilities and more guidelines surrounding variable use.

In JavaScript, variable scope is pretty straightforward. Variables may be local (only

available inside the function in which they were first declared) or they may be

global (available to all of the other coding on the page, inside and outside of

functions).

Creating Local Variables Any variable defined within a function using the var keyward in front of the variable

name is considered to be a local variable. That variable (and the values stored

within it) will only be available for use within the boundaries of that function.

Page 23: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

53

Attempting to access a local variable by name outside of the function will result in

an “object unknown” error.

Creating Global Variables Global variables, those variables that are available to any script on the page either

inside or outside of functions, can be created one of two ways:

1. By defining a variable using the var keyword outside of any particular

function

=OR=

2. By defining a variable inside of a function without using the var keyword.

When using global variables, programmers must be careful to keep in mind the

order of the code execution so that they are aware when a value is first stored in

the global variable and when that value changes. Generally speaking, global

variables are avoided whenever possible to avoid any possible naming conflicts

when integrating JavaScript code from multiple programmers/projects into a single

application.

Function Scope Functions have the same concept of scope applied to them. It is possible to nest

one function definition inside of another. The nested function would then have a

local scope; it could only be read and executed from inside the parent function.

The only way to create a function with global scope is to not nest it inside of any

other function. So far, all of the coding examples using functions have

demonstrated global functions.

Generally speaking, function scope is used to prevent conflicts when scripts from

multiple sources are combined onto a single page. It is possible that two

programmers creating two different scripts might have inadvertently used identical

function or variable names. Trying to combine both efforts onto a single page

Page 24: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

54

would then result in conflicts. Nesting the code for each separate script effort inside

of a “wrapping” function would ensure that the scope of the functions and variables

inside of those code efforts would remain local and would not override one

another.

When Things Go Wrong Enclosing code into functions is a worthwhile endeavor for reasons laid out earlier

in the chapter. However, tracking down specific erros in a page that makes heavy

use of functions can be tricky. The script engine will report the error on the line

which called the function rather than pointing out the exact line in the function that

contains the real error. A few common causes of consternation and debugging tips

are listed below.

JavaScript is a case-sensitive language.

This is a rehash of the first suggest from the last chapter, but it bears

reapeating. If a variable is declared as myFirstName then trying to call the

data stored in that later by myfirstname will only result in “object unknown”

type errors. Similarly if a function is declared as doGreeting() then the letter

“G” must be capitalized in any future successful calls to that function.

Concatenation comes from context.

The JavaScript addition operator is the same as the JavaScript concatenation

operator. JavaScript variables are loosely-typed; any variable could contain

any of the data types (numerical, string, Boolean, or object). This means

that an expression like myGuess = myFirst + mySecond could either result

in JavaScript combining the text characters stored inside of the myFirst and

mySecond variables or it could add up the numerical values contained by

those variables.

Page 25: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

55

The script engine uses context clues to determine which action is

appropriate. If the data in the variable is clearly text (the data was enclosed

in quotes when stored in the variable, the data in the element came from a

textboxʼs value, etc.) then the script engine will always try to concatenate.

When the data is clearly numerical then the script engine will always try to

add. If the script engine is guessing incorrectly for your desired results you

can force the correct behavior.

If JavaScript is treating your string data lake numerical data you can use the

toString() method build into JavaScript numerical objects. Modify our

example to force the script engine to deal with variable values as string data

would look like:

myGuess = myFirst.toString() + mySecond.toString();

If JavaScript is treating your numerical data like string data the quickest fix

is to multiply by 1. The multiplication character has no application to string

data in JavaScript, so any variable multiplied by 1 will return a numerical

result. This solution would look like:

myGuess = myFirst * 1 + mySecond * 1;

Only use the end of line character at the end of a complete JavaScript

statement

The semi-colon, the end of line character, indicates that the script engine

has reached the end of a command and should move on to the next

command as separate from the code that precedes the semi-colon. Placing

the semi-colon after declaring the name of a function but before the actual

braces containing the function commands separates those commands from

Page 26: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

56

the function name. Thus a portion of script that looks like:

function doGreeting();

{

var myName = window.prompt("Halt! Who goes there?");

window.alert("Good afternoon, " + myName);

}

will not be executable. The script engine would call the doGreeting()

function, but nothing would happen since the commands inside the braces

would not be interpreted as part of the function.

Become familiar with reserved keywords

It is all too easy to inadvertently use a reserved keyword as a variable or

function name. Date, Math, link, and window tend to be particularly used

and abused since they are such common words (but also existing JavaScript

objects). A quick Internet search for the phrase “JavaScript reserved

keywords” should net many comprehensive references. Programmers can

also almost ensure they avoid reserved words by using some sort of prefix

naming scheme. In the chapter, for example, all function names started

with the prefix “get” and all variable names started with the prefix “my”,

while parameter names began with “the”.

Keep a careful eye on punctuation pairs

A missing closing parenthesis or brace will quickly put the kibosh on the

smooth execution of code and can be tricky to hunt down. Help mitigate this

problem by coding complete pairs of punctuation at a time; type the closing

brace for a function as soon as you type the opening brace. A good code

editor can help detect the problem after it happens. Select a code editor that

color codes the text inside of parentheses and braces, provides outline

Page 27: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

57

collapsing and expanding based upon opening and closing parentheses and

braces, and/or highlights pairs of parentheses based upon selecting the

opening or closing punctuation character.

Use comment characters wisely to isolate errors

As noted earlier, script engines report errors with functions on the line that

calls the function, not on the line inside the function that is actually

“broken”. This tells the programmer that there is a problem with the

function, but not too much else about precisely where the problem might be

or what it is. Use your comment characters to hide all of the code in the

function to see if a simple window.alert() script will work to confirm the

function call. Then, gradually uncomment portions of the function code to

determine which line is the actual culprit.

Page 28: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

58

Chapter Review 1. Write an example of how to create a local variable named myAge that stores

a value of 29.

2. Write an example of how to create a local variable named myName that

stores your name as its value.

3. What are reserved keywords?

4. List a URL where you could find a relatively comprehensive list of JavaScript

keywords.

5. What are some guidelines to remember when naming variables?

6. What would be the result stored in myVal after each line of code has

finished executing? Assume that the script commands execute in the order

provided, and that values carry over into the next step. Begin with the

following lines:

var myNum = 9; var myOtherNum = 2

a. myVal = myNum * 5;

b. myVal = myOtherNum + 28 – myNum/ 2;

c. myVal++;

d. myVal = myNum % myOtherNum;

e. myVal += 45;

f. myVal += “45”;

g. myVal = (36 – myNum) * myOtherNum;

h. myVal = myNum > myOtherNum;

i. myVal = myNum <= myOtherNum;

j. myVal = (6 > 6) && myOtherNum < myNum;

k. myVal = (5 == 5) || (2 >= 5);

Page 29: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

59

l. myVal = !myVal && true;

m. myVal = !(6 >= 10) && ((myOtherNum * 5 >= myNum)|| false)

7. Where are functions normally created? Why?

8. Diagram the basic function syntax.

9. Write an example of how to create a function named doAddition that takes

two input parameters, adds them together, and returns the resulting sum.

10. Describe in general how to call a function.

11. Write out an example of how to call the doAddition function you created

above, passing along the values 12 and 5 as the input parameters.

12. Write out an example of how to call the doAddition function created above,

passing along the values stored in the myNum1 and myNum2 variables as

parameter values. You may assume that those variables already exist on the

page.

Page 30: Chapter Tw o Functions, Var Operatorscs.clackamas.edu/dcarino/133s/textbook/chap02.pdftax to add must have ctuation ch lues freque; variables rogramme lations or Operat s of their

60

Hands-On Practice Create an HTML file named yourlastname-review02.html that satisfies each of the

following:

Contains all the required tags to make a well-formed HTML 5 page

Contains a form and any other necessary tags to create a math quiz

application. The math quiz should contain:

a. At least one question using addition

b. At least one question using subtraction

c. At least one question using multiplication

d. At least one question using division

e. At least one question using the modulus operator

f. Textboxes that allow quiz takers to enter a numerical answer for each

question

g. Your choice of buttons to check answers. Either:

i. One button that checks the answers to each question and

returns results

=OR=

ii. Multiple buttons – one button to check the answer for each

individual question in turn and returns results

Contain a link to an external JavaScript file. The external JavaScript file

should:

a. Contain a comment that includes your name and the date as well as

comments that document each function you create with the functionʼs

name, description, inputs, and returned value (if any).

b. Contain function(s) necessary to check if an entered value is correct

and generate feedback.

c. Contain a window.onload event and associated function to call

functions and/or associate them with other objectsʼ events.