0% found this document useful (0 votes)
129 views

VC Bestpractice Guide

This document provides an introduction to web development and JavaScript. It discusses client-server architecture, HTTP requests and responses, static and dynamic web pages, common web technologies, and JavaScript. The document also covers AJAX and cross-browser compatibility issues.

Uploaded by

JACE Hix
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

VC Bestpractice Guide

This document provides an introduction to web development and JavaScript. It discusses client-server architecture, HTTP requests and responses, static and dynamic web pages, common web technologies, and JavaScript. The document also covers AJAX and cross-browser compatibility issues.

Uploaded by

JACE Hix
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 262

Introduction

to web development
and JavaScript

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 1
Objectives
Applied
 Load a web page from the Internet or an intranet into a web
browser.
 View the source code for a web page in a web browser.

Knowledge
 Describe the components of a client-server architecture.
 Describe HTTP requests and responses.
 Distinguish between the way a web server processes static web
pages and dynamic web pages.
 Name the common web browsers, web servers, and server-side
scripting languages.
 Describe the use of the core web technologies: XHTML, CSS, the
Document Object Model, and JavaScript.

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 2
Objectives (continued)
 Describe the basis for selecting specific releases of the core
technologies for use in your web development projects.
 In general terms, describe the use of AJAX.
 Describe the issues of cross-browser compatibility and user
accessibility.
 Describe the components of an HTTP URL.

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 3
W3C Genesis
• In the beginning, the Tim Berners-Lee created the web. And the
people of the world cried out “let there be data!”, and there was.

• But the data was empty, ugly, and formless. So on the next day the
W3C was formed, and Håkon Wium Lie created CSS to separate the
layout from the design and from the semantic markup.

• On the third day, Brendan Eich created JavaScript; breathing life into
the web content. It was given dominion over all of the DOM from
lowly HTML elements, to the CSS properties, and to the browser
window itself.

• And on the last day, the W3C rested… and let Microsoft screw it all
up with Internet Explorer. But because Microsoft blessed us with
the gift of AJAX, they were forgiven.
W3C languages as a Metaphor
If the W3C languages were a person…

• HTML would be your body


• JavaScript would be your brain
• CSS would be your clothes
W3C languages as a Metaphor
If the W3C languages were a car…

• HTML would be the engine and chassis


• JavaScript would the electrical system and all
the controls
• CSS would be the paint and exterior plastic
W3C languages as a Metaphor
If the W3C languages were a book…

• HTML would be the words


• JavaScript would the punctuation
• CSS would be the font
W3C languages as a Metaphor
The point is…

• HTML, CSS, & JavaScript have a symbiotic relationship.

• Alone, the usefulness of each of these languages is


minuscule; but together they form something that is
greater than the sum of its parts.

• There is not a popular (U3) Web site on Earth today


that does not leverage all three of these languages.
What is JavaScript?
• The first thing that creates some confusion about
JavaScript is its name. In fact, one of the most common
questions when first approaching JavaScript is:

"Is JavaScript the same as Java?".

• Clearing up this basic but important question is our


first order of business, but by no means the only one.
– What is the difference between JavaScript and Java?
– What JavaScript can and cannot do?
Are JavaScript and Java the same
thing?
No, they are not!!!
Other than a similar name, they have NOTHING to do with each other.

• Java (developed by Sun Microsystems) is a powerful and much


more complex programming language in the same category as C
and C++.

• JavaScript was created by Brendan Eich at Netscape and was first


introduced in December 1995 under the name of LiveScript.
However, it was rather quickly renamed JavaScript, although
JavaScript’s official name is ECMAScript, which is developed and
maintained by the ECMA (European Computer Manufacturer's
Association) International organization.
So then what is JavaScript?
• JavaScript is a scripting language, that is, a lightweight
programming language that is interpreted by the
browser engine when the web page is loaded.

• The fact that the JavaScript interpreter is the browser


engine itself accounts for some inconsistencies in the
way your JavaScript-powered page might behave in
different browsers. But don't worry: thankfully, well-
established techniques and powerful JavaScript
libraries such as jQuery to fix that for us.
Things you can't do with JavaScript
You can't force JavaScript on a browser.

• JavaScript runs in the client, that is, the browser. If you use
an older browser without support for JavaScript, or if you
simply choose to disable JavaScript in your browser, then a
JavaScript script can't work.

• Conclusion: unlike what happens with languages that run


on the server, such as Python or PHP, you never fully know
for sure the impact that the browser your website visitors
are going to use will have on your script, or whether your
visitors will choose to turn JavaScript support off.
Things you can't do with JavaScript
You can't access or affect resources from
another internet domain with JavaScript.
This is called the Same Origin Policy. Well,
how would you like it if all of a sudden all
the nice comments your visitors left on
your website started to disappear, or to
change place in your page because of a
naughty JavaScript script running on
another website?

This is exactly the kind of nasty situation


that the Same Origin Policy is designed to
prevent. Conclusion: your JavaScript script
can only access resources in your website
Things you can't do with JavaScript
You can't directly access server resources with
JavaScript.
Because JavaScript is a client-side
language, it's limited to what can be done
in the client, that is, usually in the
browser environment. A JavaScript script
cannot access server resources such as
databases.

• No Database access
• No File system access
• No hardware (peripheral) access
• No low level networking (http only)
Zillion things you can do with
JavaScript
Put HTML/Text in a page on-the-fly.
Say you want to display a nice thank you message to a user who has
just submitted a comment form on your website. Obviously, the
message needs to be added after the user has submitted the form.

You could let the server do that. However, if your website is very busy
and your server processes hundreds of forms a day, it might take a
little while for your thank you message to appear to the user.

Here's JavaScript to the rescue. Because JavaScript runs in the user's


browser, the thank you note can be added and displayed on the page
almost instantaneously, making your website users happy.
Zillion things you can do with
JavaScript
Make your web pages responsive.

Web environments are dynamic, things happen all the time: the
web page loads in the browser, the user clicks a button or moves
the mouse over a link, etc. These are called events.

With JavaScript you can make the page immediately react to


these events the way you choose: for example, by showing or
hiding specific page elements, by changing the background color,
etc.
Zillion things you can do with
JavaScript
Detect visitors' browsers, and
capabilities.

You can use a JavaScript script to detect the visitor’s browser, or,
even better, you can detect what features a certain browser does
or does not support. Depending on the browser and its
capabilities, you can choose to load a page specifically tailored to
that kind of browser.

See: http://modernizr.com/
Zillion things you can do with
JavaScript
Create cookies.

A JavaScript script is great if you want to create cookies so that


your visitors can enjoy a personalized experience the next time
they visit your website.
Zillion things you can do with
JavaScript
Validate web form data.

You can use a JavaScript script to validate form data before the
form is submitted to a server. This saves the server from extra
processing, and gives the user real-time feedback.
Zillion things you can do with
JavaScript
And graphics & animation to HTML.

Learning JavaScript will enable you to add cool animation effects


to your web pages without using an external Flash plug-in, use
the newest features of HTML5 such as canvas to draw directly on
your web page, and drag and drop capabilities.

See: http://www.flotcharts.org/
Zillion things you can do with
JavaScript
Talk to the web server asynchronously.

One core features of 21st century web applications is their fantastic


responsiveness. A pioneer in the business of making the web more and
more similar to a desktop application has been Google: as soon as you
start typing a character in a Google box, all kinds of suggestions and
search results keep popping up to speed up your search; and again,
just type something using Google maps, and you're instantly
catapulted to almost any street on the planet.

Behind this amazing feat of human cleverness is the coming together


of a few technologies collectively known as AJAX.
What's AJAX all about?
The acronym AJAX stands for Asynchronous JavaScript And XML. In actual fact, it's a combination of internet standards
made up of:

• standards-based presentation using HTML and CSS;


• dynamic display using the DOM;
• data interchange and manipulation using XML and JSON;
• asynchronous data retrieval using the XMLHttpRequest object;
• JavaScript magic to orchestrate the whole process.

In non-AJAX web applications, the interaction between servers and clients can be a tedious business:

• a user action from the client sends a request to the web server via HyperText Transfer Protocol (HTTP);
• the web server receives the request and processes it by invoking server-side scripts, database data, etc., and sends a
response back to the client via HTTP;
• the client browser receives the response and loads the entire updated page.

Having to go from browser to server and back again each time a user requests some piece of data from the server, in
addition to undergoing an entire page refresh at each update, can be quite stressful on servers and on users alike. AJAX
helps in at least 2 respects: piecemeal page updates and asynchronous communication between server and client.

What this means in a few words, is that every time the user interacts with the web page, only those bits that need updating
are refreshed, not the entire page. Furthermore, the fact that AJAX operations are performed asynchronously, means that
during the time that it takes for the server to respond, the page is not locked and the user can still interact with the website.
What else can JavaScript do?
How much time ya got?
What are the down sides of
JavaScript?
1. Compatibility – different browsers use different JavaScript engines and support
different features. Making it almost required to use frameworks that detect and
neutralize the compatibility issues (allowing you to get back to work).

2. Performance – different engines have different performance characteristics. For


example Firefox v3 had a JavaScript engine that was over 6 times faster than the
current version of Internet Explorer at the time.

3. Availability – a user can disable JavaScript at any time, and only they can enable
it again. This makes it incredibly impractical and time consuming to write a “Web
2.0” application that gracefully fails back to a “Web 1.0” standards when
JavaScript is disabled.

4. Security – JavaScript is parsed and interpreted by the client, thus the raw
JavaScript source is viewable to any sophisticated user who wishes to view it. As
such, you can’t fully rely on JavaScript to implement security related features.
This forces you to validate security twice, once on the client and then again on
the server.
So when should I use JavaScript vs.
something else?
• JavaScript is the ONLY language that can directly interact with the user or
browser window. If you need…
– browser inspection
– live DOM manipulation
– event handling
– or interactivity of any kind… look no further.

• If your user experience will suffer from excessive page refreshing and/or
data shuffling, use AJAX. Pulling in small chunks of JSON/XML data from
the server and updating a live DOM via JavaScript can GREATLY increase
the responsiveness of your applications.

• As a rule of thumb, if it can be done in the server side language is should


be done in the server side language… unless it fits one of the scenarios
above.
Okay I get it, lets learn some
JavaScript!
The architecture of a web application

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 27
How a web server processes a static web page

