Programming with JavaScript

Programming with JavaScript
Maureen Smith
Professor, Saddleback College
CIM 271B - Tutorial 8
Objectives

In this tutorial you will:
•
•
•
•
•
•
•
Learn about the features of JavaScript
Send output to a Web page
Work with variables and data
Work with expressions and operators
Create a JavaScript function
Work with arrays and conditional statements
Learn about program loops
Session 8.1

In this session you will learn about the
development and features of JavaScript
• You’ll learn how to insert a JavaScript program
into an HTML file and how to hide that
program from older browsers that don’t support
JavaScript
• Finally, you’ll write a simple JavaScript
program to send customized output to a Web
page
Introduction to JavaScript

So far you’ve created only static Web pages
• Content and layout don’t change

Now will create Web pages whose content
and layout can be modified using built-in
programs
Server-Side and Client-Side
Programs

Have learn about accessing programs
involving forms and CGI scripts
• Program was stored on and run off server
• Some disadvantages:
• Users have to be connected to the Web server to run
CGI script
• Only the programmer of the script can alter the
script itself
• System administrator can place limitations on how
users access the script
• Also poses problems for system administrator
who has to be concerned about users
continually accessing the server, slowing it
down, and potentially overloading the system
• Prospect of even more users accessing server
could mean costly machine upgrades to handle
increased usage


These issues led to development of
programs, or scripts, that could be run from
browser on user’s own computer (client)
Client-side programs solve many of the
problems associated with CGI scripts
• Computing is distributed over the Web so no
one server is overloaded with handling
programming requests
• Web pages containing client-side scripts can be
tested locally without first uploading them to
server
• Client-side program is likely to be more
responsive to user (no wait for it to be sent over
Internet)
• However, client-side programs can never
completely replace CGI scripts
• If you need to run a search form or process a
purchase order, must be run from central computer
because it will most likely contain the database
The Development of Java and
JavaScript

Client-side programming came from
unexpected sources
• In early 90s, before Web became hugely
popular, programmers at Sun Microsystems
saw a day when even common consumer
devices (refrigerators, garage door openers)
would all be networked and capable of being
controlled by a single operating system
• They began to develop such an operating
system and based it on a language called Oak
• Oak was designed to be extremely reliable and
flexible
• Project did not succeed, but Oak worked so
well that Sun realized that it could be used on
Internet
• Was modified in 1995 and renamed Java

Sun also released a product called HotJava
which could run programs written in Java
• HotJava acted as a Java interpreter, which
means that it was able to interpret a Java
program and run it for the user
• Idea was that Java programs would run inside
Java interpreters, and because Java interpreters
could be created for different operating
systems, users could run Java in any
environment
• Including UNIX, Windows, DOS, Macintosh
operating systems
• Just as Web pages are designed to be platformindependent, so was Java

Advantages of Java were immediately
apparent
• Netscape incorporated a Java interpreter into
Navigator 2.0 making HotJava unnecessary for
Navigator users
• IE followed suit, beginning with version 3.0

With Java, user downloads a program,
called an applet, along with the Web page
• Browser, with built-in Java interpreter, is able
to run applet from user’s machine, freeing up
server for other purposes

One problem was that nonprogrammers
found it difficult to learn and use
• Also needed access to JDK (Java Developer’s
Kit) first to create the programs and compile
them
• Compiling is process by which a program is
converted from readable text file into an executable
file
• To simplify process, a team of developers from
Netscape and Sun created JavaScript--a subset
of Java with several differences
• Don’t need to work with developer’s kit or
compile a JavaScript program
• JavaScript commands can be inserted directly
into an HTML file rather than being placed in a
separate applet
• Saves browser from having to download a
separate file when page is accessed
• Not as powerful as Java, but simpler to use and
meets needs of most people
• Figure 8-3 highlights differences between Java
and JavaScript

Several versions of JavaScript have been
developed; most recent is 1.3
• Figure 8-4 lists versions and describes how
Netscape and IE support them
• IE actually uses a variation of JavaScript called
JScript
• For all practical purposes, JScript is identical to
JavaScript, but some JavaScript commands are
not supported in JScript, and vice versa
• Should always test JavaScript programs on
several browsers

