Programming Fundamentals in JavaScript - Rex A. Barzee
Programming Fundamentals in JavaScript - Rex A. Barzee
Fundamentals in
JavaScript
Published by Maia L.L.C.
Idaho, U.S.A.
maiaco.com
ISBN 978-0-9962463-2-3
The author and publisher of this book have used their best
efforts in preparing this book, and the information contained
in this book is believed to be reliable. These efforts include
the development, research, and testing of the theories and
computer programs in this book to determine their
correctness. However, because of the possibility of human or
mechanical error, the author and publisher make no warranty
of any kind, expressed or implied, with regard to these
programs or the documentation or information contained in
this book. The author and publisher shall not be liable in any
event for incidental or consequential damages in connection
with or arising out of the furnishing, performance, or use of
these programs.
Contents
Page List
iii
Preface
1. How to Use This Book
2. Conventions
3. Acknowledgments
4. Review This Book
iv
1. Chapter Outcomes
2. Starting with JavaScript
3. Running a Program
4. Comments
5. Statements
6. Case Sensitive
7. Declaring Variables
8. String Concatenation
9. Popup Windows
10. Text Fields and Divisions
11. Reserved Words
12. Fixing a Program that Doesn’t Work
13. Common Mistakes
14. Chapter Summary
15. Review Questions
16. Programming Assignments
Chapter 6. Selection
1. Chapter Outcomes
2. Relational Operators
3. if …
4. if … else …
5. if … else if … else …
6. Power of else
v
7. switch
8. Even Integers
9. Odd Integers
10. Quadratic Formula
11. Nested If Statements
12. Common Mistakes
13. Chapter Summary
14. Review Questions
15. Programming Assignments
Chapter 7. Logic
1. Chapter Outcomes
2. Logical Operators
3. Choosing a Group
4. Disneyland Autopia
5. Exclusive Or
6. Logical Equivalences
7. Using De Morgan’s Law
8. Advanced Word Search
9. Truth Tables
10. Common Mistakes
11. Chapter Summary
12. Review Questions
13. Programming Assignments
Chapter 8. Repetition
1. Chapter Outcomes
2. Pre-test and Post-test Loops
3. Counting and Sentinel Controlled Loops
4. Repetition Control Structures
5. while
6. for
7. For Each Loop
8. do while
9. Zero-Based Counting Loop
10. Skipping Loop
11. Infinite Loop
12. Compound Interest
13. break
14. Prime Numbers
15. Repetitive Strings
vi
16. Common Mistakes
17. Chapter Summary
18. Review Questions
19. Programming Assignments
Chapter 9. Functions
1. Chapter Outcomes
2. Writing a Function
3. Calling a Function
4. Variable Scope
5. Advantages of Functions
6. Pseudo Random Integer
7. Code Reuse
8. Area of a Triangle
9. Surface Area of a Pyramid
10. How Long to Invest
11. Greatest Common Divisor
12. Common Mistakes
13. Chapter Summary
14. Review Questions
15. Programming Assignments
vii
1. Chapter Outcomes
2. Objects and Classes
3. Unified Modeling Language
4. Relationships
5. Multiplicities
6. JavaScript Built-in Objects
7. Declaring an Object
8. Creating an Object
9. Accessing an Attribute
10. Calling a Method
11. Dictionaries
12. Local Storage
13. Document Object Model
14. Chapter Summary
15. Review Questions
16. Programming Assignments
Index
1, 2, 3, 4, 5, 6, 7, 8, 9,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
ix
many students. In my teaching experience, I have found
that much of this frustration comes because students are not
shown enough programming examples. All of us learn by
watching others, so why should learning to program a
computer be any different? I wrote this book with minimal
text but filled with computer programming examples and
many hands on exercises to help beginning students learn
computer programming more efficiently and thoroughly and
with less frustration.
Within the text of this book the following fonts and font
styles are used.
x
of learning tools such as
Acknowledgments
I am grateful to Michael McLaughlin for our many discussions
on pedagogy and student learning. I thank my wife for her
support and proofreading of this book. I am also grateful to
my students who have used this book and given me valuable
suggestions, such as Adam Martin, one of my teaching
assistants, who gave me valuable suggestions about the
chapter on functions.
1
Chapter Outcome
By the end of this chapter, you will have a basic
understanding of computer hardware so that you can begin
to program computers.
Semiconductors
Many of the parts of a computer, including the CPU and main
memory, are composed of millions or billions of microscopic
semiconductors that are etched in silicon. The word
semiconductor means these microscopic parts partially
conduct or sometimes conduct electricity. There are many
different types of semiconductors, and each type fulfills a
specific purpose. Below is a list of common semiconductors
and their purpose.
5. Transistor – a
semiconductor with
two inputs and one
output called the
drain. A small Figure 1: Photographs of common
current on the semiconductors: a) capacitor, b) diode,
c) light emitting diode, d) resistor, and
center wire of the e) transistor.
transistor controls a
larger current that
flows on the two outer wires. A transistor can be used as
an amplifier or an automated switch with the small
electric current input controlling the larger input and
output current.
Parts of a Computer
A modern computer is an electronic machine that is
composed of two major parts: hardware and software.
Computer hardware is the physical parts of a computer, such
as the keyboard, mouse, CPU, hard drive, memory, monitor,
and printer. An easy mnemonic to help you remember that
hardware is the physical parts of a computer is that the
physical parts are hard. If someone threw a piece of
computer hardware at you, and it hit you, it would hurt. Of
course, each part of a computer has its own specific purpose.
Here is a list of common computer hardware parts.
3
data across the motherboard from one component to
another.
4
Figure 5: A computer hard drive with its cover removed
exposing the platter and the head that moves above the
platter. Photo is courtesy of Evan-Amos at
en.wikipedia.org
Data Sizes
Each of the following terms is a measure of the amount of
data that a computer can store or process.
5
and not just 1,000,000 bytes.
Clock Speeds
The clock within a CPU is a voltage
small electrical circuit that time
repeatedly produces an
electric signal that pulses,
meaning its voltage rises Figure 6: A graph of a pulsing
and falls similar to electric signal showing three pulses
or cycles.
Figure 6. This electric
signal pulses many times a
second, and a single core on a CPU is designed to complete
one instruction at the end of each pulse. Clock speed is
measured in hertz. A single hertz is one cycle per second. A
cycle is from any point in the pulse to where the pulse
repeats. In other words, a single cycle starts immediately
after the electric voltage falls, includes the voltage rising,
and ends when the voltage falls again. Here are the terms
used to measure clock speeds:
Classes of Computers
Computers can be classified according to their size and
primary purpose. Here are some common computer classes.
6
Categories of Software
Computer hardware is really just a bunch of metal that
electricity can flow through in well-defined paths. Computer
hardware will not do anything without some instructions. The
instructions are written by a computer programmer and are
called software. Computer software is simply a list of
instructions that the computer hardware executes. Computer
software can be classified according to its purpose.
7
Execution Example
Review Questions
1. Which of the following computer components primarily
stores data? (Mark all that apply.)
a. power supply
b. keyboard
c. motherboard
d. bus
e. central processing unit (CPU)
f. cache
g. main memory
h. hard drive
i. DVD drive
j. thumb drive
k. monitor
2. Match each of the following types of computer memory
with the physical quantity that each manipulates to store
data.
a. cache i. light
b. main memory ii. magnetization
c. flash memory iii. electric charge
d. hard drive
e. DVD drive
8
electricity in order to store data. When electricity is
turned off, volatile memory loses its data. Non-volatile
memory stores data after electricity is turned off. Which
of the following computer memory devices are volatile?
(Mark all that apply.)
a. cache
b. main memory
c. flash memory
d. hard drive
e. DVD
9
Chapter Outcomes
Defining Table
Example 1
Defining Table
Input Processing Output
A list of window For each window total cost of all
openings windows
For each compute area in sq. ft.
window multiply area by $35
add cost of this window
width in to the total cost
inches
height in
inches 10
Example 2
You have been asked to write a program that will read from
the keyboard the radius of a circle and will output to the
monitor the diameter, circumference, and area of the circle.
Defining Table
Input Processing Output
Algorithms
Ingredients
Directions
11
Example 3
1. Set sum to 0
2. Get the number of students
3. For each student
a. Get the student’s test score
b. Add the student’s score to the sum
4. Divide the sum by the number of students
Example 4
Within the algorithm that you wrote, is the order of the steps
important? Are there any steps that the order does not
matter?
Computer Programs
A computer program is composed of data and instructions.
The computer stores the data temporarily in its main
memory. It also stores data more permanently in files on a
hard drive, flash memory, or digital versatile disk (DVD). The
instructions in a computer program are like the steps in an
algorithm. In a programming language like JavaScript, the
instructions are called statements. A single statement is
equivalent to a single step in an algorithm or a single
sentence in a paragraph. The statements tell the computer
what to do with the data.
12
Computer Operations
A computer has seven basic operations that it can perform,
all of which we can use when writing algorithms in a
computer program. A computer can do the following:
Control Structures
There are five different categories of control structures
that you can use to control the order in which a computer
executes the statements in your program. They are called
control structures because they control the order in which
the computer executes statements also called the flow of
execution.
sequence
causes the computer to execute statements in the order
they are written in a program, from top to bottom. This is
the default control structure.
selection
causes the computer to select one group of statements to
execute and another group or groups to skip. This is how
a computer appears to make decisions.
repetition
causes the computer to repeat a group of statements.
function call and return
causes the computer to execute the statements in
another function and return a result from the other
function to the call point.
try, catch, and throw
are used to indicate an error occurred and to handle
errors.
You will study, learn, and use the first four of these control
structures in later chapters of this book. Sequence is the
default control structure and is covered in chapters 4 — 12.
Selection is taught in chapters 6 and 7. Repetition is taught
in chapter 8 and again in chapter 10, and function call is
taught in chapter 9.
13
Chapter Summary
An algorithm is simply a list of steps to accomplish a
task.
Sometimes the order in which the steps of an algorithm
are performed is very important.
A defining table is a simple tool to help a programmer
understand a problem before developing an algorithm to
solve the problem. A defining table has three sections:
input, processing, and output.
A computer is capable of performing only a few basic
operations:
receive input
display output
store data
perform arithmetic
compare values
repeat operations
call a function
All high level tasks that a computer can do, such as edit
photographs, play music, and search data are simply
combinations of the basic operations.
A computer program contains both data and instructions.
In JavaScript, the instructions are called statements.
The three basic control structures that a programmer
uses to control the order in which a computer executes
statements are sequence, selection, and repetition.
Review Questions
For each of the following problems write a defining table.
Then write an algorithm with numbered steps to solve the
problem. Then label each step with the name of the basic
computer operation that the computer will use during that
step.
15
language that is used to write documents for the world
wide web of information on the internet. There are several
different versions of the HTML standard, with the most recent
being XHTML 1.1 and HTML 5. This chapter will help you
learn enough HTML 5 so that you can begin writing
JavaScript code in your HTML documents.
Chapter Outcomes
By the end of this chapter, you will be able to:
Comments
A comment in an HTML document is a note or
documentation that a web designer writes for himself or
other designers who will look at the HTML code. The
computer ignores comments. A comment in HTML begins with
the symbols less than, exclamation mark, and two dashes,
like this: <!-- and ends with the symbols two dashes and
greater than, like this: -->.
16
HTML Elements
An HTML document is composed of elements. An element is
simply a part of an HTML document. Figure 7 shows an HTML
element and all of its parts. Notice that an HTML element is
composed of an opening tag, optional text, and a closing tag.
A single tag begins with the less than symbol (<) and ends
with the greater than symbol (>). For example
<div class="note" id="high"> or </div>. An opening tag
contains a tag name and optionally some attributes. Each
attribute is composed of a name and a value separated by
an equal sign (=), such as id="high". A closing tag has the
same name as the opening tag, but the name is preceded by
a slash character (/).
HTML Elements
17
Case Insensitive
HTML 5 is not case sensitive. This means that <HTML> and
<html> and <HtMl> have the same meaning in HTML 5.
However, the standard convention is to use all lower case for
tags and attributes except for the DOCTYPE declaration,
which is all uppercase. Most developers use lower case
letters for at least two reasons:
<body>
<p>Oregano is an important <i>culinary</i> herb. It is
used in Greek and Italian dishes especially tomato
based sauces, fried vegetables, and grilled meats.</p>
</body>
19
Required Elements
Every HTML 5 document must start with a <!DOCTYPE>
declaration and an opening <html> tag. Every HTML 5
document must have a head section and a body section, and
the head section should have a <title> tag and a <meta>
tag that states the document’s character encoding. In other
words, the skeleton of every HTML 5 document should look
similar to this:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
</body>
</html>
Example 1
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<!-- The following meta tag tells the browser
that this document uses the 8-bit Unicode
Transformation Format encoding. -->
<meta charset="utf-8">
<meta name="author" content="Rex Barzee">
<title>Horse Rentals</title>
</head>
<body>
<h1>Horse Rentals</h1>
<p>We rent horsies, big horsies, medium sized
horsies, and little horsies (big dogs really). Of
course, this costs a great deal of money, and in
order for us to allow you to take the horsies
anywhere, you must sign a lot of paper work, about
the same amount as if you were buying a house or
being admitted to a hospital (which might happen
if you fall off one of our horsies).</p>
<p>We rent horsy saddles and other leather and
metal stuff. Just ask for what you want, and we
probably have it. These are used mostly to control
the horsies, which they don't like. If you don't
take great care when putting these on the horsies,
you might be admitted to the hospital as mentioned
in the above paragraph.</p>
<p>We also rent horsy trailers. These trailers
require a truck the size of Texas that drinks diesel
in order to actually pull them. Of course, if you
don't have a truck that fits this description, we'll
rent you one. See the first paragraph again for our
rental terms (big money).</p>
</body>
</html>
20
21
Example 2
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<!-- The following meta tag tells the browser
that this document uses the 8-bit Unicode
Transformation Format encoding. -->
<meta charset="utf-8">
<title>Send a Text Message</title>
</head>
<body>
<h1>Send a Text Message</h1>
<p>
From (your 10-digit wireless phone number):
<input type="text" id="txtFrom" size="10">
</p>
<p>
To (10-digit wireless phone number):
<input type="text" id="txtTo" size="10">
</p>
<p>
Message:<br>
<textarea id="txaMessage" rows="8" cols="40">
</textarea>
</p>
<p>
<button type="button" onclick="sendText()">Send</button
<button type="button" onclick="clearForm()">Clear</button
</p>
</body>
</html>
22
It is helpful to examine the tags in example 2 in more
depth. How many different tags does example 2 use?
11. They are <html>, <head>, <meta>, <title>, <body>,
<h1>, <p>, <input>, <br>, <textarea>, <button>
Notice that the two <input> tags and the <textarea> tag
have an attribute named id. An id attribute uniquely
identifies an element within an HTML document. In other
words, the value for an id attribute must be unique within a
document. Notice that the values for all three of the id
attributes are different: id="txtFrom", id="txtTo",
id="txaMesssage".
Common Mistakes
Forgetting to terminate a tag
Incorrect
<div Idaho, with its volcanic
soils and cool nights, is ideal
for growing potatoes.</div>
Correct
<div>Idaho, with its volcanic
soils and cool nights, is ideal
for growing potatoes.</div>
Incorrect Correct
<div id="output></div> <div id="output"></div>
Incorrect Correct
<b>really <b>really</b>
Incorrect
<div>The average lifespan for a
female grizzly bear is estimated
at <b>26 years.</div></b>
Correct
<div>The average lifespan for a
female grizzly bear is estimated
at <b>26 years</b>.</div>
23
Forgetting to save an HTML file with a suffix of .html
Chapter Summary
Hypertext markup language (HTML) is a computer
language that is used to write documents.
HTML 5 is the most recent version of HTML.
An HTML 5 document must begin with a document type
declaration and must contain a head and a body.
HTML is composed of many tags. Each tag begins with a
less than symbol (<) and ends with a greater than
symbol (>).
HTML tags usually come in pairs, an opening tag and a
closing tag.
Opening tags may contain attributes which are
name/value pairs separated by the equal symbol (=).
Opening tags that do not require a matching closing tag
are called void tags.
HTML is not case sensitive, so tags names and attribute
name may be written in upper or lower case or any
combination of upper and lower case.
HTML tags should be properly nested.
Review Questions
8. Write the HTML tag and its attributes for creating a text
field. Include the surrounding less than (<) and greater
than (>) symbols in your answer.
Assignments
1. Create and validate a well formed HTML 5 document that
tells a short version of your life story. The document
must include at least one heading and two paragraphs.
25
Netscape under the name Mocha, later renamed
LiveScript, and finally renamed JavaScript. JavaScript is most
often used in web pages on the client side (web browser).
Despite its name, JavaScript has very little in common with
the Java programming language. The little that they have in
common includes the syntax of the C programming language
and some naming conventions and names, such as Date,
Math, and String. You can find a good online tutorial for
JavaScript at w3schools.com and a good online reference for
JavaScript at developer.mozilla.org
Chapter Outcomes
By the end of this chapter, you will be able to:
Example 1
1 <!DOCTYPE HTML>
2 <html lang="en-us">
3 <head>
4 <meta charset="utf-8">
5 <title>My First JavaScript Program</title>
6 <script>
7 /* Defining Table
8 * Input: No user input
9 * Processing: None
10 * Output: The message "Water is delicious!"
11 */
12 function showMessage() {
13 // The next line of code causes the computer
14 // to open a popup window that contains the
15 // words "Water is delicious!"
16 alert("Water is delicious!");
17 }
18 </script>
19 </head>
20
21 <body>
22 <button type="button" onclick="showMessage()"
23 </body>
24 </html>
26
the onclick
attribute. The onclick
code executes the
showMessage function,
which begins at line 12
and ends at line 17.
Within this function at
line 16, is a command
which causes the
computer to open a Figure 10: A simple HTML document
popup window that with a single button drawn in Chrome.
contains the text
“Water is delicious!” as
shown in figure 11.
Comments
A comment in a JavaScript program is a note or
documentation that a programmer writes for himself or other
programmers who will look at his code. The computer ignores
comments. There are two styles of comments in JavaScript:
single line and multi-line. A single line comment begins with
two forward slashes (//), and ends at the end of the line of
text. A multi-line comment begins with a forward slash and
an asterisk (/*), and ends with an asterisk and a forward
slash (*/). When writing a multi-line comment, many
programmers start each line with an asterisk to make the
comment stand out from the other code. Both styles of
comments are shown in example 1, multi-line at lines 7–11
and single line at lines 13–15.
27
Statements
A JavaScript program is composed of statements. A
statement is a complete command within a program.
Statements in JavaScript end with a semicolon (;). Notice in
example 1 that the statement at line 16 ends with a
semicolon. When writing a program, a programmer will often
group statements together in a block by surrounding the
statements with curly braces: { and }.
Case Sensitive
JavaScript is case sensitive, so if you want your JavaScript
program to work, you must be careful to always type
statements with the correct case. For example, to cause the
computer to open a popup window, you must type alert not
Alert.
Declaring Variables
A variable is a location within the computer’s memory to
store data. When writing a computer program, a programmer
declares variables so that the computer will reserve space in
memory for the variables’ contents. In JavaScript, we declare
a variable by writing the keyword var and the variable’s
name. Here are several examples of declaring variables in
JavaScript.
var price;
var numStudents;
var name;
String Concatenation
Within a JavaScript program, a piece of text is called a
string of text. In JavaScript, you must surround all strings of
text with quotes. It doesn’t matter if you use single (') or
double (") quotes, but you must be consistent. If you begin a
string with a single quote then you must end it with a single
quote. If you begin with double quotes, you must end with
double quotes.
28
Popup Windows
A JavaScript program can get user input by opening a popup
window where a user can type input. Example 2 contains an
HTML document with a JavaScript program that
Example 2
1 <!DOCTYPE HTML>
2 <html lang="en-us">
3 <head>
4 <meta charset="utf-8">
5 <title>A Program to Say Hello</title>
6 <script>
7 /* Defining Table
8 * Input: A person's name
9 * Processing: Create a greeting for that person
10 * Output: The greeting
11 */
12 function greetUser() {
13 // This line prompts the user to type in his name.
14 var name = prompt("Please enter your name");
15
16 // Create a personalized greeting for the user.
17 var greeting = "Hello " + name + ". I hope you are w
18
19 // The next line causes the computer to display
20 // a greeting to the user in a popup window.
21 alert(greeting);
22 }
23 </script>
24 </head>
25
26 <body>
27 <button type="button" onclick="greetUser()">Hello</
28 </body>
29 </html>
Example 3
1 <!DOCTYPE HTML>
2 <html lang="en-us">
3 <head>
4 <meta charset="utf-8">
5 <title>Applied Scripture</title>
6 <script>
7 /* Defining Table
8 * Input: A person's name
9 * Processing: Create a verse of scripture for that perso
10 * Output: The scripture
11 */
12 function applyScripture() {
13 // Get the user's name from the text field that has t
14 // of "nameInputBox" and store it in a variable named
15 var name = document.getElementById('nameInputBox'
16
17 // Use string concatenation to create a verse
18 // of scripture personalized for the user.
19 var scripture = "I, " + name + ", having been born of
20 " goodly parents, therefore I was taught somewhat
21 " in all the learning of my father.";
22
23 // Display the scripture in the div that has the id "
24 document.getElementById('outputDiv').innerHTML = scri
25 }
26 </script>
27 </head>
28
29 <body>
30 Please enter your name: <input type="text" id="nameInputB
31 <button type="button" onclick="applyScripture()">Verse</
32 <div id="outputDiv"></div>
33 </body>
34 </html>
30
The
Figure 12: A program to create a personalized verse of
scripture.
Reserved Words
The following is a list of all reserved words in JavaScript. You
should not use any of these words as variable or function
names in your JavaScript programs.
JavaScript Keywords
break case catch continue
debugger default delete do
else false finally for
function if in instanceof
let new null return
switch this throw true
try typeof undefined var
while with
JavaScript Types
Array Boolean Date Function
Math Number Object RegExp
String
JavaScript Objects
31
document event window
1. Make sure you saved your HTML file with the suffix
.html
2. Validate your HTML file by uploading it to the online
validator at validator.w3.org
3. Load your HTML document in a web browser and check
the JavaScript console for errors. You can view the
console in Google Chrome by pressing Shift-Ctrl-J
(Windows and Linux) or Command-Option-J (Mac).
4. Click the button in your HTML document to execute your
code and check the JavaScript console again for errors.
5. Use the JavaScript debugger that is built into your web
browser to step through your code line by line and watch
the values of the variables.
32
Common Mistakes
Mispelling onclick
Incorrect
<button type="button" onlick="funcName()">
Correct
<button type="button" onclick="funcName()">
Correct
<button type="button" onclick="funcName()">
Incorrect
<button type="button" onclick="funcName">
Correct
<button type="button" onclick="funcName()">
Chapter Summary
Within an HTML document, JavaScript programs must be
placed inside script tags.
To cause a computer to execute a JavaScript program
when a user clicks a button, the button must have an
onclick attribute.
A JavaScript program may get input from a popup
window or from a text field.
A JavaScript program may send output to a popup
window or to an HTML div.
To make a large string of text from smaller strings of
text, use the string concatenation operator which is the
plus symbol (+).
Review Questions
33
Programming Assignments
1. Type in the HTML and JavaScript code for example 2 in
this chapter. Modify the code by changing the greeting
that is displayed to the user. The changed greeting must
include the user’s name. Validate the code and load it in
a web browser to run and test it.
35
instructions. The data may be temporarily stored in the
computer’s memory, or it may be stored more permanently
on the computer’s hard drive, a DVD, or a jump drive. When
data is in the computer’s memory, it is stored inside
variables. A variable has a name, type, value, and scope.
The term variable comes from the fact that a variable’s value
can be changed or varied.
Chapter Outcomes
By the end of this chapter, you will be able to:
Declaring a Variable
Before you can use a variable in a computer program, you
must declare that variable. Declaring a variable tells a
computer to reserve space in main memory for that variable.
To declare a variable in a JavaScript program, simply write
the keyword var and the variable’s name. A variable name
must start with an uppercase or lowercase letter, the
underscore (_), or the dollar sign ($). The rest of the name
must be made of letters, digits (0–9), the underscore, or the
dollar sign. A variable name cannot include spaces. A
variable name should be meaningful and should curtly
describe what the variable stores. A computer programmer
uses a variable’s name in a program as a representation of
the variable’s value. This is similar to how a variable is used
in an algebraic equation.
Template
Example 1
Example 2
Variable Types
Each variable has a type so that the computer knows what
kind of data can be stored in the variable and what
operations the computer may perform on the variable. A
variable’s type is determined by the data that is stored in the
variable. A variable in a JavaScript program may have any
one of these types.
Template
name = value;
Example 3
var price, discRate;
var title;
price = 12.95;
discRate = 0.25;
title = "A Poor Wayfaring Man of Grief";
37
Template
Example 4
Example 5
Desk Checks
While reading the rest of this book, you will find it helpful to
step through the example code line by line as if you were a
computer. Doing this is sometimes called a desk check
because you are checking the code on paper or “at your
desk” instead of running it on a computer. To perform a desk
check, draw a table that represents part of the computer’s
main memory. Step through the given code line by line as if
you were the computer, and change the value of each
variable just as the computer would. For example, if you
were given the following code:
1 var x = 7;
2 var y = -3;
3 var a = x;
4 y = 4;
Desk Check
x y a
7 −3 7
4
Notice that the first line of the code changes the value of the
variable x to 7, so in the table 7 is written underneath the
heading “x”. The second line of code changes y to −3, so −3
is written underneath “y”. The third line of code copies the
value of x into a, so 7 is written underneath “a”. Finally, the
last line of code changes the value of y to 4, so −3 is crossed
through and 4 is written below “y”.
38
somewhere else. This input is given in the desk check
table. For example, the code:
var y = x;
Desk Check
x y
15
Swapping Values
If a program needs to exchange the value of one variable
with another variable, or in other words swap their values, a
common and easy way to do this is to use a temporary
variable. The example code below uses a temporary variable
named swap to exchange the values of two variables: a and
b. Desk check this code. To perform a desk check, step
through the example code line by line as if you were a
computer and write the value for each variable in the empty
boxes. A missing box is a hint that means there is no value
for you to write in that spot.
Example 6
var swap = a;
a = b;
b = swap;
Desk Check
a b swap
8 −3
Arithmetic Expressions
39
Arithmetic Operators
The five basic arithmetic operations that a computer can
perform are multiplication, division, modulus, addition, and
subtraction. As explained earlier in this chapter, a computer
can also assign a value to a variable. A programmer makes
the computer perform these arithmetic operations by writing
the corresponding operator (symbol) in a program. Here are
the arithmetic operators available in JavaScript.
Modulus
Examples
7% 3= 1
12 % 3 = 0
−6 % 4 = −2
6 % −4 = 2
−6 % −4 = −2
40
Operator Precedence
When an arithmetic expression includes two or more
different operators, the result is often ambiguous. For
example, what is the result of 7 − 3 * 2? Is it 8 or 1? The
answer depends on the order in which the arithmetic
operations are done. Because of this ambiguity, programming
languages include arithmetic operator precedence.
Precedence determines which operator the computer
evaluates first and which it evaluates last.
Example 7
var v = i * (1 + a / n) * (y / n);
Example 8
Example 9
1 <!DOCTYPE HTML>
2 <html lang="en-us">
3 <head>
4 <meta charset="utf-8">
5 <title>Convert Celsius to Fahrenheit</title>
6
7 <script>
8 /* Input: a temperature in Celsius
9 * Processing: convert the temperature from Celsius to Fa
10 * Output: the temperature converted to Fahrenheit
11 */
12 function celsToFahr() {
13 // Read a Celsius temperature from the user.
14 var text = document.getElementById('celsiusInputBox'
15
16 // Convert what the user typed from text into a numbe
17 var c = parseFloat(text);
18
19 // Convert the Celsius temperature into Fahrenheit.
20 var f = c * 9 / 5 + 32;
21
22 // Display the Fahrenheit temperature to the user.
23 document.getElementById('fahrenDiv').innerHTML = f;
24 }
25 </script>
26 </head>
27
28 <body>
29 Enter a temperature in Celsius: <input type="text"
30 <button type="button" onclick="celsToFahr()">Convert</
31 <div id="fahrenDiv"></div>
32 </body>
33 </html>
Desk Check
text c c * 9 c * 9 / 5 f
"20"
42
Fahrenheit to Celsius
The formula for converting a temperature in Fahrenheit to
Celsius is c = 5 (f − 32)
9
Example 10
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Convert Fahrenheit to Celsius</title>
<script>
/* Input: a temperature in Fahrenheit
* Processing: convert the temperature from Fahrenheit to Cel
* Output: the temperature converted to Celsius
*/
function fahrToCels() {
// Read a Fahrenheit temperature from the user.
var text = document.getElementById('fahrenInputBox'
// Convert what the user typed from text into a number.
var f = parseFloat(text);
<body>
Enter a temperature in Fahrenheit: <input type="text"
<button type="button" onclick="fahrToCels()">Convert</
<div id="celsiusDiv"></div>
</body>
</html>
Desk Check
text f f − 32 5 / 9 c
"25"
43
Assignment Operators
In addition to the arithmetic operators described above,
JavaScript also has assignment operators that perform
arithmetic. These operators are really shortcuts for
performing arithmetic using the current value of a variable
and then storing the result of the arithmetic back into that
variable.
44
Example 14
Desk Check
price toppings perTopping
10.95 3 1.45
15.30
Example 15
Desk Check
subtotal tax total
Example 16
Example 17
Desk Check
total
45
Example 18
var a = 4;
var b = ++a * 3 + 2;
Desk Check
a b
4 17
5
Example 19
var a = 4;
var b = a++ * 3 + 2;
Desk Check
a b
4 14
5
Example 20
var x = 3;
var y = ++x * 2 + 5;
Desk Check
x y
Example 21
var x = 3;
var y = x++ * 2 + 5;
Desk Check
x y
Example 22
var q = 7;
var s = 2 + 18 / --q;
Desk Check
q s
47
Math Object
The Math object is an object (see chapter 11) built into
JavaScript that enables a program to perform more advanced
mathematical computations. It contains the following
mathematical constants and functions, all of which must be
preceded by “Math.” when you use them in a program.
48
Volume of a Cylinder
If we know the radius and height of a
cylinder, we can compute the volume of that
cylinder using the formula: v = π r2h where v
is the volume, r is the radius, and h is the
height of the cylinder. This formula can be
written in JavaScript as shown in the next
example. Notice the use of the built-in
JavaScript constant Math.PI. Figure 14: A
cylinder with
radius r and
height h.
Example 23
var v = Math.PI * r * r * h;
Desk Check
r h v
2.7 5
d = √(x − x )2 + (y − y )2
2 1 2 1
where d is the
distance between the
points, point p1 has
the coordinates
(x1, y1), and point p2
has the coordinates
(x2, y2).
Example 24 contains
a program that reads
the x and y values for Figure 15: A plot of two points.
two points from a
user, and then computes and outputs the distance between
those two points. Notice the code at line 14 combines into a
single line, the code to read text from a text field and the
code to convert that text into a number. In previous
programs, these two steps were written separately like this:
var text = document.getElementById('x1inputBox').value;
var x1 = parseFloat(text);
1 <!DOCTYPE HTML>
2 <html lang="en-us">
3 <head>
4 <meta charset="utf-8">
5 <title>Distance</title>
6
7 <script>
8 /* Input: x and y for two points: x1, y1, x2, y2
9 * Processing: Calculate the distance between the two poi
10 * Output: the distance
11 */
12 function distance() {
13 // Get the coordinates for two points from the user.
14 var x1 = parseFloat(document.getElementById('x1inputB
15 var y1 = parseFloat(document.getElementById('y1inputB
16 var x2 = parseFloat(document.getElementById('x2inputB
17 var y2 = parseFloat(document.getElementById('y2inputB
18
19 // Compute the distance between the two points.
20 var dx = x2 - x1;
21 var dy = y2 - y1;
22 var dist = Math.sqrt(dx * dx + dy * dy);
23
24 // Display the distance to the user.
25 document.getElementById('outputDiv').innerHTML = dist
26 }
27 </script>
28 </head>
29
30 <body>
31 Please enter the x and y coordinates for two points:<
32 (x1, y1) <input type="text" id="x1inputBox" size="3"
33 <input type="text" id="y1inputBox" size="3"
34 (x2, y2) <input type="text" id="x2inputBox" size="3"
35 <input type="text" id="y2inputBox" size="3"
36 <button type="button" onclick="distance()">Distance</
37 <div id="outputDiv"></div>
38 </body>
39 </html>
Desk Check
x1 y1 x2 y2 dx dy dist
2 5 3 −2
50
Round to Decimal Places
The built in JavaScript Math object has a function to round a
real number to an integer. However, a programmer will
occasionally need to write a program that rounds real
numbers to a fixed number of places after the decimal point.
For example, U.S. currency amounts are usually rounded to
two decimal places (pennies). Here is code that uses the built
in Math.pow and Math.round functions to round the value in
a variable named dist to two decimal places.
Example 25
<script>
/* Input: x and y for two points: x1, y1, x2, y2
* Processing:
* 1. Calculate the distance between the two points.
* 2. Round the distance to two digits after the decimal.
* Output: the rounded distance
*/
function distance() {
// Get the coordinates for two points from the user.
var x1 = parseFloat(document.getElementById('x1inputBox'
var y1 = parseFloat(document.getElementById('y1inputBox'
var x2 = parseFloat(document.getElementById('x2inputBox'
var y2 = parseFloat(document.getElementById('y2inputBox'
// Compute the distance between the two points.
var dx = x2 - x1;
var dy = y2 - y1;
var dist = Math.sqrt(dx * dx + dy * dy);
// Round the distance to two digits after the decimal.
var digits = 2;
var multiplier = Math.pow(10, digits);
dist = Math.round(dist * multiplier) / multiplier;
// Display the distance to the user.
document.getElementById('outputDiv').innerHTML = dist;
}
</script>
Desk Check
x1 y1 x2 y2 dx dy dist digits multiplier
7 −2 4 6
51
Common Mistakes
Forgetting to declare a variable
Incorrect Correct
miles = 61; var miles = 61;
Incorrect Correct
var total = 175; var total = 175;
var total *= 1.06; total *= 1.06;
Incorrect
var x = document.getElementById('num1inputBox').value;
var sum = x + 5;
Correct
var text = document.getElementById('num1inputBox').value;
var x = parseInt(text);
var sum = x + 5;
// or
var x = parseInt(document.getElementById('num1inputBox').v
var sum = x + 5;
Incorrect
var g = (1 + r) ^ n;
Correct
var g = Math.pow(1 + r, n);
52
Chapter Summary
Before using a variable in JavaScript, you must declare
it. To declare a variable, write the keyword var followed
by the variable’s name.
Use the assignment operator (=) to assign a value to a
variable.
Within a JavaScript program, use these operators: *, /,
%, +, - to multiply, divide, compute the remainder after
division, add, and subtract.
The assignment operators (*=, /=, %=, +=, -=) are
shortcuts for performing arithmetic using the current
value of a variable and then storing the result into that
variable.
To add one to the value of a variable, you can use the
increment operator (++). You can use the decrement
operator (--) to subtract one from the value of a
variable.
Each of the arithmetic operators has a precedence. It is
important that you understand precedence when writing
formulas in JavaScript.
To program a computer to perform more advanced
arithmetic, such as exponentiation, square root, and
rounding, you must use the functions in the Math object.
Review Questions
1. Declare two variables named balance and rate.
53
code, variable e will be of what data type and hold
what value?
var c = 15;
var d = -2.17;
var e = c + d;
z += x - 3 * y;
Programming Assignments
1. Write a defining table and a JavaScript program to
compute and output the volume of a tin can. Hint: use
the formula and JavaScript code given in this chapter to
compute the volume of a cylinder. Your program should
correctly handle real numbers.
4. An employee at a
grocery store must
frequently place
boxes of cans in
stacks. Write a
defining table and a
program that allows
him to enter the total
number of boxes and
the number of boxes
he will place in each stack. Your program must output the
number of stacks he will have to make. All of the stacks
except the last one must have the exact number of boxes
that the employee specifies. The last stack must have the
exact number or fewer boxes. For example, if the
employee enters 74 total boxes and 6 boxes in each
stack your program must output 13.
5. A teacher
frequently
divides her
class into
teams. Write
a defining
table and a
program that
allows her to
enter the
number of
students in her class and the number of teams she
wants. The number of members on each team must be as
balanced as possible. In other words, if not all of the
teams can have the same number of members then some
of the teams will have only one more member than the
other teams. Your program must output a phrase that
tells the teacher how to divide her class into teams. For
example, if the teacher entered 27 class members and 8
teams, your program must output “3 teams with 4
members and 5 teams with 3 members.” Your program
must list the larger teams first.
57
must be able to make decisions. The computer makes
decisions by evaluating a condition and if the condition is
true, selecting one set of statements to execute. If the
condition evaluates to false, then the computer selects a
different set of statements to execute. This decision making
ability is known as selection because the computer is
selecting either one group of statements or another group of
statements to execute. A selection statement is also called
an if statement because in most programming languages it
starts with the keyword if.
Chapter Outcomes
By the end of this chapter, you will be able to read and write:
Relational Operators
A selection statement always has a condition, which is the
test the computer uses to select one set of statements or the
other. A condition always evaluates to either true or false.
Any expression that evaluates to either true or false is called
a boolean expression named after the British mathematician
George Boole. There are six JavaScript relational
operators, which test the relation between two values and
yield only true or false.
58
if …
Use when:
A true choice exists and the false choice does not exist
Template
if (condition) {
statements;
}
Example 1
Desk Check
balance interest
700
Desk Check
balance interest
700 21
721
Figure 16: When balance is greater than 500, the computer will
execute the statements inside the body of the if statement.
Desk Check
balance interest
300
Figure 17: When balance is not greater than 500, the computer will
skip the statements inside the body of the if statement.
59
if … else …
Use when:
Template
if (condition) {
statements;
}
else {
statements;
}
Example 2
var bonus;
if (sales <= 1000) {
bonus = 20;
}
else {
bonus = 100;
}
var salary = sales * 0.10 + bonus;
Desk Check
sales bonus salary
1250
Desk Check
sales bonus salary
1250 100 225
Figure 19: When sales is greater than
1000, the computer will skip the
statements inside the body of the if
statement and execute the statements in
the else.
61
if … else if … else …
Use when:
Template
if (condition) {
statements;
}
else if (condition) {
statements;
}
…
else {
statements;
}
Example 3
var discount;
if (cost < 100) {
discount = 0.10;
}
else if (cost < 250) {
discount = 0.15;
}
else if (cost < 400) {
discount = 0.18;
}
else {
discount = 0.20;
}
cost *= (1 - discount);
Desk Check
cost discount
300
62
Figures 20, 21, and 22 show the order in which the
computer will execute the statements from example 3.
Figure 20 shows that when cost is less than 100, the
computer will execute the statements inside the body of the
first if statement and skip the statements in the else
statements. Figure 21 shows that when cost is between 250
and 400, the computer will skip the statements inside the
body of the first two if statements, execute the statements
in the body of the third if statement, and then skip the last
else. Figure 22 shows that when cost is greater than 400,
the computer will skip the statements inside the bodies of
the first three if statements and execute the code in the
body of the last else.
Desk Check
cost discount
70 0.10
63
Figure 20: When cost is less
than 100, the computer will
execute the statements
inside the body of the first if
statement and skip the
statements in the else
statements.
Desk Check
cost discount
300 0.18
246
Figure 21: When cost is
between 250 and 400, the
computer will skip the
statements inside the body of
the first two if statements,
execute the statements in the
body of the third if
statement, and then skip the
last else.
63
Desk Check
cost discount
480 0.20
384
Figure 22: When cost is
greater than 400, the
computer will skip the
statements inside the bodies
of the first three if
statements and execute the
statements in the body of the
last else.
Power of else
Many beginning programmers forget that the keyword else
can be used by itself without another if statement. For
example, when writing an if statement that will execute
different code for males and females, many beginning
programmers write something like this:
if (gender == 'M') {
// Code for males goes here.
}
else if (gender == 'F') {
// Code for females goes here.
}
var rate;
if (age < 18) {
// Code for minors goes here.
rate = 0.4;
}
else if (age < 57) {
// Code for adults goes here.
rate = 0;
}
else {
// Code for senior citizens goes here.
rate = 0.25;
}
64
switch
Use when:
Template
switch (variable) {
case constValue1: statements; break;
case constValue2: statements; break;
…
default: statements; break;
}
Example 4
var registerDate;
switch (classStanding) {
case 'F':
registerDate = "Nov 23";
break;
case 'S':
registerDate = "Nov 17";
break;
case 'J':
registerDate = "Nov 12";
break;
case 'N':
registerDate = "Nov 6";
break;
default:
registerDate = "none";
alert("unknown class standing");
break;
}
document.getElemenById('output').innerHTML = registerDate
Desk Check
classStanding registerDate
'J'
65
Even Integers
The easiest way for a computer to determine if an integer is
even is to divide the number by two, and if the remainder of
this division is equal to zero, then the integer is even. The
modulus operator performs integer division and returns the
signed remainder of the division. The code example below
uses the modulus operator to determine if an integer is even.
Example 5
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Is Even?</title>
<script>
/* Input: An integer
* Processing: Determine if the integer is even or odd
* Output: A message that says the integer is even or odd
*/
function isEven() {
// Get the user input from a text field and convert it to
var text = document.getElementById('integerInputBox'
var number = parseInt(text);
// Choose a message.
var message;
if ((number % 2) == 0) {
message = number + " is an even integer";
}
else {
message = number + " is an odd integer";
}
// Display the message to the user.
document.getElementById('outputDiv').innerHTML = message;
}
</script>
</head>
<body>
Please enter an integer: <input type="text" id="integerInputB
<button type="button" onclick="isEven()">Is Even?</button
<div id="outputDiv"></div>
</body>
</html>
Desk Check
text number number % 2 message
"8"
Odd Integers 66
Example 6
// Wrong! Doesn't work for negative odd integers!
if ((number % 2) == 1) {
document.getElementById('outputDiv').innerHTML = numb
}
else {
document.getElementById('outputDiv').innerHTML = numb
}
Example 7
67
the bitwise And operator because it may execute faster
than a test using the modulus operator. However, the
disadvantages of such code, almost never justify the very
small, possible gain in execution speed, especially because
most modern compilers will automatically optimize the
compiled version of the statement using the modulus
operator: if ((number % 2) == 0) to be the same as using
the bitwise And operator: if ((number & 1) == 0)
Quadratic Formula
A quadratic equation
of the form
y = ax2 + bx + c has two
solutions, also called
roots, that may or
may not be distinct
and that may be real
or complex. If you
graph a quadratic
equation, the roots
are the locations
where the equation
crosses the x-axis. Figure 23: A graph of three quadratic
equations.
Figure 23 contains
the graph of three
different quadratic equations. Notice that the first equation
(on the left) crosses the x-axis twice and therefore has two
real roots. The second equation crosses or touches the x-axis
only once and therefore has only one distinct real root. The
third equation does not cross the x-axis and so its two roots
are complex meaning they contain the square root of −1.
The square root of −1 does not exist, and mathematicians
say it is imaginary.
−b ± √b2 − 4ac
x=
2a
68
quadratic equation if they exist. Notice the if statement
that determines if the roots exist (are real) or do not exist
(are complex).
Example 9
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Quadratic Formula</title>
<script>
/* Input: Three coefificients from a quadratic equation.
* Processing: If they exist, compute the root or roots of th
* Output:
* The root or roots of the equation or
* "undefined" if they don't exist.
*/
function quadratic() {
// Get three coefficients a, b, and c
// for a quadratic equation from the user.
var a = parseFloat(document.getElementById('aInputBox'
var b = parseFloat(document.getElementById('bInputBox'
var c = parseFloat(document.getElementById('cInputBox'
Desk Check
a b c discr sq root1 root2
1 −4 3
69
Nested If Statements
It is often useful to write one if statement inside another if
statement or inside the else part of an if statement.
Consider the problem to write a program that reads from the
keyboard the total weekly sales for a sales person and then
outputs the sales person’s commission according to this table.
Example 10
Desk Check
sales rate commission output
850
70
Although the previous example is correct, it can be
written in a slightly shorter way by combining the else and
if statements like this.
Example 11
Desk Check
sales rate commission output
850
71
This could also be solved using nested if statements as
shown in the next example.
Example 12
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Ticket Price</title>
<script>
/* Input: A person's age and the number
* of games that person has attended
* Processing: Determine the price to charge
* that person for a ticket to a game
* Output: The ticket price
*/
function ticketPrice() {
var age = parseInt(document.getElementById('ageBox'
var gamesAttended = parseInt(document.getElementById
var price;
if (age < 18) {
if (gamesAttended < 6)
price = 8.0;
else if (gamesAttended < 11)
price = 6.0;
else
price = 5.0;
}
else if (age < 55) {
if (gamesAttended < 11)
price = 10.0;
else
price = 8.0;
}
else {
if (gamesAttended < 11)
price = 8.0;
else
price = 6.0;
}
document.getElementById('priceDiv').innerHTML = price;
}
</script>
</head>
<body>
Age: <input type="text" id="ageBox" size="3"><br>
Number of games attended: <input type="text" id="gamesBox"
<button type="button" onclick="ticketPrice()">Ticket Price</
<div id="priceDiv"></div>
</body>
</html>
Desk Check
age gamesAttended price
38 6
72
Sometimes nested if statements can be a little tricky as
shown in the following example which has two if statements
but only one else statement. According to the rules of
JavaScript, an else statement is paired with only one if
statement. This means that in the example code below, if the
first condition (x < 2) is true and the second condition
(y > 8) is false, the computer will not change message to
either “Hello” or “Goodbye”. In that situation, the computer
will display “Wave”.
Example 13
var message = 'Wave';
if (x < 2) {
if (y > 8) {
message = 'Hello';
}
}
else {
message = 'Goodbye';
}
document.getElementById('outputDiv').innerHTML = message;
Desk Check
x y message
1 5
Common Mistakes
Forgetting parentheses around the condition
Incorrect Correct
if x < 7 { if (x < 7) {
} }
Incorrect Correct
if (age = 18) { if (age == 18) {
} }
Incorrect Correct
if (growth > 500) { if (growth > 500) {
} }
else; { else {
} }
73
Forgetting braces when there is more than one
statement inside an if statement
Incorrect
if (bal > 500)
var intr = bal * 0.03;
bal += intr;
Correct
if (bal > 500) {
var intr = bal * 0.03;
bal += intr;
}
Unnecessary Comparisons
Incorrect Correct
if (age < 18) { if (age < 18) {
} }
else if (age >= 18) { else {
} }
Chapter Summary
Selection is a control structure that allows the computer
to execute one group of statements and skip another
group of statements.
An if statement is a selection statement that begins with
the JavaScript keyword if.
An if statement must have a condition in parentheses.
The parentheses contain code to compare two values.
There are six comparison operators in JavaScript: equal
to (==), not equal to (!=), less than (<), less than or
equal to (<=), greater than (>), greater than or equal to
(>=).
A switch statement is a selection statement that begins
with the JavaScript keyword switch and can be used
instead of a long set of if … else if … else
statements.
74
Review Questions
75
Programming Assignments
4. Write a
76
defining
table
and a
program
to quiz
a child
on
simple
77
want the computer to evaluate more than one
comparison. For example, we may want the computer to
check if a person is male and older than forty years. To
combine more than one comparison within an if statement
we use the logical operators.
Chapter Outcomes
By the end of this chapter, you will be able to:
Logical Operators
To combine two or more comparisons in the condition of a
single if statement, we use the logical operators, also called
the boolean operators. The following table describes the four
JavaScript logical operators.
Template
Choosing a Group
A programmer can use the logical operators to write code
that chooses in which group a person or item belongs.
Consider the following program that reads a girl’s age from
the keyboard and determines which class she should attend.
The program uses these criteria to choose the correct class.
Age Class
younger than 12 Primary
12 or 13 Beehive
14 or 15 Mia Maid
16 or 17 Laurel
18 or older Relief Society 79
Example 2
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Which Class</title>
<script>
/* Input: A girl's age
* Processing: If statements to choose a class
* Output: Name of the class
*/
function chooseClass() {
var age = parseInt(document.getElementById('age'
var clss;
if (age <= 11) {
clss = 'Primary';
}
else if (age == 12 || age == 13) {
clss = 'Beehive';
}
else if (age == 14 || age == 15) {
clss = 'Mia Maid';
}
else if (age == 16 || age == 17) {
clss = 'Laurel';
}
else {
clss = 'Relief Society';
}
document.getElementById('output').innerHTML = clss;
}
</script>
</head>
<body>
Please enter your age: <input type="text" id="age" size="3"
<button type="button" onclick="chooseClass()">Class</
<div id="output"></div>
</body>
</html>
Desk Check
age clss
14
80
age from the keyboard and determines which scouting
group he should attend. The program uses these criteria to
choose the correct group.
Age Group
7 Tiger
8 Wolf
9 Bear
10 Webelos
between 11 and 13, inclusive Boy Scout
between 14 and 20, inclusive Venture
Example 3
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Which Group</title>
<script>
/* Input: A boy's age
* Processing: If statements to choose a group
* Output: Name of the group
*/
function chooseGroup() {
var age = parseInt(document.getElementById('age'
var group;
if (age < 7) {
group = 'When you are 7 years old, you can become a
}
else if (age == 7) {
group = 'Tiger';
}
else if (age == 8) {
group = 'Wolf';
}
else if (age == 9) {
group = 'Bear';
}
else if (age == 8) {
group = 'Webelos';
}
else if (11 <= age && age <= 13) {
group = 'Boy Scout';
}
else if (14 <= age && age <= 20) {
group = 'Venture';
}
else {
group = 'You are too old to join scouting as a partic
' Perhaps you would like to volunteer as a le
}
document.getElementById('output').innerHTML = group;
}
</script>
</head>
<body>
Please enter your age: <input type="text" id="age" size="3"
<button type="button" onclick="chooseClass()">Class</
<div id="output"></div>
</body>
</html>
Desk Check
81
age group
15
The if statements for Boy Scout and Venture use the logical
And operator and show the correct way to write JavaScript
code that determines if the value in a variable falls within a
range. For example, this is the correct way to write
JavaScript code that determines if a person’s age is between
14 and 20, inclusive.
if (14 <= age && age <= 20) {
Disneyland Autopia
According to the Disneyland website, guests wishing to drive
a car on the Autopia must meet one of the following height
requirements:
Example 4
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Are you tall enough to drive on the Autopia?</
<script>
/* Input: the height of a driver and an optional passenger
* Processing: Determine if a driver and
* optional passenger may ride the Autopia
* Output: "Enjoy the ride!" or
* "Sorry, to drive a car on the Autopia you must be
* at least 54 inches tall or at least 32 inches tall and
* accompanied by a passenger who is at least 54 inches ta
*/
function checkHeight() {
var driver = parseInt(document.getElementById('driverBox'
var passenger = parseInt(document.getElementById
var message;
if (driver >= 54 || (driver >= 32 && passenger >= 54
message = 'Enjoy the ride!';
}
else {
message = 'Sorry, to drive a car on the Autopia you m
'at least 54 inches tall or at least 32 inches ta
'accompanied by a passenger who is at least 54 in
}
document.getElementById('outputDiv').innerHTML = message;
}
</script>
</head>
<body>
<h1>Are you tall enough to drive on the Autopia?</h1
Driver's height in inches:
<input type="text" id="driverBox" size="3"><br>
Passenger's height in inches:
<input type="text" id="passengerBox" size="3" value="0"
<button type="button" onclick="checkHeight()">Check Height</
<div id="outputDiv"></div>
</body>
</html>
Desk Check
driver passenger message
48 56
83
Exclusive Or
It is interesting to consider the English equivalents of each of
the logical operators as shown in the following table.
“Where is Jonas?”
“He is at the library or the soccer field.”
84
Logical Equivalences
A logical expression can be written in many different ways
that resolve to the same result. Two different logical
expressions that resolve to the same result are said to be
equivalent, which is shown with a double ended arrow (⇔).
Two such expressions are not the same and are not equal but
are equivalent. Here is a list of logical expressions with an
equivalent expression for each.
This new if statement works but is a bit sloppy and not very
understandable. You realize that the condition looks like the
left half of De Morgan’s law part b. So, you decide to rewrite
the condition. From De Morgan’s law we see that
Not (a And b) ⇔ Not a Or Not b, so you can rewrite the previous
expression as:
if (!(gpa > 3.5) || !(credits >= 32)) {
document.getElementById('outputDiv').innerHTML =
name + ' is on the average list.';
}
Which can be simplified as:
if (gpa <= 3.5 || credits < 32) {
document.getElementById('outputDiv').innerHTML =
name + ' is on the average list.';
}
86
Advanced Word Search
The logical operators &&, ||, and ! can be used when
searching for documents on your computer or on the
internet. At google and other search engines, this is often
known as advanced search and can be very powerful.
Learning to use advanced search will make you more
efficient when searching for information and will help you
better understand boolean logic.
Example 5
Imagine you are trying to find the web page for every
Madison County in the United States except Idaho. To find
these web pages, you might think of a boolean logic query
such as
madison && (county || parish) && !idaho
87
Example 6
Truth Tables
Truth tables can help us to analyze logic, to write simpler
boolean expressions, and to prove certain propositions about
boolean expressions. We create a truth table by considering
two or more conditions. These can be any conditions, for
example “if (gpa > 3.5)” or “if (balance > 100)”. We label
these conditions a, b, c, etc. Then in the columns beneath
the named conditions (a, b, c, etc.), we write all possible
combinations of false and true. For example, if a boolean
expression includes two conditions, a and b, then
88
Example 7
1 2 3 4 5 6
a b !a !b a && b a || b a^b
False False True True False False False
False True True False False True True
True False False True False True True
True True False False True True False
Example 8
1 2 3 5 4
a b (a || b) && !a
False False False False True
False True True True True
True False True False False
True True True False False
1 2 4 3 5 7
a b ! (a || b) ⇔ !a &&
False False True False True True
False True False True True False
True False False True False False
True True False True False False
90
Example 10
1 2 3 6 5 4
a b (a && b) ^ ! (a || b)
False False False True True False
False True False False False True
True False False False False True
True True True True False True
1 2 3 6 5 4
a b (a && b) ^ ! (a || b)
False False False True True False
False True False False False True
True False False False False True
True True True True False True
91
if ( !(temp < 32 ^ humidity > 0.5) ) {
Example 11
1 2 3 4 5 7
a b c (a || b) || c ⇔ a ||
False False False False False False
False False True False True True
False True False True True True
False True True True True True
True False False True True True
True False True True True True
True True False True True True
True True True True True True
92
Common Mistakes
Forgetting the left-hand side of a second comparison
Incorrect Correct
if (y == 6 || 7) { if (y == 6 || y == 7) {
} }
if (y == (6 || 7)) {
}
if (y == 6, 7) {
}
if (y == (6, 7)) {
}
Forgetting &&
Incorrect Correct
if (10 < x < 20) { if (10 < x && x < 20) {
} }
Correct
// Almost certainly you
// meant to write this:
if (10 < x && x < 20) {
}
// Almost certainly you
// meant to write this:
if (x == 8 || x == 9) {
}
93
Unnecessary Comparisons
Incorrect
if (age < 8) {
}
if (age >= 8 && age < 12) {
}
if (age >= 12 && age < 18) {
}
if (age >= 18) {
}
if (age < 8) {
}
else if (age >= 8 && age < 12) {
}
else if (age >= 12 && age < 18) {
}
else if (age >= 18) {
}
Correct
if (age < 8) {
}
else if (age < 12) {
}
else if (age < 18) {
}
else {
}
Chapter Summary
We can use the logical operators to combine multiple
comparisons in the condition of a single if statement.
The JavaScript logical operators are: Not (!), And (&&),
Inclusive Or (||), and Exclusive Or (^).
Not (!) has a higher precedence than the other logical
operators because it is a unary operator.
The logical operators can also be used in an online
search to refine the results of the search. However, the
logical And operator might not be explicitly written in the
search query but may be implied by a space character.
We can use logical equivalences to rewrite logical
expressions in a way that is shorter or clearer.
We can use a truth table to help us discover and prove
logical equivalences.
DeMorgan’s laws are a group of four logical equivalences
that are commonly used when rewriting logical
expressions that include the Not logical operator.
94
Review Questions
1. The following if statement contains a logic error, not a
syntax error. Rewrite it so that it is correct. Assume the
variable age already exists and holds a valid number.
if (18 < age || age < 30) {
95
Programming Assignments
1. Write a defining table and then a program that reads
from the keyboard a student’s name and number of
completed university credits and then outputs the
student’s name and year in school according to this table.
If you use the above code, the variable month will hold 0
if the current month is January, 1 if February, and so on
to 11 if December. The variable dayOfMonth will hold 1
for the first day of the month up to 28, 29, 30, or 31 for
the last day of the month. The variable dayOfWeek will
hold 0 if today is Sunday, 1 if today is Monday, and so on
to 6 if today is Saturday.
96
if you and your date will be allowed to eat in a fancy
and fashionable restaurant. Your program should read
two integers from the keyboard, one that specifies your
fashion measure from 1 to 10, inclusive and one that
specifies your date’s fashion measure from 1 to 10,
inclusive. If either of your fashion measures is 2 or less,
your program should output “Not a chance”. If either of
your fashion measures is 8 or greater, your program
should output “Welcome”. If your fashion measures sum
to more than 12 your program should output, “Maybe”.
Otherwise, your program should output “Unlikely”.
97
a series of statements by writing a loop in a computer
program. Every loop includes a boolean condition. Each time
the computer needs to decide if it should repeat the
statements inside a loop, the computer evaluates the loop’s
condition. If the condition evaluates to true, then the
computer repeats the statements inside the loop. If the
condition evaluates to false, the computer does not repeat
the inside statements but instead continues executing the
program starting with the statements after the loop.
Chapter Outcomes
By the end of this chapter, you will:
while
Template
while (condition) {
statements;
}
Figure 26 shows a while loop and
the order in which the computer
executes its parts.
Example 1
var i = 1;
while (i < 3) {
// Statements to be repeated go here.
alert(i);
i++;
}
Desk Check
i
99
for
The for loop is a shortened way of writing a counting while
loop. Use a for loop when:
Template
for (initialization; condition; update) {
statements;
}
Figure 27 shows a
for loop and the
order in which
the computer
executes the
statements in the
parentheses and Figure 27: A for loop and the order that the
the body. computer executes its parts.
Example 2
Desk Check
i
Example 3
var i = parseInt(document.getElementById('startInputBox')
for ( ; i <= 5; i++) {
// Statements to be repeated go here.
alert(i);
}
Desk Check
i
4
100
For Each Loop
The for-each loop is a special case of the for loop. The
for-each loop causes the statements inside of it to be
repeated once for each attribute in an object (see
chapter 11). Use a for-each loop when:
Example 4
do while
The do-while loop is the only post-test loop in JavaScript.
The other three loops: while, for, and for-each are pre-
test loops. Use a do-while loop when:
Template
do {
statements;
} while (condition);
101
computer executes its parts.
Example 5
Desk Check
alias response
Example 6
var n = 3;
var i = 0;
while (i < n) {
alert("leaf");
i++;
}
Desk Check
i n
Example 7
var n = 3;
for (var i = 0; i < n; i++) {
alert("caterpillar");
}
Desk Check
i n
102
102
Skipping Loop
Example 8
var skip = 4;
var n = 12;
var i = 0;
while (i < n) {
alert("stem");
i += skip;
}
Desk Check
i skip n
Example 9
var skip = 2;
var n = 5;
for (var i = 0; i < n; i += skip) {
alert("aphid");
}
Desk Check
i skip n
103
Infinite Loop
What does the computer do if a programmer forgets to write
the update part of a loop? For example:
Or this example:
// Warning! This is an infinite loop.
for (var i = 0; i < 5; ) {
alert('Hello');
}
104
Compound Interest
Many bank accounts and other investments pay compound
interest on the money that is saved in the account. This
means each time the bank pays interest, the interest is
added to the original money, which is called the principal.
Then the next time the bank pays interest, it pays interest
on the principal and the previous interest. The balance of
such an account and its compound interest can easily be
computed using a loop.
Example 10
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Compound Interest</title>
<script>
/* Input:
* An amount to invest: balance
* The annual rate of growth: annualRate
* The number of months to invest: numMonths
* Processing: Use a loop to compute the balance of an accoun
* a bank has paid interest for numMonths number of month
* Output: The balance after numMonths have passed.
*/
function futureValue() {
var balance = parseFloat(document.getElementById
var annualRate = parseFloat(document.getElementById
var numMonths = parseInt(document.getElementById
var monthlyRate = annualRate / 12;
// For each month, compute the interest and add it to the
for (var month = 1; month <= numMonths; month++
// Compute the interest for a month.
var interest = balance * monthlyRate;
// Round the interest to pennies.
interest = Math.round(interest * 100) / 100;
// Add the interest to the balance.
balance += interest;
}
// Display the resulting balance for the user to see.
document.getElementById('output').innerHTML =
'Your balance after ' + numMonths + ' months will be
}
</script>
</head>
<body>
Balance: <input type="text" id="balance" size="7"><br
Annual growth rate: <input type="text" id="annualRate"
Number of months: <input type="text" id="months" size="3"
<button type="button" onclick="futureValue()">Future Value</
<div id="output"></div>
</body>
</html>
Desk Check
annualRate monthlyRate numMonths month interest balance
0.06 3 100
105
break
The break keyword causes the computer to end a loop
prematurely. It is normally used inside an if statement that
is inside a loop. Here is a code example that reads 10 or
fewer numbers from a user and computes and outputs the
sum of those numbers. The code stops reading numbers from
the user after 10 numbers or after the user enters zero (0),
whichever comes first.
Example 11
// Gets 10 or fewer numbers from the user and adds them toget
function sum10() {
var sum = 0;
for (var i = 0; i < 10; i++) {
var n = parseFloat(prompt('Please enter a number'));
if (n == 0) {
break;
}
sum += n;
}
alert(sum);
}
Desk Check
i n sum
17
-3
6
0
106
Prime Numbers
A prime number is a positive integer that is evenly divisible
by only two integers, 1 and itself. The numbers 2, 3, 5, and 7
are prime as are 91, 97, and 101. Prime numbers are very
important in computing, for example in hash code algorithms
and data encryption. There are many well know algorithms,
including the sieve of Eratosthenes, for determining if a
number is prime. The following JavaScript code uses a naive
and slow algorithm to determine if a number is prime, but it
works. The code below increments a divisor from 1 to the
candidate number, inclusive and repeatedly divides the
candidate by the divisor. Each time the divisor divides the
candidate without a remainder, then a factor count is
incremented. After the divisor loop is finished, if the factor
count is 2 (1 and the candidate itself), the candidate is
prime, otherwise it is not prime.
Example 12
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Prime Number</title>
<script>
/* Input: an integer
* Processing: determine if the given integer is prime or not
* Output: __ is prime OR __ is not prime
*/
function isPrime() {
var candidate = parseInt(document.getElementById
// Count the number of factors that evenly divide candida
var factorCount = 0;
for (var divisor = 1; divisor <= candidate; divisor++
var remainder = candidate % divisor;
if (remainder == 0) {
factorCount++;
}
}
// Determine the output and show it to the user.
var output;
if (factorCount == 2) {
output = candidate + ' is prime';
}
else {
output = candidate + ' is not prime';
}
document.getElementById('outputDiv').innerHTML = output;
}
</script>
</head>
<body>
Please enter an integer: <input type="text" id="integerBox"
<button type="button" onclick="isPrime()">Is Prime</
<div id="outputDiv"></div>
</body>
</html>
Desk Check
107
108
Example 13
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Prime Number</title>
<script>
/* Input: an integer
* Processing: determine if the given integer is prime or not
* Output: __ is prime OR __ is not prime
*/
function isPrime() {
var candidate = parseInt(document.getElementById
var limit = Math.sqrt(candidate);
var prime = true;
// Find the first integer that evenly divides candidate.
for (var divisor = 2; divisor <= limit; divisor++
var remainder = candidate % divisor;
if (remainder == 0) {
prime = false;
break;
}
}
// Determine the output and show it to the user.
var output;
if (prime) {
output = candidate + ' is prime';
}
else {
output = candidate + ' is not prime';
}
document.getElementById('outputDiv').innerHTML = output;
}
</script>
</head>
<body>
Please enter an integer: <input type="text" id="integerBox"
<button type="button" onclick="isPrime()">Is Prime</button
<div id="outputDiv"></div>
</body>
</html>
Desk Check
candidate limit prime divisor remainder output
8
109
Repetitive Strings
Occasionally we need the computer to produce a string that
has a repeating pattern. We can use a loop to cause the
computer to build such strings. Consider the string
“0, 2, 4, 6, 8, 10” with the simple pattern of counting by twos.
Here is code that builds this string and displays it to the user.
Example 14
Desk Check
i output
Incorrect
var i = 0;
while (i < 3) {
alert("Hello");
}
Correct
var i = 0;
while (i < 3) {
alert("Hello");
i++;
}
// or
for (var i = 0; i < 3; i++) {
alert("Hello");
}
Incorrect
for (var i = 0; i > 3; i++) {
}
Correct
for (var i = 0; i < 3; i++) {
}
// or
for (var i= 0; i != 3; i++) {
}
Incorrect
for (var i = 0, i < 5, i++) {
}
Correct
for (var i = 0; i < 5; i++) {
}
Incorrect
for (var i = 0; i < n; i++)
interest = balance * rate;
balance += interest;
Correct
for (var i = 0; i < n; i++) {
interest = balance * rate;
balance += interest;
}
Incorrect
var i = 0;
while (i < 3); {
alert("Hello");
i++;
}
for (var i = 0; i < 3; i++); {
alert("Hello");
}
Correct
var i = 0;
while (i < 3) {
alert("Hello");
i++;
}
for (var i = 0; i < 3; i++) {
alert("Hello");
}
Review Questions
1. Given the following JavaScript code, how many times will
the computer display the word "Flowers"?
for (var i = 3; i < 7; i++) {
alert("Flowers");
}
112
times will the computer display the word "Snow"?
var i = 0;
while (i < 3) {
alert("Snow");
}
11. Desk check the following code and then write a sentence
describing what the code does.
function func1() {
var c = "";
var a = parseInt(document.getElementById('integerBox').v
var b = 100;
while (b >= 0) {
c += b + "<br>";
b -= a;
}
document.getElementById('outputDiv').innerHTML = c;
}
Desk Check
a b c
20
113
sentence describing what the code does. How does
this code differ from the code in the previous example?
Hint: consider the indentation of the statements in the
previous example compared to the indentation of the
statements in this example. Which example is easier to
read and desk check?
function func2() {
var c = "";
var a = parseInt(document.getElementById('integerBox'
var b = 100;
while (b >= 0) {
c += b + "<br>";
b -= a;
}
document.getElementById('outputDiv').innerHTML = c;
}
Desk Check
a b c
20
13. Desk check the following code and then write a sentence
describing what the code does. How does this code differ
from the code in the previous two examples?
function countDown() {
var output = "";
var skip = parseInt(document.getElementById('integerB
var i = 100;
while (i >= 0) {
output += i + "<br>";
i -= skip;
}
document.getElementById('outputDiv').innerHTML = outp
}
Desk Check
skip i output
20
14. Desk check the following code and then write a
114
sentence describing what the code does.
function func4() {
var d = "Please enter an integer.";
var b = 38;
var c;
do {
c = parseInt(prompt(d));
if (c < b) {
d = "Too low. Please enter another integer.";
}
else if (c > b) {
d = "Too high. Please enter another integer.";
}
} while (c != b);
d = c + " is correct!";
alert(d);
}
Desk Check
b c d
15. Desk check the following code and then write a sentence
describing what the code does. How does this code differ
from the code in the previous example? Hint: consider
the indentation of the statements in the previous
example compared to the indentation of the statements
in this example. Which example is easier to read and
desk check?
function func5() {
var d = "Please enter an integer.";
var b = 38;
var c;
do {
c = parseInt(prompt(d));
if (c < b) {
d = "Too low. Please enter another integer.";
}
else if (c > b) {
d = "Too high. Please enter another integer."
}
} while (c != b);
d = c + " is correct!";
alert(d);
}
Desk Check
b c d
115
sentence describing what the code does. How does
this code differ from the code in the previous two
examples?
function numberGuessGame() {
var message =
"I'm thinking of a number between 1 and 100.\n" +
"Try to guess it!\n" +
"Please enter an integer between 1 and 100.";
var answer = 38;
var guess;
do {
guess = parseInt(prompt(message));
if (guess < answer) {
message = guess +
" is too low. Please enter another integer.";
}
else if (guess > answer) {
message = guess +
" is too high. Please enter another integer."
}
} while (guess != answer);
message = guess + " is correct!";
alert(message);
}
Desk Check
answer guess message
Programming Assignments
1. Write a defining table and program that reads an integer
n from the keyboard and then displays the word
“sunshine” n times in a div.
116
five times table from 1 to 12 in this format:
5x1=5
5 x 2 = 10
…
5 x 12 = 60
117
computer programmers divide their programs into parts.
A part of a program is called a module. In JavaScript the
smallest module that performs actions is a function, which is
sometimes called a method. Nearly all statements in a
JavaScript program must be written inside a function.
Chapter Outcomes
By the end of this chapter, you will:
Writing a Function
To write a function in JavaScript, simply type code that
matches this template.
Template
Example 1
Example 2
Example 3
Example 4
119
Calling a Function
Calling or invoking a function causes the computer to
execute the code in that function. If you write a function, but
never write a call to that function, then the code in that
function will never be executed. To call a function, simply
write its name followed by the data, known as arguments,
which the function will need to perform its task. An argument
can be a constant such as 23, a string literal such as
'Idaho', or a variable. If you use variables as arguments in
a function call, the names of the arguments do not have to
match the names of the parameters. However, the order of
the arguments must match the order of the parameters.
Template
Example 5
Write the code to call a function that has this header:
function drawCircle(centerX, centerY, radius)
function run() {
var x = parseInt(document.getElementById('xInputBox').va
var y = parseInt(document.getElementById('yInputBox').va
var radius = parseFloat(document.getElementById('radiusI
drawCircle(x, y, radius);
}
Example 6
Template
Example 7
Write code to call the square root function found in the Math
object and assign the result returned from it to a variable
named rt. The square root function has this header:
function sqrt(x)
function testSqrt() {
var value = 73.1;
var rt = Math.sqrt(value);
document.getElementById('outputDiv').innerHTML = rt;
}
Example 8
121
Variable Scope
The scope of a variable determines how long that variable
exists and where it can be used. Within a JavaScript
program, there are two categories of scope: local and global.
A local variable is declared inside a function, exists for as
long as its containing function is executing, and can be used
within its containing function only. A global variable is
declared outside all functions, exists for as long as its
containing file is loaded in the computer’s memory, and can
be used within all functions in its containing file. Parameters
are local variables because they are declared within a
function, specifically within a function’s header.
Example 9
var attempts;
function squareArea(length) {
var area = length * length;
return area;
}
function rectangleArea(width, length) {
var area = width * length;
return area;
}
122
Advantages of Functions
There are many advantages to writing statements inside a
function instead of outside of all functions, including
Example 10
Desk Check
value returned
min max from Math.random r
5 11 0.483 123
Code Reuse
The most reusable functions are ones that perform only
calculations and do not perform user input and output.
Chapter 6 contains code to determine if an integer is even or
odd. Examples 11 and 12 both contain the example code
from chapter six. However, in both examples 11 and 12, the
example code is split into two functions: doInputOutput and
isEven. The first function, doInputOutput, gets the user
input, calls the second function, and displays the result to
the user. The first function is certainly useful in this program
but is not reusable in another program because it requires a
text field with an id of “number” and a div with an id of
“output”. The second function, isEven, does only one thing:
determine if an integer is even or odd. Because the second
function does only calculations (it does not get user input nor
display results to the user), the second function is reusable
in other programs. The second function can be used in any
program that needs to determine if an integer is even or odd
regardless of where the input comes from, such as a user or
a file or anywhere else.
Example 11
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Is Even</title>
<script>
/* Input: An integer
* Processing: Determine if the integer is even or not
* Output: A message stating if the integer is even or not
*/
function doInputOutput() {
var number = parseInt(document.getElementById('numberInpu
var result = isEven(number);
document.getElementById('outputDiv').innerHTML =
number + ' is even: ' + result;
}
Desk Check
number result
8
// Returns true if value is an even
// integer; otherwise returns false.
function isEven(value) {
if ((value % 2) == 0) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
Please enter an integer: <input type="text" id="numberInputBo
<button type="button" onclick="doInputOutput()">Is Even?</
<div id="outputDiv"></div>
</body>
</html>
124
we can write it without the if statement. Eliminating
the if statement makes the function easier to test because
the function will contain only one possible path of execution
instead of two.
Example 12
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Is Even</title>
<script>
/* Input: An integer
* Processing: Determine if the integer is even or not
* Output: A message stating if the integer is even or not
*/
function doInputOutput() {
var number = parseInt(document.getElementById('numberInpu
var result = isEven(number);
document.getElementById('outputDiv').innerHTML =
number + ' is even: ' + result;
}
Desk Check
number result
8
// Returns true if value is an even
// integer; otherwise returns false.
function isEven(value) {
return (value % 2) == 0;
}
</script>
</head>
<body>
Please enter an integer: <input type="text" id="numberInputBo
<button type="button" onclick="doInputOutput()">Is Even?</
<div id="outputDiv"></div>
</body>
</html> 125
Area of a Triangle
If we know the side lengths of a
triangle as shown in figure 31, then
we can compute the area of that
triangle using Heron’s formula
which is Figure 31: An irregular
triangle with side lengths
area = √s(s−a)(s−b)(s−c) a, b, and c.
s=a+b+c
2
Example 13
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Triangle Area</title>
<script>
/* Input: No user input
* Processing: Compute the area of a triangle
* with side lengths 4, 2, and 5
* Output: The area of the triangle
*/
function testTriangle() {
var r = triangleArea(4, 2, 5);
document.getElementById('outputDiv').innerHTML = r;
}
Desk Check
r
</script>
</head>
<body>
<button type="button" onclick="testTriangle()">Test</
<div id="outputDiv"></div>
</body>
</html>
126
Surface Area of a Pyramid
Imagine designing one of the great pyramids. The stones on
the inside of the pyramids are very rough and are basically
just filler. The stones on the outside are finished smooth to
reflect sunlight. If you were writing the software to design a
pyramid, your software would have to compute the surface
area of a pyramid so the builders would know how much
finished stone they need to cover the outside of the pyramid.
2
e = / b + h 2
√ 2
127
Example 14
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Surface Area of a Pyramid</title>
<script>
/* Input: No user input
* Processing: Compute the surface area of the
* triangular faces of a regular pyramid
* that has base 8 and height 7.
* Output: The surface area of the pyramid
*/
function testPyramid() {
var pa = pyramidSurfaceArea(8, 7);
document.getElementById('outputDiv').innerHTML = pa;
}
Desk Check
pa
a b c s (s − a) (s − b) (s − c) area
</script>
</head>
<body>
<button type="button" onclick="testPyramid()">Test</
<div id="outputDiv"></div>
</body>
</html>
128
How Long to Invest
Example 15
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>How Long to Invest</title>
<script>
/* Input: No user input
* Processing: Determine the number of months required
* to grow an initial investment from $100 to at
* least $103 if it grows at an annual rate of 6%.
* Output: The number of months.
*/
function testInvest() {
var m = determineMonths(100, 0.06, 103);
document.getElementById('outputDiv').innerHTML = m;
}
Desk Check
m
</script>
</head>
<body>
<button type="button" onclick="testInvest()">Test</button
<div id="outputDiv"></div>
</body>
</html>
129
Greatest Common Divisor
The greatest common divisor (gcd) of two non-zero integers
is the largest positive integer that divides both numbers
without a remainder. An efficient algorithm to compute the
gcd was discovered by Euclid and works like this. Given two
integers, 102 and 18,
130
Example 16
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Greatest Common Divisor</title>
<script>
/* Input: No user input
* Processing: Determine the greatest common divisor of -24 a
* Output: The greatest common divisor
*/
function testGCD() {
var x = -24;
var y = 472;
var divisor = gcd(x, y);
document.getElementById('outputDiv').innerHTML = divisor;
}
Desk Check
x y divisor
return a;
}
r a b swap
</script>
</head>
<body>
<button type="button" onclick="testGCD()">Test</button
<div id="outputDiv"></div>
</body>
</html>
131
Common Mistakes
Putting a space in a function’s name
Incorrect
function check Answer() {
}
Correct
function checkAnswer() {
}
Incorrect Correct
function sum(x, y, z) { function sum(x, y, z) {
var s = x + y + z; var s = x + y + z;
return s; return s;
}
Incorrect
function getDiscountRate(birthday, gpa) {
// Wrong! Don't re-declare nor assign parameters.
var birthday = new Date("3/17/1995");
var gpa = prompt("What is your GPA?");
132
output is done by calling alert, document.write, or
assigning a value to the innerHTML attribute of a div
(document.getElementById('resultDiv').innerHTML = x;).
Chapter Summary
A module is a part of a program. The term module can
refer to a very large part of a program, including many
files and functions, or it can refer to a small part of a
program such as a single function.
A function is the smallest part of a program that
performs actions and is sometimes called a method. A
well written function is a reusable part of a program that
performs one task such as calculating the average of a
list of numbers or the area of a triangle.
A function has a header and a body. The header is also
known as the signature.
The header of a function includes the function’s
parameters. Each parameter is a variable.
A call point of a function is a line of code in a program
where that function is called or invoked. The values for a
function’s parameters come from a call point of that
function.
The body of a function includes all the statements to
perform a single task such as a calculation. The body
normally ends with a return statement to return a
calculated value to the call point.
A return statement causes a computer to stop executing
the current function, to return a value to the call point of
the current function, and to resume executing the code
at or after the call point.
To call a function, write the function’s name followed by
the arguments that the function will need to perform its
task.
An argument is the value or variable that is passed from
the call point into a function.
To store the value returned from a function write a
variable name and the assignment operator (=) at the
call point of the function.
Review Questions
1. Within a function header, for example:
function gcd(a, b) {
133
computeFutureValue, which takes as parameters
three numbers named principal, annualRate, and
years.
Programming Assignments
1. Rewrite the number guessing game code found in review
question 16 of chapter 8 so that it
a. is inside a function with this header:
function numberGuessGame()
134
fields, a button, and a div. Label the first text field
“Temperature”, label the second “Wind Speed”, and put
the text “Wind Chill” on the button. Write two functions
with these headers:
function doInputOutput()
function windChill(tempF, speed)
135
fields, a button, and a div. Label the first text field
“Temperature”, label the second “Relative Humidity”, and
put the text “Heat Index” on the button. Write two
functions with these headers:
function doInputOutput()
function heatIndex(tempF, humid)
136
triangular prism can be calculated by multiplying
the area of the triangular face by the length of the prism.
In other words
137
roof space of the house is a triangular prism and the
living space of the house is a rectangular prism. Write a
program that calculates the total volume of the house,
including the volume of the roof space. Your program
must allow the user to enter the width, depth, height,
and sweep as shown in figure 34. Here are some useful
formulas:
triangleArea = √s(s−a)(s−b)(s−c)
Figure 34: A simple house
s=a+b+c
2
a. takes no parameters
b. is called from the onclick attribute
c. gets four numbers from the user
d. calls the houseVolume function
e. displays the house volume to the user
138
figure 35. Write two functions with these headers:
function doFV()
function computeFutureValue(principal, annualRate, years,
a. takes no parameters
b. is called from the onclick attribute
c. gets input from the user
d. calls the computeFutureValue function
e. displays the result to the user
139
figure 36. Write four functions with these headers:
function doPayment()
function doBalance()
function computePayment(principal, annualRate, years, per
function computeBalance(principal, annualRate, years, per
numberOfPaymentsPaidToDate)
a. take no parameters
b. are called from an onclick attribute
c. get input from the user
d. call the computePayment or the computeBalance
function
e. display a result to the user
p= ar
1 − (1 + r)−n
141
has the same data type, for example, an array of
integers or an array of Student objects. Each variable in an
array is called an element and has a unique index, also
called the subscript, which denotes that element’s location
within the array. One advantage of using arrays is that all
the elements within an array can be declared, created, or
passed to a function as a whole. However, each element may
still be accessed individually by using the element’s index.
Figure 37 shows a representation of an array with 10
elements. Notice that each element has a unique index, and
in JavaScript, indexes are always non-negative integers with
0 as the first index.
elements
indexes [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
← array length is 10 →
Figure 37: A representation of an array showing the elements and
indexes.
Chapter Outcomes
By the end of this chapter, you will be able to:
Template
var arrayName;
Example 1
var data;
var scores;
142
Creating an Array
Declaring an array in JavaScript does not cause the computer
to reserve space for the elements of the array. To do this, a
programmer must also create the array. All objects, including
arrays, are created in JavaScript using the keyword new.
Template
Example 2
Example 3
Example 4
Template
Example 5
Example 6
Template
arrayName.length
Example 7
Accessing an Element
To access a single element within an array, either to read or
to write the element’s value, simply write the name of the
array followed by the index of the element in brackets. In
JavaScript, an index is always a non-negative integer, and
the very first index is always 0. An index is never a fractional
number because it doesn’t make sense to ask what is stored
in an array at a fractional index, for example 3.8. There is a
value stored at index 3 and a value stored at index 4 but
nothing stored at index 3.8.
Template
arrayName[index]
Example 8
Example 9
144
Filling an Array
It is often desirable to have the computer initialize all the
elements in an array to some value (usually zero). We do
this by writing a statement that assigns a value to one
element in the array, and then put that assignment
statement inside a loop. If the array has n elements in it,
then the loop causes the computer to repeat the assignment
statement n times, once for each element in the array.
Example 10
Desk Check
list x i
8.3
[0] [1] [2] [3]
145
Filling an Array with a Ramp
Within programs that perform image processing, we often
use an array as a palette or look up table. To get the color
value of a pixel, the computer reads the value of the pixel
stored in the image and then looks up that value in the
palette. Then the computer displays the color from the
palette at the corresponding pixel location on the monitor.
Often the palette must be initialized to contain values that
are constantly increasing, for example: 0, 1, 2, 3… This is
known as a ramp
because if you plotted
the values in the
array, you would see
a sloping line or
ramp, constantly
increasing to the
right as shown in
Figure 38.
Here is a code
example showing how
to initialize an array
to an increasing
ramp. Figure 38: A plot of constantly increasing
values forming a ramp.
Example 11
Desk Check
list i
Example 12
Desk Check
list high i
Example 13
Desk Check
list left right swap
3.4 −2 5 7 12
Example 14
Desk Check
list i s
3.4 −2 5 7 12
[0] [1] [2] [3] [4]
148
Finding a Value (Linear Search)
Very often a computer program must determine if a certain
value is stored in an array or not and if stored in the array,
then return the value’s location. The value to be found is
called the key. If the array is not too large (perhaps less
than 100 elements), finding the key can be easily done using
a linear search. A linear search is done by comparing each
element in the array with the key until the key is found in
the array or the end of the array is reached.
Example 15
Desk Check
list key i return
28.1 20 23.6 0 15 23.6
[0] [1] [2] [3] [4]
Parallel Arrays
Parallel arrays are two or more arrays that contain
corresponding values. For example, an array of student IDs
and an array of corresponding student names are parallel
arrays. Consider this student data.
Example 16
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Student ID to Name</title>
<script>
// The values in these parallel arrays can be hard coded into
// program, or even better, they can be read from a file or d
var studentIDs = [ '07-153-4276', '34-513-3186', '26-430-0198
var studentNames = [ 'Felix', 'Jonathan', 'Grace' ];
/* Input: a student's ID
* Processing: find the student's name
* Output: the student's name
*/
function findName() {
// Get the student's ID.
var studID = document.getElementById('studID').value;
// Use linear search to find the student's ID.
var index = linearSearch(studentIDs, studID);
var name;
if (index == -1) {
// The student ID that the user entered
// is not stored in the studentIDs array.
name = 'No such student ID';
}
else {
// Get the student's name.
name = studentNames[index];
}
// Display the student's name for the user to see.
document.getElementById('output').innerHTML = name;
}
Desk Check
studentIDs
'07-153-4276' '34-513-3186' '26-430-0198'
[0] [1] [2]
studentNames
'Felix' 'Jonathan' 'Grace'
[0] [1] [2]
150
// key is located within list; otherwise returns -1.
function linearSearch(list, key) {
var index = -1;
for (var i = 0; i < list.length; i++) {
if (list[i] == key) {
index = i;
break;
}
}
return index;
}
key i index
</script>
</head>
<body>
Student ID: <input type="text" id="studID">
<button type="button" onclick="findName()">Name</button
<div id="output"></div>
</body>
</html>
Finding a Range
Example 17
Desk Check
purchase rate discount return
$708.00
Example 18
Desk Check
purchase rate discount return
$708.00
152
The problem with both these solutions is that if the
company changes the purchase amount ranges or the
discount rates, then a programmer must change the
corresponding code. An improved solution is to remove the
ranges and rates from the code and place them in a file or
database so that the computer can read them into two
parallel arrays when it runs the program. Then the
programmer must write a simple linear search method to find
the correct range and the corresponding discount rate as
shown in the next example.
Example 19
Desk Check
limits rates
300 600 1000 0 0.02 0.025 0.03
[0] [1] [2] [0] [1] [2] [3]
Example 20
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Compute Total</title>
<script>
/* Input: The subtotal for a customer's purchases
* Processing: Compute a discounted amount and sales tax and
* them together to get the total amount that the custome
* Output: The total that the customer owes.
*/
function computeTotal() {
// Get the subtotal from the user.
var subtotal = parseFloat(document.getElementById
// Compute the customer's total.
var discounted = getDiscountedAmount(subtotal);
var tax = getSalesTax(discounted);
var total = discounted + tax;
154
155
Example 21
If the key is not present in the array, the return value of the
binary search function above is -insertPoint - 1. In other
words, if the key is not present in the array, the index where
key should be inserted can be found using this code:
var index = binarySearch(list, key);
if (index < 0) {
var insertPoint = -index - 1;
}
156
computes mid needs some explanation. Here is the
statement:
The right shift operator (>>>) shifts all the bits in an integer
to the right which is the same as using integer division to
divide a non-negative integer by a power of two. However,
the right shift operator executes faster than division. To help
us understand the statement, we can rewrite it by replacing
>>> 1 with / 2.
mid = left + Math.floor((right - left) / 2);
Notice that this statement uses the Math.floor function to
truncate (not round) the result of the division. Also, notice
that if this were an algebraic expression, it could be
simplified to
mid = Math.floor((left + right) / 2);
Array Methods
JavaScript includes several useful methods that you can use
to manipulate the contents of arrays. Many of these methods
are listed in the next table. When calling these methods, a
programmer must write the name of the array in front of the
method name as shown in this template.
Template
Array Methods
Method Description
a.concat(item1, item2, …) Returns a
new array
composed of
the original
array and the
argument
arrays or
values.
a.every(func, thisArg) Returns true
if a test
function
returns true
for every
element in
an array.
a.filter(func, thisArg) Returns a
new array
that contains
all elements
that passed a
test function.
a.forEach(func, thisArg) Calls a
function once
for each
element in
an array.
a.indexOf(toFind, start) Returns the
index within
the array a
of the first
occurrence of
the element
toFind, or −1
if not found.
a.join(separator) Joins all
elements of
an array into
a string.
a.lastIndexOf(toFind, start) Returns
157
157
the index
within the
array a of
the last
occurrence of
the element
toFind, or −1
if not found.
a.map(func, thisArg) Returns a
new array
that contains
the results of
calling a
function on
every
element in
an array.
a.pop() Removes and
returns the
last element
from an
array.
a.push(item1, item2, …) Adds one or
more
elements to
the end of an
array.
a.reduce(func, thisArg) Returns an
accumulated
value
produced by
calling a
function on
every
element in
an array.
a.reverse() Reverses the
elements in
an array.
a.shift() Removes and
returns the
first element
from an
array.
a.slice(start, end) Returns a
new array
that is a copy
of elements
between
[start, end).
a.some(func, thisArg) Returns true
if a test
function
returns true
for at least
one element
in an array.
a.sort(compareFunc) Sorts the
elements of
an array in
place.
a.toString() Returns a
string
representing
an array.
a.splice(start, count, item1, item2, …) Removes and
adds
elements to
an array.
a.unshift(item1, item2, …) Adds one or
more
elements to
the
beginning of
an array.
Sorting an Array
The best way to sort an array is to use the sort functionality
provided by the programming language you are using
because that built-in sorting functionality has been optimized
and tested. JavaScript includes built-in sort functionality,
which is in the Array object. Shown below is JavaScript code
to sort an array using the built-in functionality.
var vegetables = [ "Radish", "Carrot", "Tomato", "Pea" ];
vegetables.sort();
Example 22
The
next
159
Example 23
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="author" content="Rex Barzee">
<title>Sort Text</title>
<script>
/* Input: A list of text items, each item on a separate line.
* Processing:
* Split the text items into an array.
* Sort the array.
* Join the array into a string.
* Output: The sorted list of text items
*/
function process() {
// Get the text entered by the user.
var text = document.getElementById('input').value;
// Split the text at each new
// line into an array of strings.
var list = text.split('\n');
// Sort the array of strings.
list.sort();
// Join the sorted array into a string
// of text separated by newline characters.
var output = list.join('\n');
// Display the string for the user to see.
document.getElementById('output').value = output;
}
</script>
</head>
<body>
<textarea id="input" rows="16" cols="20"></textarea>
<button type="button" onclick="process()">Sort</button
<textarea id="output" rows="16" cols="20"></textarea
</body>
</html>
160
Sorting Numbers
By default, the built-in sort function in JavaScript sorts
arrays lexicographically which essentially means
alphabetically. This causes problems if you wish to sort an
array of numbers. For example, this code will sort the
numbers array in a surprising way.
var numbers = [ 7, 10, 8, 16, 3, 35 ];
// WARNING: this will sort the numbers array
// lexicographically and not numerically.
numbers.sort();
Example 24
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Compound Interest</title>
<script>
/* Input: No user input
* Processing: Test the built-in JavaScript sort function
* Output: The contents of an array before it is
* sorted, and the contents after it is sorted.
*/
function testSort() {
var numbers = [ 7, 10, 8, 16, 3, 35 ];
document.getElementById('output').innerHTML = numbers +
numbers.sort(compareNumbers);
document.getElementById('output').innerHTML += numbers;
}
// Compares two numbers by subtracting the second
// from the first which will return a negative
// number if the first number should be placed
// before the second, a zero if the two numbers
// are equal, and a positive number if the first
// number should be placed after the second.
function compareNumbers(x, y) {
return x - y;
}
</script>
</head>
<body>
<button type="button" onclick="testSort()">Sort an Array</
<div id="output"></div>
</body>
</html>
Example 25
Desk Check
list first i swap j last
6 −8 9 7 0
6 −8 9
6 −8
6 0 7 9
7 9
[0] [1] [2] [3] [4]
162
Common Mistakes
Forgetting that the first index in a JavaScript array is
always 0
Incorrect
for (var i = 1; i < a.length; i++) {
a[i] = 0;
}
Correct
for (var i = 0; i < a.length; i++) {
a[i] = 0;
}
Incorrect
for (var i = 0; i <= a.length; i++) {
a[i] = 0;
}
Correct
for (var i = 0; i < a.length; i++) {
a[i] = 0;
}
Correct
var sum = 0;
for (var i = 0; i < a.length; i++) {
// Right. a[i] is the value stored at index i.
// This code adds the values that are stored
// in the array.
sum += a[i];
}
163
Chapter Summary
An array is a collection of variables. Each variable in an
array is called an element and has a unique index which
denotes that element’s location within the array
To declare an array, use the keyword var.
To create an array which will reserve space in main
memory for the elements of the array, write code that
uses the keywords new and Array, like this template:
arrayName = new Array(size);
164
Review Questions
1. Given the following JavaScript statement what is the
index of the last element in the stuff array?
var stuff = [ 13, -1.8, 20, 6.3 ];
Programming Assignments
1. Write a function that creates and returns an array that
contains the values: 1908, 5, 10. The function must have
this header:
function mothersDay()
2. Write a function that returns the sum of the first and last
values in an array. The function must have this header:
function addEnds(list)
165
value of the middle element in an array. If the array
has an even number of elements, then this function must
return the average of the two middle elements. The
function must have this header:
function getMiddle(list)
function rotateLeft(list)
function chooseNoun()
function chooseVerb()
function chooseAdjective()
function chooseAdverb()
function chooseInteger()
168
button. Write a
JavaScript
program that
will
a. read all
the text
from the
first text
area,
b. split the
text into
numbers in
an array,
c. sort the
array
numerically, and
d. display the sorted numbers in the second text area.
169
the cards in a deck Rook cards.
var cards = [
"Green 1", "Green 2", "Green 3", "Green 4", "Green 5"
"Green 6", "Green 7", "Green 8", "Green 9", "Green 10
"Green 11", "Green 12", "Green 13", "Green 14",
"Yellow 1", "Yellow 2", "Yellow 3", "Yellow 4", "Yell
"Yellow 6", "Yellow 7", "Yellow 8", "Yellow 9", "Yell
"Yellow 11", "Yellow 12", "Yellow 13", "Yellow 14",
"Black 1", "Black 2", "Black 3", "Black 4", "Black 5"
"Black 6", "Black 7", "Black 8", "Black 9", "Black 10
"Black 11", "Black 12", "Black 13", "Black 14",
"Red 1", "Red 2", "Red 3", "Red 4", "Red 5",
"Red 6", "Red 7", "Red 8", "Red 9", "Red 10",
"Red 11", "Red 12", "Red 13", "Red 14", "Rook Bird"
];
171
difficult for the programmer to keep all the code
organized. One way to keep the code in a large program
organized is to use object oriented programming. Object
oriented programming is a way of viewing the world and
designing and implementing software that matches the
world.
Chapter Outcomes
By the end of this chapter, you will:
Identity
a unique name or identification number
Data
These are characteristics of an object and are usually
adjectives. These are also called attributes, properties,
characteristics, fields, instance variables, or structure.
Behavior
These are the things that an object does and usually
verbs. These are also called methods, operations,
functions, or procedures.
Relationships
links or connections between objects
172
Relationships
There are several different relationships that can exist
between objects or classes. Relationships between classes are
shown as different types of lines connected to the classes.
Aggregation
A relationship between two objects such that one object
contains the other object. This is sometimes called a
whole‑part relationship. In order to use aggregation
between two objects whole and part, one of these English
phrases must make sense: whole contains part or whole
has a part. The UML symbol for aggregation is a solid line
with an unfilled diamond connected to the containing
class:
Composition
A relationship between two objects such that one object
contains the other object and the contained object may
not be shared. This is also a whole‑part relationship and
is a strong form of aggregation. In order to use
composition between two objects whole and part, one of
these English phrases must make sense: whole contains
part or whole has a part. The UML symbol for aggregation
is a solid line with a filled diamond connected to the
containing class:
Inheritance
173
A relationship between two classes that causes the
child class to automatically have everything (data,
behavior, and relationships) that the parent class has. In
order to use inheritance between two objects parent and
child, one of these English phrases must make sense:
child is a kind of parent or child is a parent. The UML
symbol for inheritance is a solid line with an unfilled
triangle connected to the parent class:
Dependency
A relationship between two objects such that one object
requires or uses the other object to accomplish a task. In
order to use dependency between two objects x and y,
one of these English phrases must make sense: x uses
y, x requires y, or x needs y. The UML symbol for
dependency is a dashed line with an open arrow head
connected to the required or needed class:
Association
A general relationship between objects. When two
objects are related but the relationship is not
aggregation, composition, inheritance, or dependency,
then use association. The UML symbol for association is a
solid line:
Multiplicities
Multiplicities are
small numbers and
punctuation at one or
both ends of a Figure 42: A UML class diagram showing
relationship that two classes with multiplicities.
constrain the
relationship. A single number multiplicity constrains a
relationship to exactly that number of objects. Two or more
numbers separated by commas constrain a relationship to
exactly one of those numbers of objects. Two numbers
separated by two periods (..) constrain a relationship to a
range of objects. For example, multiplicities may be used to
show that one egg carton has either 12 or 18 eggs inside it
as shown in figure 42.
Multiplicity Examples
Multiplicity Meaning
1 Exactly one
4,8 Exactly four or exactly eight
0,1 Zero or one, also known as optional
0..1 Zero or one, also known as optional
12..18 Between 12 and 18 inclusive
0..* Zero or more
* Zero or more
1..* One or more, also known as at least one
3..* Three or more, also known as at least three
174
Example 1
Example 2
Figure 44: Elements of the JavaScript language and the relationships among
those elements.
176
Declaring an Object
Just like a variable must be declared before it can be used in
a program, an object must also be declared. To declare an
object in JavaScript, a programmer writes the keyword var
followed by the object’s name, exactly the same as declaring
a variable.
Template
var objName, objName2, … objNameN;
Example 3
var now;
var s;
Creating an Object
Template
Example 4
Example 5
Template
Example 6
student : Object
firstName = 'Samuel'
address = '125 W Main'
height = 1.78
Figure 45: A UML object
diagram showing one object.
Accessing an Attribute
To access an attribute of an object, either to write or to read
the attribute’s value, simply write the name of the object
followed by a period (.) followed by the name of the
attribute.
Template
objectName.attributeName
Example 7
178
Calling a Method
A method is a function that is part of an object. To call a
method, simply write the name of the object, a period (.),
the name of the method, and an argument list.
Template
Example 8
Dictionaries
Because JavaScript stores attributes in objects as name
value pairs, a programmer can use a JavaScript object as a
dictionary. A dictionary is a collection of key value pairs
where each key appears only once. A computer can insert
and remove key value pairs from a dictionary and can search
a dictionary very quickly. A dictionary is sometimes called an
associative array or a map. One example of a program that
could use a dictionary is a program that finds a student’s
name by using her student ID. Example 16 in chapter 10
solves this problem using parallel arrays. The following
example solves the same problem using an object as a
dictionary.
179
Example 9
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Student ID to Name</title>
<script>
// The values in this dictionary can be hard coded into a pro
// or even better, they can be read from a file or database.
var students = {
'07-153-4276' : 'Felix',
'34-513-3186' : 'Jonathan',
'26-430-0198' : 'Grace'
};
/* Input: a student's ID
* Processing: find the student's name
* Output: the student's name
*/
function findName() {
// Get the student's ID.
var studID = document.getElementById('studID').value;
// Find the student's name in the dictionary of students.
var name = students[studID];
if (!name) {
// The student ID that the user entered
// is not stored in the students array.
name = 'No such student ID';
}
Local Storage
Sometimes a programmer needs to store data that persists
after a program finishes. One way to do this in JavaScript is
to use local storage. localStorage is a built-in JavaScript
object that holds data after a program finishes and even
after a user closes the browser. To store a value in local
storage, a programmer simply adds an attribute to the
localStorage object.
Template
localStorage.attributeName = value;
Template
181
Document Object Model
JavaScript was developed so that HTML pages could be
interactive, meaning that they could change as a user moved
her mouse pointer and clicked the mouse buttons and typed
keys. The developers of the JavaScript language also
developed the HTML document object model (DOM). The
DOM is the list of all the objects and their attributes and
methods that a programmer can use to make an HTML
document interactive.
Example 11
184
diagramming language that enables a software
developer to draw classes and objects.
JavaScript includes several prototype objects including
Array, Boolean, Date, Number, String, and RegExp, that
a programmer can use to create new objects.
To create a JavaScript object use the new keyword and
the name of the prototype object:
var objectName = new PrototypeName();
Review Questions
1. Write JavaScript code to declare and create a Number
object named fifty that holds the value 50.
185
Programming Assignments
1. Write a program that allows a user to enter a date in the
format YYYY/MM/DD (a four digit year, a slash, a two digit
month, a slash, and a two digit day of the month). Your
program should output the name of the day of the week
for that date. For example, if the user entered
“2016/05/22”, your program would output “Sunday”.
Hint: your program should create a Date object and use
the method Date.getDay().
187
string of text or a group of characters strung together.
When writing JavaScript code, a good way to visualize a
string is as an array of individual characters inside an object
with 0 as the index of the first character.
Chapter Outcomes
By the end of this chapter, you will be able to:
Creating a String
To create a string you can use a string literal inside single (')
or double (") quotes or the new keyword.
Templates
Example 1
Example 2
var x = 3;
var s = new String(x);
String Concatenation
To create a large string of text from smaller strings of text
you can use the string concatenation operator which is the
plus symbol (+). For example:
Example 3
Escape Sequences
Occasionally you will want to include single or double quotes
or other special characters in a string literal. You can include
a special character by placing a backslash character (\)
immediately before it. Within a string literal, a backslash
followed by one or more characters is called an escape
sequence. You can also write escape sequences to include
Unicode characters in a string literal that you would not be
able to type from your keyboard. This includes mathematical
symbols and characters from languages other than English.
Example 4
Example 5
Template
name.length
Example 6
Accessing a Character
Just like an array, you can use the bracket operators ([ and
]) to retrieve a single character from a string. Also just like
an array, the index of the very first character in a string is 0.
Template
Example 7
190
Reversing a String
Occasionally you will want to reverse the order of the
characters in a string. This is easily done with a loop and
string concatenation.
Example 9
Desk Check
s i rev
'pool'
Comparing Strings
To compare strings in JavaScript, you can use the relational
operators (<, >, <=, >=, ==, and !=) just as you would for
numbers.
Example 10
function compareStrings() {
var a = 'always';
var b = 'believe';
var c = 'always';
var output;
if (a < b) {
output = a + ' is less than ' + b + '. ';
}
else {
output = a + ' is equal or greater than ' + b + '. ';
}
if (a == c) {
output += a + ' equals ' + c + '.';
}
else {
output += a + ' does not equal ' + c + '.';
}
document.getElementById('outputDiv').innerHTML = output;
}
Desk Check
a b c output
'always' 'believe' 'always'
191
String Methods
JavaScript includes several useful string methods that you
can use to manipulate the contents of arrays. Many of these
methods are listed in the next table. When calling these
methods, a programmer must write the name of the string in
front of the method name as shown in this template.
Template
String Methods
Method Description
s.charAt(index) Returns the character
at the given index.
s.charCodeAt(index) Returns a number
indicating the Unicode
value of the character
at the given index.
s.concat(s2, s3, …) Combines the text of
two or more strings and
returns a new string.
s.endsWith(toFind, start) Returns true if the
string s ends with the
characters of the string
toFind.
s.indexOf(toFind, start) Returns the index
within the string s of
the first occurrence of
the string toFind, or -1
if not found.
s.lastIndexOf(toFind, start) Returns the index
within the string s of
the last occurrence of
the string toFind, or -1
if not found.
s.replace(toFind, replacement) Used to find a match
between a regular
expression and a string,
and to replace the
matched substring with
a new substring.
s.split(sep, limit) Splits a string into an
array of strings by
separating the string
into substrings.
s.startsWith(toFind, start) Returns true if the
string s starts with the
characters of the string
toFind.
s.substr(start, length) Returns the characters
of a string starting at
the specified index and
continuing for the
specified number of
characters.
s.substring(start, end) Returns the characters
of a string between two
indexes into the string.
s.toLowerCase() Returns a copy of the
string s with all
characters converted to
lower case.
s.toUpperCase() Returns a copy of the
string s with all
characters converted to
upper case.
s.trim() Trims whitespace from
the beginning and end
of the string.
192
Extracting a Substring
Many computer programs store people’s names in this
format: FamilyName, GivenName (a person’s family name
followed by a comma and a space followed by the person’s
given name). When names are stored in this format, a
common operation is to extract the family name as done in
this function.
Example 11
Desk Check
fullName comma family
'Washington, George'
Counting Characters
Another common operation with strings is to count how
many times a specific character occurs in a string. This can
be done with a loop and an if statement.
Example 12
// Returns the number of times that the
// character stored in c occurs in the string s.
function countOccurrences(s, c) {
var count = 0;
for (var i = 0; i < s.length; i++) {
if (s[i] == c) {
count++;
}
}
return count;
}
Desk Check
s c i count
'ahead' 'a'
193
You may also want to know how many upper case letters
are in a string, which can be done very similarly to the
previous example.
Example 13
Desk Check
s i c count
'H. W. Bush'
Transposing Chords
In music theory, a chord name contains two parts: a note
name and an optional suffix. There are twelve note names:
A, Bb, B, C, C#, D, Eb, E, F, F#, G, Ab. Within a chord name, the
suffix is all the characters after the note name. Some
example suffixes are m, 7, m7, maj7, and sus4. If a chord
name doesn’t contain a suffix, that chord is a major chord.
Notice in the
code that the
194
Example 14
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="author" content="Rex Barzee">
<title>Transpose</title>
<script>
/* Input: Chord names and an integer
* Processing:
* A loop that repeats once for each chord
* Transpose the chord
* Append the transposed chord onto an output string.
* Output: The transposed chords
*/
function transposeAll() {
// Get the chord names entered by the user as a string.
var input = document.getElementById('chords').value;
// Split the string into an array of chord names.
var chords = input.split(', ');
// Separate the note name and suffix from the chord name.
var note = getNote(chord);
var suffix = getSuffix(chord);
// Find where the note name is stored
// in the array of all 12 note names.
var index = notes.indexOf(note);
// Transpose the original note by adding the half steps.
index += halfSteps;
// If the half steps value is negative and the
// transposed index is less than 0, then repeatedly
// add 12 to the index until it is non-negative.
while (index < 0) {
index += notes.length;
}
// If the half steps value is positive and the
// transposed index is 12 or greater, then repeatedly
// subtract 12 from the index until it is less than 12.
while (index >= notes.length) {
index -= notes.length;
}
// Build the transposed chord name by concatenating
// the transposed note name to the chord suffix.
var transposed = notes[index] + suffix;
return transposed;
}
Chapter Summary
To create a string surround text with single or double
quotes.
To include special characters, such as single quote ('),
double quote ("), or new line, in a string use an escape
sequence: \' \" \n etc.
To read or write a single character within a string, use
the bracket operators ([ and ]) like an array:
stringName[index];
To compare to strings, use the comparison operators:
==, !=, <, <=, >, and >=
JavaScript contains many useful built-in string methods.
Review Questions
1. Write JavaScript code to declare a string named address
and assign the text “123 W Main” to it.
Programming Assignments
1. Write a function named extractGivenName with one
parameter named fullName. The parameter fullName
will always contain a person’s family and given names in
that order separated by a comma and a single space, for
example “Reagan, Ronald” (without the quotation
marks). The function should extract and return the
person’s given name, for example “Ronald” (without the
quotation marks).
199
computer evaluates operators. Operators with higher
precedence are evaluated first. For example, 7 + 3 * 2 is 13
because multiplication has a higher precedence than
addition, so the computer performs the multiplication before
the addition.
Associativity
Operator associativity determines the order in which the
computer evaluates operators of the same precedence. There
are two categories of associativity, left to right and right to
left. Consider the expression: a OP1 b OP2 c
200
Precedence
Listed from highest precedence (evaluated first) to lowest
precedence
201
like this. A consultant went to a large company to teach
the software engineers in the company. At the beginning of
the class she said to the students, “If you got on an airplane
and realized that your team had written the software that
runs the airplane, how many of you would be afraid for your
life and get off the plane?” Every student except one put his
hand up. The consultant looked at the one student who didn’t
raise his hand and asked, “What does your team do
differently so that you wouldn’t be afraid to ride on the
airplane?”
203
− (negation)
− (subtraction)
' (single quote) [1] [2]
" (double quotes) [1] [2]
! (logical not)
!= (not equal)
% (modulus)
&& (logical and)
( ) (parentheses)
* (multiplication)
/ (division)
/* (multi-line JavaScript comment)
// (single line JavaScript comment)
[ ]. See array index
\ (backslash). See escape sequence
^ (exclusive or) [1] [2]
|| (logical inclusive or)
+ (addition)
+ (string concatenation). See string concatenation
++ (increment)
< (less than)
<= (less than or equal)
<!-- (HTML comment)
= (assignment)
== (equal to)
> (greater than)
>= (greater than or equal)
aggregation
alert
algorithm
And. See &&
array
element
index [1] [2]
length
subscript. See array index
array methods
Array object
ASCII
association
associative array. See dictionary
attribute [1] [2]
bit
boolean [1] [2]
break
byte
case
class
composition
concatenation. See string concatenation
control structure
flow of execution
for
for each
function [1] [2]
argument [1] [2] [3]
call point [1] [2]
header
parameter [1] [2] [3]
return [1] [2] [3]
signature. See function header
getElementById
gigabyte
gigahertz
Heron’s formula
hertz
if
if else
inclusive or. See ||
index. See array index
inheritance
innerHTML
integer division
kilobyte
204
local storage
parseFloat
parseInt
precedence
prompt
Roman numerals
scope
global
local
statement [1] [2]
string [1] [2] [3]
concatenation [1] [2] [3]
length
String object [1] [2]
switch
tab character
truth table
undefined
Unicode [1] [2]
Unified Modeling Language
while
Xor
About the Author
Rex A. Barzee is a professor
of Computer Information
Technology at Brigham Young
University – Idaho. He is an
inventor of two United States
patents and the author of
numerous books. He earned
a bachelor’s and a master’s
degree in Computer Science
from Brigham Young
University. Before becoming
a professor, he worked in
industry for eight years as a
software engineer for
Southwest Research Institute,
Hewlett-Packard Company,
Voyant Technologies, and the Utah State University Space
Dynamics Laboratory. He worked on a variety of projects
including the HP-UX kernel, the HP-UX standard C library,
HP-UX OpenGL 3D Graphics Library, full text indexing, image
processing, and VoiceXML applications. You can see his full
profile at LinkedIn.