HTTP request
XHTML
file
`
HTTP response

Web browser Web server

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 28
A simple HTTP request
GET / HTTP/1.1
Host: www.example.com

A simple HTTP response


HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 136
Server: Apache/2.2.3

<html>
<head>
<title>Example Web Page</title>
</head>
<body>
<p>This is a sample web page</p>
</body>
</html>

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 29
Two protocols that web applications depend upon
 Hypertext Transfer Protocol (HTTP)
 Transmission Control Protocol/Internet Protocol ( TCP/IP).

Terms
 Hypertext Markup Language (HTML)
 static web page
 HTTP request
 HTTP response

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 30
How a web server processes a dynamic web page

HTTP request

`
HTTP response

Web browser Web server Application server Database server

Application
script

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 31
How JavaScript fits into this architecture

HTTP request

`
HTTP response

Web browser Web server Application server Database server

Application
JavaScript
script

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 32
Common uses of JavaScript
 Validate form data before it is sent to the server for processing.
 Respond to user actions such as mouse clicks and key presses.
 Create dynamic menus.
 Create slide shows.
 Animate elements in a web page.
 Create timers, clocks, and calendars.
 Change the style sheet that a web page uses.
 Sort the data that’s in a table.
 Control the web browser window.
 Detect web browser plug-ins.
 Open new web browser windows.
 Change images when the user rolls the mouse over an image.

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 33
The code for a web page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Mike's Bait and Tackle Shop</title>
</head>
<body>
<h1>Mike's Bait and Tackle Shop</h1>
<p>Welcome to Mike's Bait and Tackle Shop.
We have all the gear you'll need
to make your next fishing trip a great success!</p>
<h2>New Products</h2>
<ul>
<li>Ultima 3000 Two-handed fly rod</li>
<li>Phil's Faux Shrimp Fly - Size 6</li>
<li>Titanium Open Back Fly Reel - Black</li>
</ul>
<p>Contact us by phone at 559-555-6624 to place
your order today.</p>
</body>
</html>

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 34
The web page in a web browser

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 35
The DOM for the web page
html

head body

title h1 p h2 ul p

text text text text text

li li li

text text text

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 36
Terms
 document object model (DOM)
 node

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 37
Embedded JavaScript in an XHTML document
<!-- The code before this is the same as in figure 1-6. -->
<p>Contact us by phone at 559-555-6624
to place your order today.</p>
<p>&copy;
<script type="text/javascript">
var today = new Date();
document.writeln( today.getFullYear() );
</script>
Mike's Bait and Tackle Shop</p>
</body>
</html>

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 38
The JavaScript application in a web browser

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 39
How the web technologies interact

Web browser
Web page (XHTML and CSS)

DOM

JavaScript

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 40
The DOM event cycle

Page
Loaded

Event Script DOM Page


Occurs Executes Modified Updated

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 41
Terms
 DOM scripting
 event-driven programming
 event
 event handler

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 42
AJAX-enabled request and response cycle
AJAX HTTP request:
Client The browser requests
Server
updated information for a
page.
Browser Web server

AJAX HTTP response:


The server returns the
requested information and
the page is updated.
Browser Web server

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 43
Terms
 rich Internet application (RIA)
 AJAX (asynchronous JavaScript and XML)
 XMLHttpRequest object
 Extensible markup language (XML)
 JavaScript object notation (JSON)

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 44
The Sales Tax application in a web browser

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 45
The XHTML file for the Sales Tax application
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sales Tax Calculator</title>
<link rel="stylesheet" type="text/css"
href="sales_tax.css" />
<script type="text/javascript"
src="sales_tax.js"></script>
</head>
<body>
<div id="content">
<h1>Sales Tax Calculator</h1>
<p>Enter the values below and click "Calculate".</p>
<div id="taxCalc">
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" /><br />

<label for="taxRate">Tax Rate:</label>


<input type="text" id="taxRate" />%<br />

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 46
The XHTML file (continued)
<label for="salesTax">Sales Tax:</label>
<input type="text" id="salesTax"
disabled="disabled" /><br />

<label for="total">Total:</label>
<input type="text" id="total"
disabled="disabled" /><br />

<label>&nbsp;</label>
<input type="button" id="calculate"
value="Calculate" /><br />
</div>
</div>
</body>
</html>

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 47
The JavaScript file for the Sales Tax application
var $ = function (id) {
return document.getElementById(id);
}

window.onload = function () {
$("calculate").onclick = calculate_click;
$("subtotal").focus;
}

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 48
The JavaScript file (continued)
var calculate_click = function () {
var subtotal = parseFloat( $("subtotal").value );
var taxRate = parseFloat( $("taxRate").value );

$("salesTax").value = "";
$("total").value = "";

if ( isNaN(subtotal) || subtotal < 0 ) {


alert("Subtotal must be a number that is zero
or more!");
} else if ( isNaN(taxRate) || taxRate < 0 ) {
alert("Tax Rate must be a number that is zero
or more!");
} else {
var salesTax = subtotal * (taxRate / 100);
salesTax = parseFloat( salesTax.toFixed(2) );
var total = subtotal + salesTax;
$("salesTax").value = salesTax;
$("total").value = total.toFixed(2);
}
}

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 49
The source code for the Sales Tax application
in Mozilla Firefox

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 50
How to view the source code in Mozilla Firefox
 Use the ViewPage Source command.

How to view the source code in Internet Explorer


 Use the ViewSource command.

Murach’s JavaScript, C1 © 2009, Mike Murach & Associates, Inc.


Slide 51
How to code
a JavaScript application

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 52
Objectives
Applied
 Using a text editor like Notepad++ or TextWrangler, enter and edit
XHTML, CSS, and JavaScript files.
 Using Firefox as your web browser, display any error messages in
the Error Console when you test a JavaScript application.
 Given the specifications for a JavaScript application that requires
only the skills and language elements presented in this chapter,
code, test, and debug the application.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 53
Objectives (continued)
Knowledge
 Describe the use of the two types of JavaScript comments.
 Describe the type of error that can occur if you split a JavaScript
statement in the wrong place.
 List the primary rules for creating a JavaScript identifier.
 Describe the three primitive data types used in JavaScript.
 Describe the use of the \n escape sequence in a string literal.
 Describe the rules for evaluating an arithmetic expression,
including order of precedence and the use of parentheses.
 Describe the use of variable declarations and assignment
statements.
 Describe the use of objects, properties, methods, and object
chaining.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 54
Objectives (continued)
 Describe the ways that number, string, Boolean, and Date objects
are created.
 Given the name of a common method for a window, document,
Number, String, Boolean, or Textbox object, describe the function
of the method.
 Describe the rules for evaluating a conditional expression,
including the use of the isNan function, the order of precedence for
logical operators, and the use of parentheses.
 Describe the flow of control for an if, while, or for statement.
 Describe the creation and use of functions.
 Describe the creation and use of event handlers for the click event
of a button element and the load event of the window object.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 55
Notepad++ with an auto-completion list

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 56
Basic skills for using Notepad++
 How to open, save, close, and start files
 How to change the style for comments
 How to use the auto-completion feature
 How to let Notepad++ know which language you’re working with

Note
 These skills are presented in figure 2-1.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 57
The Sales Tax application in the Firefox browser

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 58
How to test a web page
 Open the web page in your browser.
 Enter the required input data, and run the application.

How to retest a web page


after you change the source code
 To reload the edited file for the page, click the Reload or Refresh
button.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 59
If the Reload or Refresh button
doesn’t clear browser memory…
 you may need to close the browser window and reopen the
application.

If the application doesn’t do anything when you


test it…
 it either has syntax errors or other types of coding errors.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 60
The Firefox Error Console with an error displayed

How to display the Firefox Error Console


 Use the ToolsError Console command or press Ctrl+Shift+J.

How to display the source code


 Click on the link in the Error Console.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 61
The source code that’s displayed
when you click on the link

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 62
How to load JavaScript from an external file
<script type="text/javascript" src="sales_tax.js"></script>

How to embed JavaScript


in the head of an XHTML document
<head>
...
<script type="text/javascript">
var $ =
function (id) { return document.getElementById(id); }
</script>
...
</head>

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 63
How to embed JavaScript
in the body of an HTML document
<p>&copy;
<script type="text/javascript">
var today = new Date();
document.writeln( today.getFullYear() ); </script>
Mike's Bait and Tackle Shop</p>

How to load a script from a different web server


<script type="text/javascript"
src="http://www.google-analytics.com/urchin.js">
</script>

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 64
How to use the noscript tag
in the body of an XHTML document
<script type="text/javascript">
var today = new Date();
document.writeln( today.getFullYear() );
</script>
<noscript>2009</noscript>

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 65
The basic syntax rules for JavaScript
 JavaScript is case-sensitive.
 JavaScript statements end with a semicolon.
 JavaScript ignores extra whitespace in statements.
 Single-line comments begin with two forward slashes.
 Multi-line comments begin with /* and end with */.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 66
A single-line comment
nextYear = thisYear + 1; // Add 1 to this year

A multi-line comment
/* The following line determines what the
next year is by adding 1 to the current year
*/
nextYear = thisYear + 1;

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 67
How to split a statement across multiple lines
 Split a statement after an arithmetic or relational operator such as:
+, -, *, /, =, ==, >, or <.
 Split a statement after an opening brace ( { ), bracket ( [ ), or
parenthesis.
 Split a statement after a closing brace ( } ).
 Do not split a statement after an identifier, a value, or the return
keyword.
 Do not split a statement after a closing bracket ( ] ) or parenthesis.

A split statement that results in an error


return
"Hello";

A split statement that works correctly


nextYear =
thisYear + 1;

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 68
Rules for creating identifiers in JavaScript
 Identifiers can only contain letters, numbers, the underscore, and
the dollar sign.
 Identifiers can’t start with a number.
 Identifiers are case-sensitive.
 Identifiers can be any length.
 Identifiers can’t be the same as reserved words.
 Avoid using global properties and methods as identifiers.
 Avoid using names that are similar to reserved words, global
properties, or global methods.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 69
Valid identifiers in JavaScript
subtotal
index_1
$
taxRate
calculate_click
$log

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 70
Examples of number values
15 // an integer

-21 // a negative integer

21.5 // a floating-point value

-124.82 // a negative floating-point value

-3.7e-9 // a floating-point value


// equivalent to -0.0000000037

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 71
The primitive data types
 Number
 String
 Boolean

Terms
 integer
 floating-point value
 exponent
 empty string
 escape sequence
 Boolean value

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 72
Variable Data Types
• Booleans - This is the simplest type. A boolean expresses a truth value. It
can be either TRUE or FALSE.

• Integers – An integer is a signed number with no fraction (decimal places).


For example {..., -2, -1, 0, 1, 2, ...}

• Floats - Floating point numbers (also known as "floats", "doubles", or "real


numbers") are signed number with fractions (decimals). For example {...,
2.0e-11, -1.810, 0, 1.2e3, 2e10, ...}

• Strings - A string is series of characters of any kind.


Variable Data Types
• Arrays - An array in PHP is an ordered map. A map is a type that associates
values to keys. Arrays in PHP are similar to lists, collections, hashs, or
dictionaries in other languages.

• Objects –… its complicated …


Arithmetic Operators
Operator Description Example Result
+ Addition $x=2 4
$x+2
- Subtraction $x=2 3
5-$x
* Multiplication $x=4 20
$x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division 5%2 1
remainder) 10%8 2
10%2 0
++ Increment $x=5 x=6
$x++
-- Decrement $x=5 x=4
$x--
Assignment Operators
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
Flow Control
Conditional Statements
• Very often when you write code, you want to perform different
actions for different decisions. You can use conditional statements
in your code to do this.
• In PHP we have the following conditional statements:
– if statement - use this statement to execute some code only if a
specified condition is true
– if...else statement - use this statement to execute some code if a
condition is true and another code if the condition is false
– if...elseif....else statement - use this statement to select one of several
blocks of code to be executed
– switch statement - use this statement to select one of many blocks of
code to be executed
Examples of string values
"JavaScript" // a string with double quotes
'String Data' // a string with single quotes
"" // an empty string

How the \n escape sequence can be used


to start a new line in a string
"A valid variable name\ncannot start with a number."
// represents the string: A valid variable name
// cannot start with a number.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 78
The two Boolean values
true // equivalent to true, yes, or on
false // equivalent to false, no, or off

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 79
Common arithmetic operators
+
-
*
/
%
++
--

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 80
The order of precedence
for arithmetic expressions
Order Operators
1 ++
2 --
3 * / %
4 + -

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 81
Precedence and the use of parentheses
3 + 4 * 5 // Result is 23

(3 + 4) * 5 // Result is 35

13 % 4 + 9 // Result is 10

13 % (4 + 9) // Result is 0

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 82
Terms
 arithmetic expression
 arithmetic operator
 order of precedence
 concatenate
 concatenation operator

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 83
How to declare variables
without assigning values to them
var subtotal;
// declares a variable named subtotal

var lastName, state, zipCode;


// declares three variables

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 84
The assignment operators
=
+=
-=
*=
/=
%=

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 85
How to declare variables and assign values
var subtotal = 74.95; // subtotal is 74.95

var salesTax = subtotal * .1; // salesTax is 7.495

var isValid = false; // Boolean value is false

var zipCode = "93711", state = "CA"; // two assignments

var firstName = "Ray", lastName = "Harris";


var fullName = lastName + ", " + firstName;
// fullName is "Harris, Ray"

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 86
How to code compound assignment statements
var subtotal = 24.50;

subtotal += 75.50; // subtotal is 100


subtotal *= .9; // subtotal is 90 (100 * .9)

var firstName = "Ray", lastName = "Harris";


var fullName = lastName; // fullName is "Harris"
fullName += ", "; // fullName is "Harris, "
fullName += firstName; // fullName is "Harris, Ray"

var months = 120, message = "Months: ";


message += months; // message is "Months: 120"

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 87
Terms
 variable
 declare a variable
 assignment statement
 assignment operator
 string literal
 numeric literal

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 88
The syntax for creating a new object
new ObjectType()

Examples that create new objects


var today = new Date(); // creates a Date object

var states = new Array(); // creates an Array object

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 89
The syntax for accessing a property of an object
objectName.propertyName

Examples that access a property of an object


alert(window.screenX);
// Displays the width of the user's screen

window.location = "http://www.murach.com";
// Loads the murach.com home page

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 90
The syntax for calling a method of an object
objectName.methodName(parameters)

Examples that call a method of an object


// Stores a reference to the XHTML element
// with the id "rate"
var rateTextbox = document.getElementById("rate");

// Gets the full year and writes it to the web page


document.writeln( today.getFullYear() );

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 91
Examples of object chaining
// Uses the alert method to display the value property
// of the DOM object that is returned
// by the getElementById method.
alert( document.getElementById("rate").value );

// Uses the alert method to display the location property


// of the current page
// after it has been converted to lowercase letters
// by the toLowerCase method.
alert( window.location.toLowerCase() );

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 92
Terms
 object
 property
 method
 call a method
 parameter (or argument)
 object chaining

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 93
One property of the window object
location

Common methods of the window object


alert(message)
prompt(message,default)
parseInt(string)
parseFloat(string)

Examples that use these properties and methods


alert("Invalid entry."); // displays "Invalid entry."

var userEntry = prompt(errorMessage,100);


// accepts user entry
parseInt("12345.67"); // returns the integer 12345
parseFloat("12345.67"); // returns the floating point
// value 12345.67
parseFloat("Ray Harris"); // returns NaN

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 94
Common methods of the document object
getElementById(id)
write(text)
writeln(text)

Examples that use these methods


// gets the DOM object that represents
// the XHTML element with "rate" as its id
// and stores it in a variable named rateTextbox
var rateTextbox = document.getElementById("rate");

// writes the string in the message variable to the


document
document.writeln(message);

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 95
Notes on using the window and document objects
 The window object is the global object when JavaScript is used in a
web browser.
 JavaScript lets you omit the object name and period when referring
to the window object.
 The document object is the object that allows you to work with the
DOM.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 96
One method of the Number object
toFixed(digits)

Examples
var balance = 2384.55678;
// creates a number object named balance

alert ( balance.toFixed(2) );
// displays 2384.56
// balance is still 2384.55678

balance = parseFloat( balance.toFixed(2) );


// balance is now 2384.56

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 97
Methods of the String object
substr(start,length)
toLowerCase()
toUpperCase()

Examples
var guest = "Ray Harris";
// creates a string object named guest

alert ( guest.toUpperCase() ); // displays "RAY HARRIS"

alert ( guest.substr(0,3) ); // displays "Ray"

guest = guest.substr(4,6); // guest is now "Harris"

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 98
Methods of the Date object
toDateString()
getMonth()
getDate()
getFullYear()

Examples
var today = new Date();
// creates a Date object named today

// assume the current date is 09/20/2008


alert ( today.toDateString() );
// displays Sat Sep 20 2008

alert ( today.getFullYear() ); // displays 2008

alert ( today.getMonth() );
// displays 8, not 9, for September

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 99
Common properties of the Textbox object
value
disabled

Two XHTML <input> tags that create text boxes


<input type="text" id="rate" />
<input type="text" id="salesTax" disabled="disabled" />

How to get the text box value in two statements


// Store a reference to the text box
var rateTextbox = document.getElementById("rate");

// Get the value and convert it to a number


var rate = parseFloat( rateTextbox.value );

How to get the value with with object chaining


var rate =
parseFloat(document.getElementById("rate").value);

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 100
How to enable a text box
document.getElementById("salesTax").disabled = false;

How to display a value in a text box


// Assign an empty string to a text box
document.getElementById("salesTax").value = "";

// Assign the value of a variable named salesTax


// to a text box
document.getElementById("salesTax").value =
salesTax.toFixed(2);

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 101
One method of the Textbox object
focus()

How to move the cursor to a text box


document.getElementById("investment").focus();

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 102
The relational operators
==
!=
<
<=
>
>=

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 103
The syntax of the global isNaN method
isNaN(expression)

Examples of the isNaN method


isNaN("Harris")
// Returns true since "Harris" is not a number

isNaN("123.45")
// Returns false since "123.45"
// can be converted to a number

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 104
The logical operators in order of precedence
Operator Description
! NOT
&& AND
|| OR

How the logical operators work


 Both tests with the AND operator must be true for the overall test
to be true.
 At least one test with the OR operator must be true for the overall
test to be true.
 The NOT operator switches the result of the expression to the
other Boolean value.

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 105
Terms to know
 conditional expression
 relational operator
 compound conditional expression
 logical operator

One common programming error


 Confusing the assignment operator ( = )
with the equality operator ( ==).

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 106
An if statement with an else clause
if ( age >= 18 ) {
alert ("You may vote.");
} else {
alert ("You are not old enough to vote.");
}

An if statement with else if and else clauses


if ( isNaN(rate) ) {
alert ("You did not provide a number for the rate.");
} else if ( rate < 0 ) {
alert ("The rate may not be less than zero.");
} else {
alert ("The rate is: " + rate + ".");
}

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 107
An if statement
with a compound conditional expression
if ( isNaN(userEntry) || userEntry <= 0 ) {
alert ("Please enter a valid number > zero.");
}

An if statement that tests a Boolean value


if ( invalidFlag ) {
alert ("All entries must be numeric values > 0.");
}

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 108
A nested if statement
if ( isNaN(totalMonths) || totalMonths <= 0 ) {
alert ("Please enter a number of months > zero.");
} else {
var years = parseInt ( totalMonths / 12 );
var months = totalMonths % 12;
if ( years == 0 ) {
alert ( "The investment time is "
+ months + " months.");
} else if ( months == 0 ) {
alert ( "The investment time is "
+ years + " years.");
} else {
var message = "The investment time is "
+ years + " years ";
message += "and " + months + " months.";
alert(message);
}
}

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 109
A while loop that adds 1 through 5
var sumOfNumbers = 0;
var loops = 5;
var counter = 1;
while (counter <= loops) {
sumOfNumbers += counter;
counter++;
}
alert(sumOfNumbers); // displays 15

A for loop that adds 1 through 5


var sumOfNumbers = 0;
var loops = 5;
for (var counter = 1; counter <= loops; counter++) {
sumOfNumbers += counter;
}
alert(sumOfNumbers); // displays 15

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 110
A while loop that gets a user entry
userEntry = prompt("Please enter a number:", 100);
while ( isNaN( userEntry ) ) {
alert( "You did not enter a number.");
userEntry = prompt("Please enter a number:", 100);
}

A for loop that calculates the future value


of a monthly investment
var monthlyInvestment = 100; // investment is $100
var monthlyRate = .01; // interest rate is 12%
var months = 120; // 120 months is 10 years
var futureValue = 0; // futureValue starts at 0

for ( i = 1; i <= months; i++ ) {


futureValue = ( futureValue + monthlyInvestment ) *
(1 + monthlyRate);
}

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 111
A function with no parameters
var showYear = function () {
var today = new Date();
alert( today.getFullYear() );
}

How to call a function that doesn’t return a value


showYear(); // displays the current year

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 112
A function with one parameter that returns a value
var $ = function ( id ) {
return document.getElementById( id );
}

How to call a function that returns a value


var taxRate = $("taxRate");

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 113
A function with two parameters
that doesn’t return a value
var displayEmail = function ( username, domain ) {
document.write( username + "@" + domain);
}

How to call a function with two parameters


that doesn’t return a value
displayEmail( "mike", "murach.com");

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 114
A function with two parameters
that returns a value
var calculateTax = function ( subtotal, taxRate ) {
var tax = subtotal * taxRate;
tax = parseFloat( tax.toFixed(2) );
return tax;
}

How to call a function with two parameters


that returns a value
var subtotal = 74.95;
var taxRate = 0.07;
var salesTax = calculateTax( subtotal, taxRate );
// returns 5.25

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 115
Terms to know
 function
 return statement
 call a function
 return undefined

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 116
Common events
Object Event
button onclick
window onload

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 117
An application with an onclick event handler
<head>
<script type="text/javascript">
// This function receives an id and returns an XHTML
object.
var $ = function ( id ) {
return document.getElementById( id );
}
// This is the onclick event handler named display_click.
var display_click = function () {
alert( "You clicked the button.");
}
// This is the onload event handler that assigns the
// display_click handler to the click event of the button.
window.onload = function () {
$("btnDisplay").onclick = display_click;
}
</script>
</head>
<body>
<p><input type="button" value="Display Message"
id="btnDisplay" /></p>

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 118
The web browser
after the Display Message button is clicked

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 119
The Future Value application in a web browser

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 120
The XHTML for the Future Value application
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css"
href="future_value.css" />
<script type="text/javascript"
src="future_value.js"></script>
</head>

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 121
The XHTML (continued)
<body>
<h1>Future Value Calculator</h1>
<p>Enter the values below and click "Calculate".</p>

<label for="investment">Monthly Investment:</label>


<input type="text" id="investment" /><br />

<label for="rate">Annual Interest Rate:</label>


<input type="text" id="rate" />%<br />

<label for="years">Number of Years:</label>


<input type="text" id="years" /><br />

<label for="futureValue">Future Value:</label>


<input type="text" id="futureValue"
disabled="disabled" /><br />

<label>&nbsp;</label>
<input type="button" id="calculate"
value="Calculate" /><br />
</body>

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 122
The JavaScript for the Future Value application
var $ = function (id) {
return document.getElementById(id);
}

window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
}

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 123
The JavaScript (continued)
var calculate_click = function () {

// Get the user entries from the first three text boxes.
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );

// Set the value of the fourth text box.


$("futureValue").value = "";

// Test the three input values for validity.


if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand
greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0) {
alert("Annual rate must be a valid number\nand
greater than zero.");
} else if(isNaN(years) || years <= 0) {
alert("Years must be a valid number\nand
greater than zero.");

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 124
The JavaScript (continued)
// If all input values are valid, calculate future value.
} else {
var monthlyRate = annualRate / 12 / 100;
var months = years * 12;
var futureValue = 0;

for ( i = 1; i <= months; i++ ) {


futureValue = ( futureValue + investment ) *
(1 + monthlyRate);
}

// Set the value of the fourth text box to the future value
$("futureValue").value = futureValue.toFixed(2);
}
}

Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc.


Slide 125
How to code control
statements

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 126
Objectives
Applied
 Code if statements including those that use else and else if clauses.
 Code switch statements including those that use fall through and
default cases.
 Code while, do-while, and for statements including those that use
break and continue statements.

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 127
Objectives (continued)
Knowledge
 Describe type coercion and distinguish between the equality and
identity operators.
 Describe these relations operators: <, <=, >, >=.
 Describe these logical operators: !, &&, ||.
 Describe how a flag variable works.
 Describe the order of precedence for the relational and logical
operators and explain how parentheses can be used to control that
order.

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 128
The equality operators
Operator Description
== Equal
!= Not equal

The identity operators


Operator Description
=== Equal
!== Not equal

Description
 The equality operators perform type coercion.
 The identity operators do not perform type coercion.

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 129
The relational operators
Operator Description
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal

Comparing strings to numbers


Expression Result
1 < "3" true
"10" < 3 false

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 130
Comparing strings to strings
Expression Result
"apple" < "orange" true
"apple" < "appletree" true
"Orange" < "apple" true
"@" < "$" false

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 131
The logical operators
Operator Name
! NOT
&& AND
|| OR

The NOT operator


!isNaN(number)

The AND operator


age >= 18 && score >= 680

The OR operator
state == "CA" || state == "NC"

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 132
The order of precedence
Order Operators
1 !
2 <, <=, >, >=
3 ==, !=, ===, !==
4 &&
5 ||

AND, OR, and NOT operators


!oldCustomer || loanAmount >= 10000 &&
score < minScore + 200

How parentheses can change the evaluation


(!oldCustomer || loanAmount >= 10000) &&
score < minScore + 200

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 133
An if clause with one statement and no braces
if ( rate === undefined ) rate = 0.075;

An if clause with one statement and braces


if ( qualified ) {
alert("You qualify for enrollment.");
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 134
If and else clauses with no braces
if ( age >= 18 )
alert("You may vote.");
else
alert("You may not vote.");

Why you should use braces


if ( age >= 18 )
alert("You may vote.");
else
alert("You may not vote.");
may_vote = false; // Not a part of the else clause.

Braces make your code easier to modify


if ( score >= 680 ) {
alert("Your loan is approved.");
}
else {
alert("Your loan is not approved.");
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 135
A nested if statement
var isLeapYear;
if ( year % 4 == 0 ) {
if ( year % 100 == 0 ) {
if ( year % 400 == 0) {
isLeapYear = true; // div by 4, 100, and 400
} else {
isLeapYear = false; // div by 4 & 100, not 400
}
} else {
isLeapYear = true; // div by 4, not 100
}
} else {
isLeapYear = false; // no div by 4
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 136
An if statement with one else if clause
if ( age < 18 ) {
alert("You're too young for a loan.");
}
else if ( score < 680 ) {
alert("Your credit score is too low for a loan.");
}

An if statement with an else if and an else clause


if ( age < 18 ) {
alert("You're too young for a loan.");
}
else if ( score < 680 ) {
alert("Your credit score is too low for a loan.");
}
else {
alert("You're approved for your loan.");
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 137
An if statement with else if clauses
and else clauses
rateIsValid = false;
if ( isNaN(rate) ) {
alert("Rate is not a number.");
}
else if (rate < 0) {
alert("Rate cannot be less than zero.");
}
else if (rate > 0.2) {
alert("Rate cannot be greater than 20%.");
}
else {
rateIsValid = true;
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 138
An if statement to determine
a student’s letter grade
if ( average >= 89.5 ) {
grade = "A";
} else if ( average >= 79.5 ) {
grade = "B";
} else if ( average >= 69.5 ) {
grade = "C";
} else if ( average >= 64.5 ) {
grade = "D";
} else {
grade = "F";
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 139
A switch statement with a default case
switch ( letterGrade ) {
case "A":
message = "well above average";
break;
case "B":
message = "above average";
break;
case "C":
message = "average";
break;
case "D":
message = "below average";
break;
case "F":
message = "failing";
break;
default:
message = "invalid grade";
break;
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 140
A switch statement with fall through
switch ( letterGrade ) {
case "A":
case "B":
message = "Scholarship approved.";
break;
case "C":
message = "Application requires review.";
break;
case "D":
case "F":
message = "Scholarship not approved.";
break;
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 141
The if statement for a Future Value application
// Test if input is valid
if (isNaN(investment) || investment <= 0) {
alert("Investment is not a valid number.");
} else if(isNaN(annualRate) || annualRate <= 0) {
alert("Annual rate is not a valid number.");
} else if(isNaN(years) || years <= 0) {
alert("Years is not a valid number.");

// If input is valid, calculate future value


} else {
// code that calculates the future value goes here
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 142
How to use a flag to get the same results
// Test if input is valid
var valid = true;
if (isNaN(investment) || investment <= 0) {
alert("Investment is not a valid number.");
valid = false;
} else if(isNaN(annualRate) || annualRate <= 0) {
alert("Annual rate is not a valid number.");
valid = false;
} else if(isNaN(years) || years <= 0) {
alert("Years is not a valid number.");
valid = false;
}

// If input is valid, calculate the future value


if ( valid ){
// code that calculates the future value goes here
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 143
A while loop to validate user input
var value = parseInt(
prompt("Please enter a number from 1 to 10") );

while ( isNaN(value) || value < 1 || value > 10 ) {


alert("You did not enter a number between 1 and 10.");
value = parseInt(
prompt("Please enter a number from 1 to 10") );
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 144
A while loop that finds the average
of a series of numbers
alert("Enter a non-number to stop.");

var total = 0, count = 0, number;


number = parseFloat( prompt("Enter a number") );
while ( !isNaN(number) ) {
total += number;
count++;
number = parseFloat( prompt("Enter another number") );
}

var average = total / count;

if ( isNaN(average) ) {
alert("You didn't enter any numbers.");
} else {
alert("The average is: " + average);
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 145
A while loop that counts dice rolls
until a six is rolled
var rolls = 1;
while ( random_number(1,6) != 6 ) {
rolls++;
}

alert("Number of times to roll a six: " + rolls);

// NOTE: See figure 7-5 for the random_number function

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 146
Nested while loops that find the average
and max to roll a six
var total = 0, count = 0, max = -Infinity;
var rolls;

while ( count < 10000 ) {


rolls = 1;
while ( random_number(1, 6) != 6 ) {
rolls++;
}
total += rolls;
count++;
if ( rolls > max ) max = rolls;
}

var average = total / count;

alert ("Average rolls: " + average);


alert ("Max rolls: " + max);

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 147
A do-while loop to validate user input
var value, valid;
do {
value = parseInt(
prompt("Enter a number between 1 and 10") );

if (isNaN(value) || value < 1 || value > 10) {


alert("You did not enter a valid number.");
valid = false;
} else {
valid = true;
}
} while ( !valid );

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 148
A do-while loop that counts dice rolls
until a six is rolled
var rolls = 0;
do {
rolls ++;
} while ( random_number(1,6) != 6 );

alert("Number of times to roll a six: " + rolls);

// NOTE: See figure 7-5 for the random_number function

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 149
A do-while loop that finds max and min values
alert("Enter a non-number to stop.");

var max = -Infinity, min = Infinity, number;


var value_entered = false, stop = false;

do {
number = parseFloat( prompt("Enter a number") );
if ( isNaN(number) ) {
stop = true;
} else {
value_entered = true;
if ( number > max ) max = number;
if ( number < min ) min = number;
}
} while ( !stop );

if (value_entered) {
alert("Max: " + max + ", Min: " + min);
} else {
alert("No numbers entered.");
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 150
A for statement
for ( var count = 1; count <= 10; count++ ) {
alert ( count );
}

A while statement that does the same thing


var count = 1;
while ( count <= 10 ) {
alert ( count );
count++;
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 151
A for loop to display even numbers from 2 to 10
for ( var number = 2; number <= 10; number += 2 ) {
alert( number );
}

A for loop to reverse a string


var message = "JavaScript", reverse = "";
for (var i = message.length - 1; i >= 0; i-- ) {
reverse += message.charAt(i);
}
alert(reverse); // Displays "tpircSavaJ"

A for loop to display all the factors of a number


var number = 18;
for ( var i = 1; i < number; i++ ) {
if ( number % i == 0 ) {
alert( i + " is a factor of " + number );
}
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 152
A for loop to determine if a number is prime
var number = 31, prime = true;

for ( var i = 2; i < number; i++ ) {


if ( number % i == 0 ) prime = false;
}

if (prime) {
alert( number + " is prime.");
} else {
alert( number + " is not prime.");
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 153
The break statement in a while loop
var number;
while (true) {
number = parseInt(
prompt("Enter a number from 1 to 10.") );

if ( isNaN(number) || number < 1 || number > 10 ) {


alert("Invalid entry. Try again.");
} else {
break;
}
}

The break statement in a for loop


var number = 31, prime = true;
for ( var i = 2; i < number; i++ ) {
if ( number % i == 0 ) {
prime = false;
break;
}
}

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 154
The continue statement in a for loop
for ( var number = 1; number <= 10; number++ ) {
if ( number % 3 == 0 ) continue;
alert(number);
}
// Only displays 1, 2, 4, 5, 7, 8, and 10

The continue statement in a while loop


var number = 1;
while ( number <= 10 ) {
if ( number % 3 == 0 ) {
number++;
continue;
}
alert(number);
number++;
}
// Only displays 1, 2, 4, 5, 7, 8, and 10

Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc.


Slide 155
How to create and use
functions

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 156
Objectives
Applied
 Create and call functions.
 Create functions that handle a variable number of parameters by
using the arguments property.
 Call functions by using the call and apply methods of the
functions

Knowledge
 Distinguish between a named function and an anonymous
function.
 Distinguish between passing an argument by value and passing an
argument by reference.

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 157
Objectives (continued)
 Describe the types of data that are passed by value and by
reference.
 Describe how lexical scope works, including the scope of a global
variable and the scope of a local variable.
 Describe what the this keyword refers to when it’s used within a
function.
 Describe how closure works with nested functions.
 Describe how recursive functions work.

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 158
How to create an anonymous function
var display_error = function ( message ) {
alert("Error: " + message);
}

How to create a named function


function isEven (value) {
return value % 2 == 0;
}

A function with no parameters


var coin_toss = function() {
return ( Math.random() > 0.5 ) ? "Heads" : "Tails";
}

A function with three parameters


var avg_of_3 = function( x, y, z ) {
return ( x + y + z ) / 3;
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 159
Calling a function that returns a value
var average = avg_of_3( 5, 2, 8 ); // average is 5
alert( coin_toss() ); // "Heads" or "Tails"

Calling a function that doesn’t return a value


display_error("Value out of range");

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 160
Terms
 An anonymous function isn’t given a name in its function
declaration.
 A named function is given a name in its function declaration.
 When you code a function, you code a list of parameters that are
accepted by the function.
 When you call a function, you code a list of arguments that will
be passed to the function.

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 161
A function that accepts a primitive type (a string)
var add_timestamp = function ( text ) {
var now = new Date();
text = text + " " + now.toString();
alert(text);
}

Code that passes an argument to the function


var message = "Error: Value out of range.";
add_timestamp(message); // displays message and timestamp

Code that displays the argument


alert(message); // message hasn't been changed

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 162
A function that accepts an object type (an array)
var uppercase_first = function ( x ) {
x[0] = x[0].toUpperCase();
}

Code that passes an argument to the function


var fruits = [ "apple", "orange" ];
uppercase_first(fruits);

Code that displays the argument


alert( fruits[0] ); // fruits has been changed!

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 163
Terms
 The primitive types are numbers, strings, and Booleans.
 When a primitive type is passed to a function, it is passed by
value.
 When an object is passed to a function, it is passed by reference.

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 164
A function that uses local and global scope
var display_message = function() {
if ( message == undefined ) {
var message1 = "Unknown message.";
alert ( message1 ); // local scope
} else {
alert(message); // global scope
}
}

Global var is available to all functions


display_message(); // Displays "Unknown message."
var message = "Test.";
display_message(); // Displays "Test."

Local var is only available within the function


alert ( message1 ); // Causes runtime error

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 165
Named functions are created before execution
alert( coin_toss() ); // Displays Heads or Tails

function coin_toss() {
return (Math.random() > 0.5) ? "Heads" : "Tails";
}

Anonymous functions are created in sequence


alert( coin_toss() ); // Causes a runtime error

var coin_toss = function () {


return (Math.random() > 0.5) ? "Heads" : "Tails";
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 166
Terms
 The scope of a variable or function determines what code has
access to it.
 JavaScript uses lexical scope.
 Any variable created outside of a function has global scope and is
available to all functions.
 Any variable created inside a function has local scope and is only
available within that function.

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 167
A function that uses the arguments property
var isEven = function (value) {
return arguments[0] % 2 == 0;
}

How to determine the number of arguments


var count_args = function () {
alert("Number: " + arguments.length );
}

count_args( 1, "Text", true ); // Displays "Number: 3"

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 168
A function that handles fewer arguments
var pad_left = function(text, width, pad) {
if ( arguments.length < 2 ) return "";
if ( arguments.length == 2 ) pad = " ";
while( text.length < width ) {
text = pad + text;
}
return text;
}

alert( "Welcome to " + pad_left("JavaScript", 15) );


// Displays "Welcome to JavaScript"

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 169
A function that handles more arguments
var average = function () {
if ( arguments.length == 0 ) return 0;
var sum = 0;
for ( var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum / arguments.length;
}

alert ( average(8, 15, 5, 10) ); // Displays 9.5

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 170
A function that uses the this keyword
var this_test = function () {
if (this === window) {
alert("Window object.");
} else {
alert( this );
}
}

How to use the call and apply methods


this_test(); // Displays "Window object."
this_test.call("Test String"); // Displays "Test String"
this_test.apply(456.72); // Displays 456.72

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 171
A $log function that uses the call method
var $log = function (message) {
if (typeof console == "object" &&
typeof console.log == "function") {
// sets this to console
console.log.call(console, message);
} else {
alert(message);
}
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 172
A $log function that uses the apply method
var $log = function () {
if (typeof console == "object" &&
typeof console.log == "function") {
// sets this to console
console.log.apply(console, arguments);
} else {
var message = "";
for ( var i = 0; i < arguments.length; i++ ) {
message += arguments[i] + " ";
}
alert(message);
}
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 173
XHTML for two counters
<p>
<span id="counter_a">0</span>
</p>
<p>
<input type="button" value="Increment" id="button_a" />
</p>
<p>
<span id="counter_b">0</span>
</p>
<p>
<input type="button" value="Increment" id="button_b" />
</p>

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 174
The JavaScript code
var $ = function (id) {return document.getElementById(id);}

var make_counter = function () {


var count = 0;
var increment = function () {
count++;
return count;
}
return increment;
}

var counter_a_increment = make_counter();


var counter_b_increment = make_counter();

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 175
The JavaScript code (continued)
var button_a_click = function() {
$("counter_a").firstChild.nodeValue =
counter_a_increment();
}

var button_b_click = function() {


$("counter_b").firstChild.nodeValue =
counter_b_increment();
}

window.onload = function () {
$("button_a").onclick = button_a_click;
$("button_b").onclick = button_b_click;
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 176
The code running in a web browser

Term
 In JavaScript, a nested function has access to the outer function’s
variables. This is called closure.

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 177
A recursive function that searches an array
var search = function(needle, haystack, lo, hi) {
if ( arguments.length == 2 ) {
lo = 0;
hi = haystack.length - 1;
}

var middle = Math.ceil( (hi + lo) / 2 );

if ( hi < lo ) return -1;


if ( hi == lo ) {
if ( needle == haystack[middle] ) {
return middle;
} else {
return -1;
}
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 178
A recursive function that searches an array (cont.)
if ( needle == haystack[middle] ) {
return middle;
} else if ( needle < haystack[middle] ) {
return search( needle, haystack, lo, middle - 1);
} else if ( needle > haystack[middle] ) {
return search( needle, haystack, middle + 1, hi);
}
}

Code that creates a sorted array of 256 numbers


var numbers = [];
for ( var i = 0; i < 256; i++) {
numbers[i] = random_number(1,1000);
}

var numeric_order = function (a,b) {


if ( a < b ) return -1;
if ( a > b ) return 1;
return 0;
}
numbers.sort(numeric_order);

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 179
Code that uses the search function on the array
var number, position;
do {
number =
prompt("Number to find (click cancel to quit):");

if ( number == null ) break;

number = parseInt(number);
if ( isNaN(number) ) continue;

position = search(number, numbers);


if ( position == -1 ) {
alert(number + " is not in the list.");
} else {
alert(number + " is at position " + position + ".");
}
} while ( true );

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 180
The Invoice application

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 181
The XHTML file (excerpt)
<head>
<title>Invoice Manager</title>
<link rel="stylesheet" type="text/css"
href="invoice.css" />
<script type="text/javascript" src="invoice_library.js">
</script>
<script type="text/javascript" src="invoice.js">
</script>
</head>

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 182
The XHTML file (continued)
<body>
<div id="content">
<h1>Invoice Manager</h1>
<div class="formLayout">
<label for="item_code">Item Code:</label>
<input type="text" name="item_code"
id="item_code" /><br />
<label for="item_name">Item Name:</label>
<input type="text" name="item_name"
id="item_name" /><br />
<label for="item_cost">Item Cost:</label>
<input type="text" name="item_cost"
id="item_cost" /><br />
<label for="item_qty">Quantity:</label>
<input type="text" name="item_qty"
id="item_qty" value="1" /><br />
<label>&nbsp;</label>
<input type="button" id="item_add"
value="Add Item" /><br />
</div>

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 183
The XHTML file (continued)
<p class="startInvoice">Current Invoice</p>
<p><textarea id="item_list" rows="5"
cols="80"></textarea></p>
<div class="formLayout">
<label for="subtotal">Subtotal:</label>
<input type="text" name="subtotal" id="subtotal"
class="disabled" disabled="disabled" /><br />
<label for="sales_tax">Sales Tax:</label>
<input type="text" name="sales_tax" id="sales_tax"
class="disabled" disabled="disabled" /><br />
<label for="total">Total:</label>
<input type="text" name="total" id="total"
class="disabled" disabled="disabled" /><br />
</div>
</body>
</html>

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 184
The invoice_library.js file
var pad_left = function(text, width, pad) {
if ( arguments.length < 2 || arguments.length > 3 ) {
return "";
}
if ( arguments.length == 2 ) {
pad = " ";
}
var result = text.toString();
while ( result.length < width ) {
result = pad + result;
}
return result;
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 185
The invoice_library.js file (continued)
var pad_right = function(text, width, pad) {
if ( arguments.length < 2 || arguments.length > 3 ) {
return "";
}
if ( arguments.length == 2 ) {
pad = " ";
}
var result = text.toString();
while ( result.length < width ) {
result = result + pad;
}
return result;
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 186
The invoice_library.js file (continued)
var get_item_list = function(item_list) {
if ( item_list.length == 0 ) {
return "";
}

var list, line_cost, item_cost, item_count = 0;


list = pad_right("Item Code", 10) + " ";
list += pad_right("Item Name", 40) + " ";
list += "Qty ";
list += "Item Cost ";
list += "Line Cost\n";
list += pad_right("", 10, "-") + " ";
list += pad_right("", 40, "-") + " ";
list += "--- ";
list += pad_right("", 9, "-") + " ";
list += pad_right("", 9, "-") + "\n";

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 187
The invoice_library.js file (continued)
for ( var i in item_list ) {
item_cost = parseFloat(item_list[i]["item_cost"]);
line_cost = item_list[i]["item_qty"] *
item_list[i]["item_cost"];
list += pad_right(item_list[i]["item_code"], 10)
+ " ";
list += pad_right(item_list[i]["item_name"], 40)
+ " ";
list += pad_left (item_list[i]["item_qty"], 3)
+ " ";
list += "$" + pad_left(item_cost.toFixed(2), 8)
+ " ";
list += "$" + pad_left(line_cost.toFixed(2), 8)
+ "\n";
}
return list;
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 188
The invoice_library.js file (continued)
var get_subtotal = function (item_list) {
var subtotal = 0, line_cost;
for ( var i in item_list ) {
line_cost = item_list[i]["item_qty"] *
item_list[i]["item_cost"];
subtotal += parseFloat( line_cost.toFixed(2) );
}
return subtotal;
}

var get_sales_tax = function (item_list) {


var subtotal = get_subtotal(item_list);
var sales_tax = subtotal * 0.07;
return parseFloat( sales_tax.toFixed(2) );
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 189
The invoice_library.js file (continued)
var get_total = function (item_list) {
var total = get_subtotal(item_list) +
get_sales_tax(item_list);
return parseFloat( total.toFixed(2) );
}

var invoice = [];

var $ = function(id) { return document.getElementById(id); }

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 190
The invoice_library.js file (continued)
var update_display = function () {
$("item_list").value = get_item_list(invoice);
$("subtotal").value = get_subtotal(invoice).toFixed(2);
$("sales_tax").value =
get_sales_tax(invoice).toFixed(2);
$("total").value = get_total(invoice).toFixed(2);
$("item_code").value = "";
$("item_name").value = "";
$("item_cost").value = "";
$("item_qty").value = "1";

$("item_code").focus();
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 191
The invoice_library.js file (continued)
var item_add_click = function() {
var item = [];
item["item_code"] = $("item_code").value;
item["item_name"] = $("item_name").value;
item["item_cost"] = parseFloat($("item_cost").value);
item["item_qty"] = parseInt($("item_qty").value);

if ( item["item_code"] == "" ) return;


if ( item["item_name"] == "" ) return;
if ( isNaN(item["item_cost"]) ) return;
if ( isNaN(item["item_qty"] ) ) return;

invoice.push(item);
update_display();
}

window.onload = function () {
$("item_add").onclick = item_add_click;
$("item_code").focus();
}

Murach’s JavaScript, C10 © 2009, Mike Murach & Associates, Inc.


Slide 192
How to create and use
arrays

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 193
Objectives
Applied
 Write code that works with arrays.
 Write code that works with associative arrays.
 Write code that works with arrays of arrays.

Knowledge
 Describe how an index is used to access the data that’s stored in
an array.
 Describe the length property of an array.
 Distinguish between the for statement and the for-in statement.

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 194
Objectives (continued)
 Describe these methods of the Array object: push, pop, shift,
unshift, splice, slice, concat, sort, reverse, and join.
 Describe the split method of the String object.
 Distinguish between an array and an associative array.
 Describe how an array of arrays can be used to store tabular data.

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 195
The syntax for creating an array
var arrayName = new Array(length);
var arrayName = [];

The syntax for creating an array and assigning


values
var arrayName = new Array(arrayList);
var arrayName = [arrayList];

Code that creates an array and assigns values


var rates = new Array(14.95, 12.95, 11.95, 9.95);
var names = ["Ted Lewis", "Sue Jones", "Ray Thomas"];

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 196
The syntax for referring to an element
arrayName[index]

Code that refers to the elements in an array


rates[2] // Refers to the third element
names[1] // Refers to the second element

An array that starts with four undefined elements


var rates = new Array(4);
rates[0] = 14.95;
rates[1] = 12.95;
rates[2] = 11.95;
rates[3] = 9.95;

An array that starts with no elements


var names = [];
names[0] = "Ted Lewis";
names[1] = "Sue Jones";
names[2] = "Ray Thomas";

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 197
One property and one operator for an array
Property
length
Operator
delete

How to add an element to the end of an array


var numbers = [1, 2, 3, 4]; // array is 1, 2, 3, 4
numbers[numbers.length] = 5; // array is 1, 2, 3, 4, 5

How to add an element at a specific index


var numbers = [1, 2, 3, 4];
numbers[6] = 7; // 1, 2, 3, 4, undefined, undefined, 7

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 198
How to delete a number at a specific index
var numbers = [1, 2, 3, 4]; // 1, 2, 3, 4
delete numbers[2]; // 1, 2, undefined, 4

A sparse array with 999 undefined elements


var numbers = [1]; // 1
numbers[1000] = 1001; // 1 and 1001 with undefined between

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 199
Code that stores 1 through 10 in an array
var numbers = [];
for (var i = 0; i < 10; i++) {
numbers[i] = i + 1;
}

Code that displays the array


var numbersString = "";
for (var i = 0; i < numbers.length; i++) {
numbersString += numbers[i] + " ";
}
alert (numbersString);

The message that’s displayed

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 200
Code that computes sum and average
var totals = [141.95, 212.95, 411, 10.95];
var sum = 0;
for (var i = 0; i < totals.length; i++) {
sum += totals[i];
}
var average = sum / totals.length;

Code that displays the array, sum, and average


var totalsString = "";
for (var i = 0; i < totals.length; i++) {
totalsString += totals[i] + "\n";
}

alert ("The totals are:\n" +


totalsString + "\n" +
"Sum: " + sum.toFixed(2) + "\n" +
"Average: " + average.toFixed(2) );

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 201
The message that’s displayed

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 202
The syntax of a for-in loop
for (var elementIndex in arrayName) {
// statements that access the elements
}

A for-in loop that displays the numbers array


var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var numbersString = "";
for (var index in numbers) {
numbersString += numbers[index] + " ";
}
alert(numbersString);

The message that’s displayed

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 203
The difference between for and for-in loops
var names = ["Mike", "Anne", "Ray"];
names[4] = "Joel";
names[names.length] = "Pren";
delete names[2];

// The for loop


var namesString1 =
"The elements displayed by the for loop:\n\n";
for (var i = 0; i < names.length; i++) {
namesString1 += names[i] + "\n";
}

// The for-in loop


var namesString2 =
"The elements displayed by the for-in loop:\n\n";
for (var i in names) {
namesString2 += names[i] + "\n";
}

alert (namesString1);
alert (namesString2);

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 204
The messages of the for and the for-in loops

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 205
The methods of an Array object
push(elements_list)
pop()
unshift(elements_list)
shift()
reverse()
sort()
sort(comparison_function)
splice(start, number)
splice(start, number, elements_list)
slice(start, number)
concat(array_list)
join(separator)
toString()
toLocaleString()

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 206
How to use the push and pop methods
var names = ["Mike", "Anne", "Joel"];
names.push("Ray", "Pren");
var removedName = names.pop(); // removedName is Pren
alert (names.join()); // Mike,Anne,Joel,Ray

How to use the unshift and shift methods


var names = ["Mike", "Anne", "Joel"];
names.unshift("Ray", "Pren");
removedName = names.shift(); // removedName is Ray
alert (names.join()); // Pren,Mike,Anne,Joel

How to use the splice method


var names = ["Mike", "Anne", "Joel", "Pren"];
names.splice(2, 1); // Mike,Anne,Pren
names.splice(2, 1, "Judy"); // Mike,Anne,Judy
names.splice(2, 0, "Ray"); // Mike,Anne,Ray,Judy

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 207
How to use the slice and concat methods
var names = ["Mike", "Anne", "Joel", "Ray"];
var namesSlice = names.slice(0, 2);
alert (names.join()); // Mike,Anne,Joel,Ray

var namesConcat = names.concat(namesSlice);


alert (namesConcat.join()); // Mike,Anne,Joel,Ray,Mike,Anne

How to perform an alphanumeric sort


var names = ["Mike", "Anne", "Joel", "Ray", "Pren"];
names.sort(); // Anne,Joel,Mike,Pren,Ray

var numbers = [520, 33, 9, 199];


numbers.sort(); // 199,33,520,9

How to perform a numeric sort


var comparison = function(x, y) {
return x - y;
}
var numbers = [520, 33, 9, 199];
numbers.sort(comparison); // numbers is 9, 33, 199, 520

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 208
How to use the reverse method
var names = ["Mike", "Anne", "Joel", "Ray", "Pren"];
names.reverse(); // Pren,Ray,Joel,Anne,Mike

How to use the join and toString methods


var names = ["Mike", "Anne", "Joel", "Ray"];
alert (names.join()); // Mike,Anne,Joel,Ray
alert (names.join(", ")). // Mike, Anne, Joel, Ray
alert (names.toString()); // Mike,Anne,Joel,Ray

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 209
A String method that creates an array
split(separator, limit) // returns an array

How to split a string into an array by spaces


var fullName = "Ray L Harris";
var nameParts = fullName.split(" "); // creates an array
alert (nameParts.length); // 3
alert (nameParts.join()); // Ray,L,Harris
var lastName = nameParts[2];
alert (lastName); // Harris

How to split a string into an array by hyphens


var date = "1-2-2009";
var dateParts = date.split("-"); // creates an array
alert (dateParts.length); // 3
alert (dateParts.join("/")); // 1/2/2009

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 210
How to split a string into an array of characters
var fullName = "Ray Harris";
var nameCharacters = fullName.split("");
alert (nameCharacters.length); // 10
alert (nameCharacters.join()); // R,a,y, ,H,a,r,r,i,s

What if the string doesn’t contain the separator?


var date = "1-2-2009";
var dateParts2 = date.split("/");
alert (dateParts2.length); // 1
alert (dateParts2.join()); // 1-2-2009

How to get one element from a string


var fullName = "Ray L Harris";
var firstName = fullName.split(" ", 1);
alert (firstName.length); // 1
alert (firstName); // Ray

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 211
How to create an associative array
var item = [];
item["itemCode"] = 123;
item["itemName"] = "Visual Basic 2008";
item["itemCost"] = 52.5;
item["itemQuantity"] = 5;

alert( item.length ); // Displays 0

How to add an element to the associative array


item["lineCost"] =
(item["itemCost"] * item["itemQuantity"]).toFixed(2);

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 212
How to retrieve and display the elements
alert ("Item elements:\n\nCode = " + item["itemCode"] +
"\nName = " + item["itemName"] +
"\nCost = " + item["itemCost"] +
"\nQuantity = " + item["itemQuantity"] +
"\nLine Cost = " + item["lineCost"]);

The message that’s displayed

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 213
How to use a for-in loop with the associative array
var result = "Item elements:\n\n";
for ( var i in item ) {
result += i + " = " + item[i] + "\n";
}
alert(result);

The message that’s displayed

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 214
Code that creates an array of arrays
var timesTable = []; // create an empty array
for (var i = 0; i < 5; i++) {
timesTable[i] = []; // add 5 empty arrays
}

Code that adds values to the array of arrays


for (var i = 0; i < 5; i++) {
for (var j = 0; j < 5; j++) {
timesTable[i][j] = i * j;
}
}

Code that refers to elements in the array of arrays


alert (timesTable[1][1]); // displays 1
alert (timesTable[4][3]); // displays 12

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 215
Code that creates an array
var invoice = []; // create an empty array
var item1 = [], item2 = []; // create 2 empty arrays

Code that adds the first associative array


item1["itemCode"] = 123;
item1["itemName"] = "Visual Basic 2008";
item1["itemCost"] = 52.5;
item1["itemQuantity"] = 5;
invoice.push(item1); // add item1 to invoice

Code that adds a second associative array


item2["itemCode"] = 456;
item2["itemName"] = "C++ 2008";
item2["itemCost"] = 52.5;
item2["itemQuantity"] = 2;
invoice.push(item2); // add item2 to invoice

Code that refers to the elements


alert (invoice[0]["itemCode"]); // displays 123
alert (invoice[1]["itemName"]); // displays C++ 2008

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 216
Terms
 An array can store one or more elements.
 The length of an array is the number of elements in the array.
 To refer to the elements in an array, you use an index.
 A sparse array is a large array with few defined elements.
 An associative array uses strings as the indexes.
 In an array of arrays, each element in the first array is another
array.

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 217
The Task List Manager application

The XHTML ids


add_task task_list
sort_tasks delete_task

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 218
The JavaScript code
var task_list = [];

var $ = function (id) { return document.getElementById(id);


}

var update_task_list = function () {


if ( task_list.length == 0 ) {
$("task_list").value = "";
} else {
var list = "";
for ( var i in task_list ) {
list += (parseInt(i)+1) + ": "
+ task_list[i] + "\n";
}
$("task_list").value = list;
}
}

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 219
The JavaScript code (continued)
var add_task_click = function () {
$("add_task").blur();
var task = prompt("Enter a task:", "");
if ( task != "" && task != null) {
task_list[task_list.length] = task;
update_task_list();
}
}

var sort_tasks_click = function () {


$("sort_tasks").blur();
task_list.sort();
update_task_list();
}

var delete_task_click = function () {


$("delete_task").blur();
if ( task_list.length == 0 ) {
alert("No task to delete.");
return;
}

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 220
The JavaScript code (continued)
var to_delete = prompt(
"Enter the task number to delete:", "");
if (to_delete == null) { return; }

to_delete = parseInt(to_delete);
if ( isNaN(to_delete) ) {
alert("You did not enter a number.");
return;
}
if ( to_delete < 1 ) {
alert("The task number is too low.");
return;
}
if ( to_delete > task_list.length ) {
alert("The task number is too high.");
return;
}
to_delete--;
task_list.splice(to_delete, 1);
update_task_list();
}

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 221
The JavaScript code (continued)
window.onload = function() {
$("add_task").onclick = add_task_click;
$("sort_tasks").onclick = sort_tasks_click;
$("delete_task").onclick = delete_task_click;
update_task_list();
}

Murach’s JavaScript, C9 © 2009, Mike Murach & Associates, Inc.


Slide 222
How to create and use
objects

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 223
Objectives
Applied
 Write code that creates objects from the Object type.
 Write code that creates and uses your own object types.
 Write code that adds properties and methods, including cascading
methods, to object types, including native object types such as the
String, Date, and Math object types.
 Write code that uses the delete operator to work with objects.
 Write code that uses the for-in statement to loop through an
object’s enumerable properties.
 Write code that uses the in, instanceof, and typeof operators to
work with objects.

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 224
Objectives (continued)
Knowledge
 Describe the inheritance hierarchy for these JavaScript object
types: Object, String, Number, Boolean, Date, Array, and
Function.
 Describe how two variables can refer to the same object.
 Describe how the constructor function and the prototype object
allow you to create your own object types.
 Identify the object referred to by the this keyword in a constructor
function.
 Describe how inheritance works.

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 225
The JavaScript hierarchy of some
of the native object types
Object

String Number Boolean Date Array Function

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 226
The syntax for creating a new object
var variable_name = new ObjectType(arguments);

How to create a new object of the Date type


var today = new Date();

How to create a new object of the Object type


var invoice = new Object();

How to create a new object of the String type


var lastName = "Harris"; // = new String("Harris");

How to create a new object of the Number type


var taxRate = .0875; // = new Number(.0875);

How to create a new object of the Boolean type


var validFlag = true; // = new Boolean(true);

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 227
The length property of a String object
length = lastName.length;

The toFixed method of a Number object


formattedRate = taxRate.toFixed(4);

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 228
Two ways to create an object of the Object type
var invoice = new Object(); // with the new keyword
var invoice = {}; // with braces

How to initialize an object with one property


var invoice = { taxRate: 0.0875 };

How to initialize an object with one method


var invoice = {
getSalesTax: function( subtotal ) {
return ( subtotal * invoice.taxRate );
}
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 229
How to initialize an object with properties and
methods
var invoice = {
getSalesTax: function( subtotal ) {
return ( subtotal * invoice.taxRate );
},
getTotal: function ( subtotal, salesTax ) {
return subtotal + salesTax;
},
taxRate: 0.0875,
dueDays: 30
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 230
How to nest one object within another
var invoice = {
terms: {
taxRate: 0.0875,
dueDays: 30
}
}

How to refer to a nested object


alert( invoice.terms.taxRate ); // Displays 0.0875
alert( invoice["terms"]["dueDays"] ); // Displays 30

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 231
How to add properties and methods to an object
// Using the dot operator
invoice.taxRate = 0.0875; // property
invoice.getSalesTax = function(subtotal) { // method
return ( subtotal * invoice.taxRate );
};

// Using brackets
invoice["taxRate"] = 0.0875; // property

How to modify the properties of an object


invoice.taxRate = 0.095;

How to remove a property from an object


delete invoice.taxRate;
alert( invoice.taxRate ); // Displays undefined

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 232
Two variables that refer to the same object
var today = new Date();
var now = today;

A diagram that illustrates these references


today

Date object

now

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 233
How to delete an object
var today = new Date();
delete today;
alert(today); // Displays undefined

How to delete a reference to an object


var today = new Date();
var now = today;
delete today;
alert( today ); // Displays undefined
alert( now.getFullYear() ); // Displays the year

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 234
How to code constructor functions
// A constructor that creates an InvestmentTerms object
var InvestmentTerms = function (init_rate, init_years) {
// Define properties of the object
this.rate = init_rate;
this.years = init_years;
}

// A constructor that creates an Invoice object


var Invoice = function () {
this.items = [];
this.tax_rate = 0.07;
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 235
How to add methods to object types
// Add getMonths method to the InvestmentTerms type
InvestmentTerms.prototype.getMonths = function () {
return this.years * 12;
}

// Add the delete_item method to the Invoice type


Invoice.prototype.delete_item = function(item_code) {
if ( item_code in this.items ) {
delete this.items[item_code];
}
return this;
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 236
How to create a new instance of an object type
var terms = new InvestmentTerms(0.04, 10);
var invoice = new Invoice();

How to access a new object’s properties


alert (terms.rate); // Displays 0.04
alert (invoice.tax_rate); // Displays 0.07

How to use a new object’s methods


var months = terms.getMonths();
invoice.delete_item(item_code);

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 237
Terms
 To create your own object type, you code a constructor function
(or just constructor) with the name of the object type.
 Within a constructor, the this keyword refers to the object that is
created by the constructor.
 In JavaScript, every object type has a prototype object that
contains the properties and methods of that object type.

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 238
The Vehicle object type
var Vehicle = function (make, model) {
this.make = make;
this.model = model;
this.miles = 0;
this.last_oil_change = 0;
}

Vehicle.prototype.drive = function ( miles ) {


this.miles += miles;
return this;
}

Vehicle.prototype.change_oil = function () {
this.last_oil_change = this.miles;
return this;
}

Vehicle.prototype.need_oil_change = function () {
return ( this.miles - this.last_oil_change > 3000 );
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 239
The Car type that inherits the Vehicle type
var Car = function ( make, model, door_count, hatch_back ) {
this.make = make;
this.model = model;
this.door_count = door_count;
if ( arguments.length == 4 ) {
this.hatch_back = hatch_back;
} else {
this.hatch_back = false;
}
this.miles = 0;
this.last_oil_change = 0;
}

Car.prototype = new Vehicle();

Code that uses the Car object


var myCar = new Car("Univeral Imports", "Q", 2);

// Call methods from the Vehicle type


myCar.drive(2000).change_oil().drive(4000);

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 240
How to add a method to the Date object type
Date.prototype.isLeapYear = function () {
var year = this.getFullYear();
if ( year % 4 == 0 ) {
if ( year % 100 == 0 ) {
if ( year % 400 == 0) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
}

var opening = new Date( 2009, 1, 1 ); // Feb 1, 2009


alert( opening.isLeapYear() ); // Displays false

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 241
How to add a method to the String object type
String.prototype.reverse = function () {
var reverse = "";
for (var i = this.length - 1; i >= 0; i-- ) {
reverse += this.charAt(i);
}
return reverse;
}

var message = "JavaScript";


alert( message.reverse() ); // Displays "tpircSavaJ"

How to add a method to the Math object


Math.add = function( x, y ) {
return parseFloat(x) + parseFloat(y);
}

alert( "3" + "5" ); // Displays 35


alert( Math.add("3", "5") ); // Displays 8

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 242
An add method that is not a cascading method
Array.prototype.add_value = function (key, value) {
this[key] = value;
}

Chaining the add method calls won’t work


var pin_codes = [];
pin_codes.add_value("Mike", "123").add_value("Ray", "987");

The add methods must be called one at a time


var pin_codes = [];
pin_codes.add_value("Mike", "123");
pin_codes.add_value("Ray", "987");

Term
 A cascading method can be chained with other methods.

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 243
An add method that is a cascading method
Array.prototype.add_value = function (key, value) {
this[key] = value;
return this;
}

A delete method that is a cascading method


Array.prototype.delete_value = function (key) {
delete this[key];
return this;
}

Chaining the method calls does work


var pin_codes = [];
pin_codes.add_value("Mike", "123").add_value("Ray", "987");
pin_codes.add_value("Kelly", "456").delete_value("Ray");

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 244
The syntax of the for-in statement
for ( var property_name in object ) {
// code to execute
}

The objects used by the for-in loops that follow


var application = {
rate: 0.04,
years: 10
};

var invoice = {
getSalesTax: function( subtotal ) {
return ( subtotal * invoice.taxRate );
},
getTotal: function ( subtotal, salesTax ) {
return subtotal + salesTax;
},
taxRate: 0.0875,
dueDays: 30
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 245
A for-in loop with the application object
for ( var property in application ) {
alert( property + ": " + application[property] );
}

A for-in loop with the invoice object


var propList = "";
for ( var property in invoice ) {
propList += property + ": " + invoice[property] + "\n";
}
alert ( propList );

The propertyIsEnumerable method


application.propertyIsEnumerable("rate") // true
application.propertyIsEnumerable("propertyIsEnumerable")
//false

Term
 A for-in statement loops through all the defined properties of an
object that are enumerable.

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 246
Objects and variables for the following code
var application = {
rate: 0.04,
years: 10
};

function Invoice() {
this.items = [];
this.tax_rate = 0.07;
}
var invoice = new Invoice();

var today = new Date();


var testArray = [];
var testString = "123";
var testNumber = 123;

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 247
The in operator
alert( "rate" in application ); // Displays true
alert( "month" in application ); // Displays false
alert( "items" in invoice ); // Displays true

The instanceof operator


alert( today instanceof Object ); // Displays true
alert( today instanceof Date ); // Displays true
alert( application instanceof Object ); // Displays true
alert( application instanceof Date ); // Displays false
alert( invoice instanceof Object ); // Displays true
alert( invoice instanceof Invoice ); // Displays true

The typeof operator


alert( typeof application ); // Displays object
alert( typeof testArray ); // Displays object
alert( typeof testString ); // Displays string
alert( typeof testNumber ); // Displays number
alert( typeof application.rate ); // Displays number
alert( typeof Invoice ); // Displays function

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 248
The user interface for the Invoice application

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 249
The XHTML file (excerpt)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Invoice Manager</title>
<link rel="stylesheet" type="text/css"
href="invoice.css" />
<script type="text/javascript"
src="invoice_library.js"></script>
<script type="text/javascript"
src="invoice.js"></script>
</head>

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 250
The XHTML file (continued)
<body>
<div id="content">
<h1>Invoice Manager</h1>
<div class="formLayout">
<label for="item_code">Item Code:</label>
<input type="text" name="item_code"
id="item_code" /><br />
<label for="item_name">Item Name:</label>
<input type="text" name="item_name"
id="item_name" /><br />
<label for="item_cost">Item Cost:</label>
<input type="text" name="item_cost"
id="item_cost" /><br />
<label for="item_qty">Quantity:</label>
<input type="text" name="item_qty"
id="item_qty" value="1" /><br />
<label>&nbsp;</label>
<input type="button" id="item_add"
value="Add/Update Item" /><br />
</div>

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 251
The XHTML file (continued)
<div class="formLayout deleteForm">
<label for="item_delete_code">Item Code:</label>
<input type="text" name="item_delete_code"
id="item_delete_code" /><br />
<label>&nbsp;</label>
<input type="button" id="item_delete"
value="Delete Item" /><br />
</div>
<p class="startInvoice">Current Invoice</p>
<p><textarea id="item_list"
rows="5" cols="80"></textarea></p>

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 252
The XHTML file (continued)
<div class="formLayout">
<label for="subtotal">Subtotal:</label>
<input type="text" name="subtotal" id="subtotal"
class="disabled" disabled="disabled" /><br />
<label for="sales_tax">Sales Tax:</label>
<input type="text" name="sales_tax" id="sales_tax"
class="disabled" disabled="disabled" /><br />
<label for="total">Total:</label>
<input type="text" name="total" id="total"
class="disabled" disabled="disabled" /><br />
</div>
</body>
</html>

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 253
The invoice_library.js file
String.prototype.pad_left = function() {
if ( arguments.length < 1 || arguments.length > 2 ) {
return this;
}
var width = parseInt(arguments[0]);
var pad = " ";
if ( arguments.length == 2 ) pad = arguments[1];
var result = this;
while ( result.length < width ) {
result = pad + result;
}
return result;
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 254
The invoice_library.js file (continued)
String.prototype.pad_right = function() {
if ( arguments.length < 1 || arguments.length > 2 ) {
return this;
}
var width = parseInt(arguments[0]);
var pad = " ";
if ( arguments.length == 2 ) pad = arguments[1];
var result = this;
while ( result.length < width ) {
result = result + pad;
}
return result;
}

var Item_Info = function ( item_name, item_cost, item_qty )


{
this.item_name = item_name;
this.item_cost = parseFloat(item_cost);
this.item_qty = parseInt(item_qty);
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 255
The invoice_library.js file (continued)
var Invoice = function () {
this.items = [];
this.tax_rate = 0.07;
}

Invoice.prototype.add_item = function(item_code, item_info)


{
if ( ! item_info instanceof Item_Info ) return this;
if ( isNaN(item_info.item_cost) ) return this;
if ( isNaN(item_info.item_qty) ) return this;
if ( item_info.item_name == "" ) return this;
if ( item_code == "" ) return this;

item_code = item_code.toUpperCase();
if ( item_code in this.items ) {
delete this.items[item_code];
}
this.items[item_code] = item_info;
this.sort_by_code();
return this;
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 256
The invoice_library.js file (continued)
Invoice.prototype.delete_item = function(item_code) {
item_code = item_code.toUpperCase();
if ( item_code in this.items ) {
delete this.items[item_code];
}
return this;
}

Invoice.prototype.get_item_list = function() {
var item_list, line_cost, item_count = 0;
item_list = "Item Code".pad_right(10) + " ";
item_list += "Item Name".pad_right(40) + " ";
item_list += "Qty ";
item_list += "Item Cost ";
item_list += "Line Cost\n";
item_list += "".pad_right(10,"-") + " ";
item_list += "".pad_right(40,"-") + " ";
item_list += "--- ";
item_list += "".pad_right(9,"-") + " ";
item_list += "".pad_right(9,"-") + "\n";
for ( var code in this.items ) {

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 257
The invoice_library.js file (continued)
line_cost =
this.items[code].item_qty *
this.items[code].item_cost;
item_list +=
code.pad_right(10) + " ";
item_list +=
this.items[code].item_name.pad_right(40) + " ";
item_list +=
this.items[code].item_qty.toString().pad_left(3)
+ " ";
item_list +=
"$" +
this.items[code].item_cost.toFixed(2).pad_left(8)
+ " ";
item_list += "$" + line_cost.toFixed(2).pad_left(8)
+ "\n";
item_count++;
}
return (item_count == 0) ? "" : item_list;
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 258
The invoice_library.js file (continued)
Invoice.prototype.get_subtotal = function () {
var subtotal = 0, line_cost;
for ( var code in this.items ) {
line_cost =
this.items[code].item_qty *
this.items[code].item_cost;
subtotal += parseFloat( line_cost.toFixed(2) );
}
return subtotal;
}

Invoice.prototype.get_sales_tax = function () {
var subtotal = this.get_subtotal();
var sales_tax = subtotal * this.tax_rate;
return parseFloat( sales_tax.toFixed(2) );
}

Invoice.prototype.get_total = function () {
var total = this.get_subtotal() + this.get_sales_tax();
return parseFloat( total.toFixed(2) );
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 259
The invoice_library.js file (continued)
Invoice.prototype.sort_by_code = function () {
var code, codes = [], sorted_list = [];
for ( code in this.items ) codes.push(code);
codes.sort();
for ( code in codes ) {
sorted_list[ codes[code] ] =
this.items[ codes[code] ];
}
this.items = sorted_list;
return this;
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 260
The invoice.js file
var invoice = new Invoice();

var $ = function(id) { return document.getElementById(id); }

var update_invoice = function () {


$("item_list").value = invoice.get_item_list();
$("subtotal").value = invoice.get_subtotal().toFixed(2);
$("sales_tax").value =
invoice.get_sales_tax().toFixed(2);
$("total").value = invoice.get_total().toFixed(2);

$("item_code").value = "";
$("item_name").value = "";
$("item_cost").value = "";
$("item_qty").value = "1";
$("item_delete_code").value = "";

$("item_code").focus();
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 261
The invoice.js file (continued)
var item_add_click = function() {
var item_code = $("item_code").value;
var item_name = $("item_name").value;
var item_cost = $("item_cost").value;
var item_qty = $("item_qty").value;
var item_info =
new Item_Info(item_name, item_cost, item_qty);
invoice.add_item(item_code, item_info);
update_invoice();
}
var item_delete_click = function() {
var item_code = $("item_delete_code").value;
invoice.delete_item(item_code);
update_invoice();
}
window.onload = function () {
$("item_add").onclick = item_add_click;
$("item_delete").onclick = item_delete_click;
$("item_code").focus();
}

Murach’s JavaScript, C11 © 2009, Mike Murach & Associates, Inc.


Slide 262

You might also like