Like HTML and CSS, development of a
JavaScript standard has been turned over to
an international body called ECMA
• European Computer Manufacturers Association
• Standard developed by them is called
ECMAScript, though browsers will still use
common name JavaScript
• Latest version is ECMA-262 which most major
browsers support, though some areas have not
been implemented

Other client-side programming languages
are also available
• Can use IE scripting language, VBScript

Because of the nearly universal support of
JavaScript, will use this language in your
work for North Pole Novelties
Running JavaScript

Task is to use JavaScript to create a page
that calculates remaining days until
Christmas for North Pole Novelties
• Andrew wants this info to appear on home
page, shown in Figure 8-5, so that customers
know how long they have to make their holiday
purchase

Home page shows number of days
remaining until Christmas
• But this info has been explicitly entered into
HTML file and works only if the date is June
27, 2001
• Andrew wants this info to be calculated
automatically for current date, whatever that
might be
• And if the current date is between December 25
and December 31, wants page to display
“Happy Holidays from North Pole Novelties”

First task is to create and run a simple
JavaScript program that sends output to
Web page
• A JavaScript program is run by browser either
when the page is first loaded, or in response to
an event such as clicking a button or hovering
over a hyperlink
• Will create a program that is run when browser
loads home page

There are two ways to create a JavaScript
program
• Can place commands directly into HTML file
• Can also place commands in an external file
• Placing program in an external file allows you
to hide the program code from user, whereas
source code placed directly in HTML file can
be viewed by anyone
• However, an external file must be stored on
server--added task of transferring both the Web
page and JavaScript file to user
• Generally, the more complicated and larger the
JavaScript program, the more likely you are to
place it in an external file
• Will enter the code directly into the HTML file

When you place JavaScript code directly
into the HTML file, need some way of
distinguishing it from text that you want to
appear on page
• Otherwise browser might start displaying your
JavaScript commands
• So this with the <SCRIPT> tag
Using the <SCRIPT> Tag

<SCRIPT> tag is a two-sided tag that
identifies beginning and end of a client-side
program
<SCRIPT SRC=URL LANGUAGE=“language”>
Script commands and comments</SCRIPT>
• where URL is URL or filename of external
document containing program code and
language is language program is written in
• SRC property is required only if you place
program in separate file
• LANGUAGE property is needed so browser
knows which interpreter to use
• Default LANGUAGE is JavaScript, and if you
omit this property, browser will assume
program is written in JavaScript

Program can be placed anywhere within
HTML file
• Either within <HEAD> tags or <BODY> tags
• Many programmers favor placing their
programs between <HEAD> tags in order to
separate programming code from content
• Others favor placing programs in page’s body,
at location where output is generated and
displayed; we will do both
Hiding Your Script from Older
Browsers

Older browsers that do not support
JavaScript present a problem
• If they encounter JavaScript, will attempt to
display them on page, treating script as part of
content
• To avoid this, can hide script using comment
tags

Have already used comment tags
• JavaScript supports similar comment tags,
using a set of double slashes (//) at beginning of
a line to tell browser to ignore line and not
interpret it as a JavaScript command

By combining HTML comment tag and
JavaScript comment symbols, can hide
program from browsers that don’t support
<SCRIPT> tag
<SCRIPT LANGUAGE=“JavaScript”>
<!-- Hide this script from browsers that don’t
support JavaScript
JavaScript commands
// Stop hiding from other browsers -->
</SCRIPT>

When older browser encounters this code,
first ignores <SCRIPT> tag
• Next line it sees is start of HTML comment tag
which doesn’t close until > symbol in secondto-last line
• So everything in JavaScript program is ignored
• Final </SCRIPT> tag is similarly ignored

Browser that supports JavaScript recognizes
the <SCRIPT> tag and will ignore any
HTML tags found between on and off tags
• Passes the comment tag in second line and
processes JavaScript program as written
• JavaScript comment (starting with //) is there to
help other users understand and interpret code

Ready to insert code in order to hide the
script from older browsers
• Delete HTML tags already in file that has date
info because will eventually replace them with
a program that works for any date
• See NPN.html

With <SCRIPT> tags and comments in
place, next task is to write a JavaScript
program that sends output to page
• Because you haven’t yet learned how to either
determine current date or calculate number of
days until Christmas, this program will display
a simple text string
Sending Output to a Web Page

JavaScript provides two methods to display
text:
• The document.write() and document.writeln()
method
document.write(“text”);
document.writeln(“text”);
• where text is a string of characters you want to
appear on page
• Following will display “Only 45 days until
Christmas”
document.write(“Only 45 days until Christmas”);

Both methods reflect the object-oriented
nature of JavaSript
• Here “document” is an object (the page that
browser is accessing) and “write” or “writeln”
are actions that can be applied to the document
• For now, when term “method” is used,
understand that it means an action applied to
something existing on page or in browser

Most of the time will use document.write()
method
• Document.writeln() method differs from
document.write() in that it attaches a carriage
return to end of each text string sent to page
• Becomes relevant only when text string is
preformatted with <PRE> tag for which
browser recognizes existence of carriage
returns

Text string created with document.write()
method is enclosed within double or single
quotation marks
• Allows you to include single/double quotation
marks as part of text string
document.write(“Come meet David ‘Bud’
Davis”);
• will display text Come meet David ‘Bud’ Davis
(including single quotation marks)
• Can display double quotation marks by
enclosing text string within single quotation
marks

Not limited to displaying only text
• Can also include HTML tags in text string to
format text and insert images
document.write(“<H3>News Flash!</H3>”);
• displays text News Flash! formatted with <H3>
header tag

Most JavaScript commands and names are
case-sensitive
• Browser will not recognize
“Document.Write()” and give error message

Each JavaScript command line ends with a
semicolon to distinguish it from next
command line in program
• Sometimes semicolon is optional, but should
still use it to make code easier to follow

Will now add document.write() method to
JavaScript program just created in
NPN.html file

Will create a simple program to display the
number of days until Christmas, assuming
that the current date is December 15, 2001
• See NPN_10.html

Have completed first JavaScript program!
• Does nothing more than display text you could
have entered directly, but it’s a program you’ll
build upon to perform more sophisticated tasks
Session 8.2

In this session you will learn some of the
fundamentals of JavaScript language
• Will learn how to create variables and how to
work with different data types
• Will learn about expressions and operators and
how to use them to change the variable values
• Finally, will create your own JavaScript
function and use it in a program
Working with Variables and Data

Have inserted text using document.write()
method
• Had to specify text explicitly; program did not
more than as if you had placed the text directly
• Next task is to have your program determine
current date and display it on the page

To do this, will create a JavaScript variable
• A variable is a named element used to store and
retrieve info
• Useful because they can store info created in
one part of the program and use that info in
another part
• Could create a variable named “Year” to store value
of the current year and then use the Year variable at
different locations in your program
• To assign value 2001 to variable “Year”:
Year=2001;


With Year variable assigned a value, can use
document.write() method to display this
value:
document.write(Year);
This code would cause text “2001” to
appear
• Can also combine text with the variable value
by using a plus symbol (+)
document.write(“The year is “ + Year);
• This will display text The year is 2001

In your program you won’t explicitly enter
date info
• Instead, your program will determine current
date and year for you and store that info in a
variable so you can use date from variable later
in the program
• For now will learn about variables by entering a
fixed value

Following restrictions apply to variable
names:
• First character must be either a letter or an
underscore (_)
• Rest of the characters can be letters, numbers,
or underscores
• Variable names cannot contain spaces
• Cannot use words that JavaScript has reserved
for other purposes
• Cannot name a variable “document.write”

Variable names are case-sensitive
• If your JavaScript isn’t working properly, might
be because you did not match case
Types of Variables

JavaScript supports four different types of
variables:
•
•
•
•

Numeric
String
Boolean
Null
A numeric variable can be any number
• 13, 22.5, -3.14159
• Numbers can be expressed in scientific
notation:
• 5.1E2 for the value 5.1 X 102, or 510
• A string variable is any group of characters
such as “Hello”
• Strings must be enclosed in double or single
quotation marks, but must be consistent
• ‘Hello’ is acceptable; “Hello’ is not
• Boolean variables are variables that can take
only one of two values, either true or false
• Use Boolean variables in situations in which you
want the program to act in a particular way,
depending on whether a condition, represented by
the Boolean variable, is true or false
• A null variable is a variable that has no value at
all
• Will happen when you have created a variable but
have not assigned it a value yet
• Once a value has been given, it will fall into one of
the other three data types
Declaring a Variable

Before you can use a variable, have to
create it
• Also known as declaring a value
• Declare a variable in JavaScript using the var
command or by assigning the variable a name
• Any of the following will create a variable
named “Month”:
var Month;
var Month=“December”;
Month=“December”;

First command creates the variable without
assigning it a value
• Second and third both create the variable and
assign it a value

Considered good style to include var
command whenever you create variables
• Helps you keep track of variables program will
use and makes it easier for others to interpret
your code
• Many programmers place all their variable
declarations at beginning along with comments
describing each variable’s purpose

Now will create some variables
• Today, which will contain info about current
date and time
• ThisDay, which will store current day of the
month
• ThisMonth, which will store a number
indicating the current month
• ThisYear, which will store a number indicating
the current year
• DaysLeft, which will store number of days until
Christmas
• See NPN_14.html

Now that you’ve declared the variables,
need to use JavaScript methods to calculate
variable values
Working with Dates

You will be working with dates as you try to
calculate number of days remaining until
December 25
• JavaScript does not provide a date data type as
some other programming languages do
• However, allows you to create a date object,
which is an object that contains date info
• Date object can then be saved as a variable in
your JavaScript program
• There are two ways to save a date as a variable:
variable=new Date(“month, day, year,
hours:minutes:seconds”)
• or
variable=new Date(year, month, day, hours,
minutes, seconds)
• where variable is the name of the variable that
will contain the date info and month, day, etc.
indicate the date and time
• Keyword new indicates that you’re creating a
new object
• Note that in the first command form you
specify the date using a text string and in the
second you use values
• Each of the following will create a variable
named “SomeDay” corresponding to a date of
June 15, 2001 and a time of 2:35p:
SomeDay=new Date(“June, 15, 2001, 14:35:00”);
or
SomeDay=new Date(2001, 5, 15, 14, 35, 0);

In this example, might notice a couple of
quirks in how JavaScript handles dates
• First, when you specify month with values
rather than text, must subtract 1 from the month
number
• JavaScript numbers the months starting with 0
for January up through 11 for December
• So in second command, date for June 15 is
expressed as (2001, 5, 15…)
• Also note that hours are expressed in military
(24-hour) time (14:35 rather than 2:35)

If you omit hours, minutes, and seconds
values, JavaScript assumes that the time is 0
for all
• If you omit both date and time info, JavaScript
returns current date and time, which it gets
from system clock
• Following command creates a variable named
“Today” that contains info about current date
and time:
Today=new Date();
• This is exactly what you will eventually want

Now that you’ve seen how to store date and
time info in a variable, can add that feature
• Eventually will want to set Today variable to
whatever current date is
• For now will use a specific date, October 15,
2001
• See NPN_15.html
Retrieving the Day Value

The Today variable now has all the date and
time info you need
• Unfortunately, it’s not in a form that will be
very useful
• Problem is that JavaScript stores date and time
info as a numeric value--number of
milliseconds since January 1, 1970
• All of JavaScript date and time functions are
numerical calculations of these hidden numbers
• Fortunately, you don’t have to do the
calculations that translate those numbers into
dates
• Can use built-in JavaScript date methods
• For each part of the date that you want visible
(or used in a calculation) need a date method to
retrieve its value

For example, second variable is ThisDay
which will contain the day of the month
• To get just that info, apply getDate() method to
date variable
DayValue=DateObject.getDate()
• where DayValue is name of a variable that will
contain the day of the month and DateObject is
date object or a date variable that contains the
complete date and time info
• To retrieve day of the month from Today
variable:
ThisDay=Today.getDate();
Retrieving the Month Value

Similar method exists for extracting value
of the current month
• Named getMonth()
• One important point about this method: because
JavaScript starts counting the months with 0 for
January, need to add 1 to the month number
JavaScript produces
• Following extracts current month number,
increases it by 1, and stores it in a variable
named ThisMonth:
ThisMonth=Today.getMonth()+1;

If current date is June 28, value of the
ThisMonth variable will be 6
Retrieving the Year Value

Final date method you’ll be using is
getFullYear() method
• Extracts the year value from date variable
• Following shows how you would store the
value of the current year in a variable named
ThisYear:
ThisYear=Today.getFullYear();
• If date stored in Today variable is October 15,
2001, value of getFullYear will be 2001

Why is method name GetFullYear() and not
simply getYear()?
• There is a getYear() method
• Problem with this date method is that it returns
only last two digits of year prior to 2000
• Instead of 1999, a date of 99 would be returned

The getYear() method returns a value of
2000 for year 2000
• So if you use it to calculate the number of years
between 1998 and 2000, would come up with
an answer of 1902 years
• Classic example of a Y2K bug that caused so much
concern
• The getFullYear() date method was introduced
in JavaScript 1.3 to correct this problem and is
supported by Netscape 4.5 and IE 4.0 or above
• So even though there is a getYear() date
method, should not use it if your program will
be calculating the difference in dates before and
after year 2000
• We will use GetFullYear() method


See Figure 8-10 for date methods
Ready to modify your program to work with
Today variable
• Will still use a specific date to test the program
• See NPN_18.html

To display this date info on your page, use
the command:
document.write(“Today is “+ThisMonth+”/
“+ThisDay+”/”+ThisYear+”<BR>”);

Haven’t calculated value of DaysLeft
variable yet
• At this point, will set this value equal to 999
and learn how to calculate true value shortly
• See NPN_18a.html

Have completed second item on your task
list by displaying date info
• Next step is to take those date values and use
them to calculate days remaining until
December 25
• Will work with expressions, operators,
functions
Working with Expressions and
Operators

Expressions are JavaScript commands that
assign values to your variables
• Have already worked with several expressions
• Used DaysLeft=999 to assign the value 999 to
DaysLeft variable
• Expressions will always use some sort of
assignment operator, such as = sign, but can
also contain variety of other operators, which
are elements that perform actions within the
expression
• A simple example is the + operator which
performs action of adding or combining two
elements
• Used the plus operator with following
command:
var ThisMonth=Today.getMonth()+1;

This command uses the + operator to
increase value returned by GetMonth()
method by 1
• Also used + operator to combine text strings:
document.write(“Only “ + DaysLeft + “days until
Christmas”);

In both examples, plus operator combines
two or more values or elements to create a
single value or element
Arithmetic Operators

The + operator belongs to a group of
operators called arithmetic operators
• Perform simple math calculations
• Figure 8-13 lists some of the arithmetic
operators and gives examples of how they work

Some of the arithmetic operators are also
known as binary operators because they
work on two elements in an expression
• There are also unary operators which work on
only one variable
• These include the increment (++), decrement
(--), and negation (-) operators
• The increment operator can be used to increase
the value of a variable by 1
• In the following, the value of the x variable is
100 and the value of the y variable is 101:
x=100;
y=x++;

The decrement operator has the opposite
effect, reducing the value of a variable by 1
• Following assigns the value 100 to the x
variable and 99 to the y variable:
x=100;
y=x--;

Finally, the negation operator simply
changes the sign of a variable:
x=-100;
y=-x;
• Here the value of the x variable is -100 and the
value of the y variable is opposite that, or 100
Assignment Operators

Expressions assign values using assignment
operators
• Have already seen one example, the equals (=)
sign
• JavaScript provides other assignment operators
that manipulate elements in an expression and
assign values within a single operation
• One of these is the += operator
• In JavaScript, the following create same result:
x= x + y;
x += y


In both the value of the x variable is added
to the value of the y and stored in x
An assignment operator can also be used
with numbers to increase a variable by a
specific amount
• To increase the value of the x variable by 2, can
use either of the following:
x= x + 2;
x += 2


Other assignment operators are shown in
Figure 8-14
Once you master the syntax, assignment
operators are efficient and compact
• As you start learning JavaScript, might prefer
using longer form for such expressions
The Math Object and Math
Methods

Another way of performing a calculation is
to use one of the built-in Math methods
• These methods are applied to an object called
the Math object
• Syntax for applying a math method:
value = Math.method(variable);
• where method is the method you’ll apply to a
variable and value is resulting value
• To calculate absolute value of a variable named
NumVar, use “abs” method:
AbsValue=Math.abs(NumVar);
• and the value of the AbsValue variable is set to
the absolute value of the NumVar variable
• Figure 8-15 lists other math methods
• As usual, case is important with JavaScript
commands
• Must type “Math” instead of “math” when
using these commands
Creating JavaScript Functions

Can use all the JavaScript different
expressions and operators to create your
own customized functions
• A function is a series of commands that either
performs an action or calculates a value
• Consists of the function name which identifies
it; parameters, which are values used by the
function; and a set of commands that are run
when the function is used
• Not all functions require parameters
• General syntax is:
function function_name(parameters) {
JavaScript commands
}
• where function_name is the name of the
function, parameters are the values sent to the
function, and JavaScript commands are actual
commands/expressions used by the function
• Note that curly braces are used to mark the
beginning and end of the commands in the
function
• Group of commands set off by curly braces is
called a command block and command blocks
exist for other JavaScript structures in addition
to functions

Function names, like variable names, are
case-sensitive
• Function name must begin with a letter or
underscore and cannot contain any spaces

Are not limited in the number of function
parameters a function contains
• Parameters must be placed within parentheses
(following function name) and each parameter
must be separated from others with a comma
Performing an Action with a
Function

To see how a function works, consider the
following which displays a message with
the current date:
function ShowDate(date) {
document.write(“Today is “ + date + “<BR>”);
}

Function name is ShowDate and it has one
parameter, date
• There is one line in the function’s command
block, which displays current date along with a
text string
• To run a function, you insert a JavaScript
command containing the function name and any
parameters it requires
• This process is known as calling a function
• To call the ShowDate function, could enter the
following commands:
var Today = “3/25/2001”;
ShowDate(Today);

Here the first command creates a variable
named “Today” and assigns it the text string
“3/25/2001”
• Second command runs ShowDate function,
using value of the Today variable as a
parameter
• Result of calling the ShowDate function is that
the following sentence appears:
Today is 3/25/2001
Returning a Value from a
Function

Can also use a function to calculate a value
• This process is also known as returning a value
and is achieved by placing a return command
along with a variable or value at the end of the
function’s command block
• Consider the following Area function:
function Area(Width, Length) {
var Size = Width*Length; return Size;
}

Area function calculates area of a
rectangular region, given its width and
length, and places the value in a variable
named “Size”
• Value of the Size variable is then returned by
the function
• A simple JavaScript program that uses this
function might appear as follows:
var x = 8;
var y = 6;
var z = Area(x,y);

First two commands assign values 8 and 6
to the x and y variables, respectively
• Values of both are then sent to Area function,
corresponding to Width and Length parameters
• Area function uses these values to calculate the
area, which it then returns, assigning that value
to the z variable
• Result is that 48 is assigned to the value of the z
variable
I hate math!
Placing a Function in an HTML
File

Where you place a function is important
• Function definition must be placed before the
command that calls the function
• If you try to call a function before it is defined,
might receive error message from browser
• Although not a requirement, one programming
convention is to place all function definitions
used in the page between the <HEAD> tags
• Ensures that each function definition has been
read and interpreted before being called by
JavaScript commands in body
• When browser loads HTML file containing a
function, browser passes over the function and
does not execute it
• Function will be executed only when called by
another JavaScript command
Create the XmasDays Function

Now have all the info you need to create
your own function, the XmasDays function
• Will have only one parameter, CurrentDay,
which is the current date
• Function will return one value, the number of
days between current date and December 25 of
the current year
• Function will have three variables:
• XYear: the current year
• XDay: the date of Christmas
• Initial value of this variable will be the date
“December 25, 2001”
• DayCount: the number of days between current
date and December 25
• This is the value that will be returned by the
function

Initial structure will look like:
function XmasDays(CurrentDay) {
var XYear=CurrentDay.getFullYear();
varXDay=new Date(“December, 25, 2001”);
var DayCount;
return DayCount;
}

First task is to set XDay to December 25 of
current year
• Might not be 2001!
• Do this using JavaScript setFullYear() method
XDay.setFullYear(XYear);

If current year is actually 2002, date stored
in XDay variable changes from “December
25, 2001” to “December 25, 2002”
• Next you calculate difference between
December 25 and current date
DayCount=XDay - CurrentDay;

There’s a problem
• Remember that JavaScript stores date info in
terms of milliseconds
• Taking difference between these two dates
calculates the number of milliseconds before
Christmas
• Hardly the info you want in the page!
• so you have to convert this value by dividing
the difference by the number of milliseconds in
one day; this would then be:
DayCount=(XDay CurrentDay)/(1000*60*60*24);
• because there are 1000 milliseconds in a
second, 60 seconds in a minute, 60 minutes in
an hour, 24 hours in one day

One more issue
• When user opens page, it’s unlikely that it will
be exactly a certain number of days before
Christmas
• More likely that it will be a certain number of
days, plus a fraction of a day
• Andrew doesn’t want that fractional part
displayed
• Will remove the fractional part by rounding the
value of DayCount to nearest day using round
Math method
DayCount = Math.round(DayCount);

Complete XmasDays function would then
look as follows:
function XmasDays(CurrentDay) {
var XYear=CurrentDay.getFullYear();
var XDay=new Date(“December, 25, 2001”);
XDay.setFullYear(XYear);
var DayCount=(XDay-CurrentDay)/1000*60*
60*24);
DayCount=Math.round(DayCount);
return DayCount; }

Now that you see what the XmasDays
function looks like will insert it into your
file
• Following standard practice, will place code
between <HEAD> tags
• Must place within a set of <SCRIPT> tags
• See NPN_25.html

Next have to insert a command to call the
function
• Recall that you previously set value of
DaysLeft variable to 999
• Will replace that command with one that calls
XmasDay function using Today variable
• DaysLeft variable will then be set to whatever
value is returned by XmasDays function
• See NPN_26.html

Have completed XmasDays function
• Andrew will test page you’ve created and get
back to you with any changes
Session 8.3

In this session you will learn how to add
decision-making capabilities to your
JavaScript program through the use of
conditional statements
• Will learn how to create and use arrays
• Will be introduced to program loops in order to
run a command block repeatedly
Working with Conditional
Statements

Only task remaining is to have the page
display a greeting message in place of day
count from December 25 through the 31st
• Need to create a conditional statement

A conditional statement is one that runs
only under certain conditions
• Are many types; one most used is the If
statement
if(condition){
JavaScript Commands}
• where condition if an expression that is either
true or false
• If condition is true, JavaScript commands in
command block are executed
• If condition is not true, no action is taken
Comparison and Logical
Operators

To create a condition, need to use two types
of operators: comparison and logical
• A comparison operator compares the value of
one element with that of another, creating a
Boolean expression that is either true or false
• Here are two examples:
x < 100;
y == 20;

If x is less than 100, this expression returns
the value true
• If x is 100 or greater, the expression is false
• In second example, y variable must have an
exact value of 20 for expression to be true
• Uses a double equal sign rather than a single one
• Single equal sign is an assignment operator and is
not used for making comparisons
• See Figure 8-19

A logical operator connects two or more
Boolean expressions
• One is the && operator which returns a value
of true only if all the Boolean expressions are
true
Following will be true only if x is less than 100
and y is equal to 20:
(x < 100) && (y == 20);
• See Figure 8-20
Using an If Statement

Now will see how these comparison and
logical operators work in an If statement
• if(Day==“Friday”){
• document.write(“The weekend is almost
here!”);}

Here, if the Day variable is equal to
“Friday,” text string is sent to page
• If Day is not equal to Friday, no action
Using an If…Else Statement

If statement runs a set of commands if
condition is true, but does nothing if false
• Sometimes will want If statement to run one set
of commands if condition is true and another if
condition is false
• An If…Else statement does this
if(condition){JavaScript Commands if true
} else {JavaScript Commands if false}
• where condition is an expression that is either
true or false and one set of commands is run if
true; another is run if false
if(Day==“Friday”){
document.write(“The weekend is almost here!”);
} else {
document.write(“Hello!”);}

If…Else structures can be nested, one
within another
if(Day==“Friday”){
document.write(“The weekend is almost here!”);
} else {
if(Day==“Monday”){
document.write(“Time for another work week”);
} else {
document.write(“Hello”);}
• Here text “The weekend is almost here!”
appears if day is Friday
• If day is Monday, text “Time for another work
week” appears
• On other days text “Hello” is generated

Have similar situation on North Pole page
• If current date is before December 25, page
should display number of days until Christmas
as calculated by XmasDays function
• Otherwise (if date is between December 25 and
31), should display a holiday greeting

Can distinguish between two situations by
creating an If…Else statement that looks at
the value returned by XmasDays function
• If that value is positive, current date is before
December 25 and page should display number
of days left
• If value is 0 or negative, current date is
December 25 or later and a holiday message
should be generated
• Code is:
if(DaysLeft > 0){
document.write(“Only “ + DaysLeft + “ days
until Christmas”);
} else {
document.write(“Happy Holidays from North
Pole Novelties”);}

Replace previous document.write() method
• See NPN_31.html
• See NPN_31a.html

Next will deal with some of the things
Andrew wants you to change
Using Arrays

Some feedback indicates that the date
format looks dry and uninviting
• Instead of “Today is 10/15/2001,” would rather
see “Today is October 15.”

No built-in JavaScript methods to display
dates in this format, so will create your own
• One way would be to create a series of
conditional statements based on value of
ThisMonth variable
• And then display a different text string for each
month
• Would require 12 nested If…Else statements!
• Can do it more simply by using arrays

An array is an ordered collection of values
referenced by a single variable name
var variable = new Array(size);
• where variable is name of array variable and
size is number of elements (values) in array
• Specifying a size is optional
• If you don’t specify a size, JavaScript will
automatically increase the size of the array as
you add more elements
• Code for creating an array named “Month”
would be:
var Month = new Array();

Once array is created, create values for each
individual element in the array
Month[1] = “January”;
Month[2] = “February”;
Month[3] = “March;
etc.

These commands create 12 new elements in
Month array
• Each element is identified by its index, which is
an integer that appears between the brackets
• Element “August” has an index value of 8 in
Month array
• First element in any array has an index value of
0, second item has 1, etc.
• In Month array, there are actually thirteen total
elements
• First element, Month[0] is not shown and has a
null value because you want the index number
to match the month number
• Seems counterintuitive to assign December an
index value of 11, though one could write a
program that way if one chose

Can also use variables in place of index
values
• If variable “IndexNumber” has value 5, then:
Month[IndexNumber]
• would be equal to value of Month[5] which is
“May”

Can use arrays to create a function named
“MonthTxt”
• Function has one parameter, “MonthNumber”
which is the number of a month, and the
function returns the name of that month
function MonthTxt (MonthNumber) {
var Month = new Array();
Month[1]=“January”;
Month[2]=“February”;
Month[3]=“March”;
etc.
return Month[MonthNumber];}
• Command MonthTxt(10) will return text
“October”
• This is what to add to HEAD section so that the
name of the month rather than the number will
show
• See NPN_34.html

Next will use value of the ThisMonth
variable to call this function and then store
results in a new variable named
“MonthName”
• Will then display name of month along with the
day of the month
• See NPN_35.html

Now need to remove test date and allow
page to use current date
• If you don’t specify a date value, current date
and time are automatically used
• See NPN_36.html
Working with Loops

Andrew may have future JavaScript
programs he wants you to run
• Programming often involves creating code that
does not run just once (as this page), but is
repeated an indefinite number of times

To provide this capability, must use a
program loop
• A program loop is a set of instructions that is
executed repeatedly
• Two types: loops that repeat a set number of
times before quitting, and loops that repeat until
a certain condition is met
• Create the first type using a For statement
The For Loop

The For loop allows you to create a group
of commands that will be executed a set
number of times through use of a counter,
which tracks the number of times the
command block has been run
• Set an initial value for the counter, and each
time the command block is executed, the
counter changes in value
• When counter reaches a value above or below a
certain stopping value, the loop ends
for(start; condition; update) {
JavaScript Commands }
• where start is starting value of counter,
condition is a Boolean expression that must be
true for loop to continue, and update specifies
how the counter changes in value each time the
command block is executed
• Like a function, the command block in the For
loop is set off by curly braces
• This loop displays several lines of text:
for(Num=1; Num<4; Num++) {
document.write(“The value of Num is “ + Num +
“<BR>”); }

The counter is the variable Num, which
starts with an initial value of 1
• As long as the value of Num is less than 4, the
condition for running the loop is met
• When value of Num reaches 4, loop stops
• Finally, expression “Num++” indicates that
each time the command block is run, value of
Num increases by 1 (example of increment
operator)
• When this For loop is run, following lines will
be generated:
The value of Num is 1
The value of Num is 2
The value of Num is 3
• and then the loop will end
The While Loop

Similar to For loop is the While loop
• Also runs a command group as long as a
specific condition is met
• But does not employ any counters
while(condition) {
JavaScript Commands }
• where condition is a Boolean expression that
can be either true or false
• As long as the condition is true, the group of
statements will be executed
var Num=1;
while(Num<4) {
document.write(“The value of Num is “ + Num);
Num++; }

Produces same result as For loop
• But used in different situations
• Would use a While loop instead of a For loop in
situations in which there is no counter variable
and you want more flexibility in halting the
program loop

Have completed your study of JavaScript