You are on page 1of 38

JavaScript programing statements (source code) may only be placed in certain locations within

HTML documents. When a browser with a JavaScript interpreter reads the JavaScript code it can
interpret and execute it so that some scripting task is completed. The simple document below
shows JavaScript source code placed within HTML <SCRIPT></SCRIPT> tags.

<HTML>
<HEAD>
<TITLE>The Script Tag 1</TITLE>

<SCRIPT>
document.write("<P>Script tags can be placed ")
document.write("in the Head of an HTML document.</P>")
</SCRIPT>

</HEAD>

<BODY>
<H1>The Script Tag: Example 1</H1>
<P>Script tags can also be placed in the Body of an HTML
document.</P>

<SCRIPT>
document.write("<P>Script tags will be ignored by ")
document.write("browsers that do not understand them.</P>")
</SCRIPT>

</BODY>
</HTML>

The Difference Between HTML and JavaScript


When the browser is reading in an HTML document it needs to be able to determine what text is
HTML and therefore what to display in the browser window, and what text is JavaScript source
code to be interpreted and executed. One way to let a browser know that part of an HTML
document is JavaScript is to enclose it inside the HTML <SCRIPT></SCRIPT> tags as illustrated
above. A browser that knows how to interpret JavaScript will attempt to interpret text inside the
script tags while reading and displaying HTML elements correctly.

Script tags are most often placed inside the head or body tags but may also be placed inside other
elements. Not every version of every browser correctly interprets JavaScript code when script
tags are placed inside other HTML elements such as table data cells.

JavaScript Statements and Source Code


The JavaScript text is often referred to as "source code" or just "code" and is made up of
statements. In the example above these two JavaScript statements:

document.write("<P>Script tags can be placed ")


document.write("in the Head of an HTML document.</P>")
write some text, consisting of an HTML paragraph, into the Web page being loaded by the
browser. The first statement writes the first half of the paragraph and the second writes the last
half. A full description of the parts of these statements is provided later but the net effect is to
make the text:

<P>Script tags can be placed in the Head of an HTML document.</P>

part of the HTML document. Use the View Page button above to see what happens when you
load a page containing this script into a Web browser.

Simple Statements
Here is a simpler JavaScript statement:

a = 2 + 3

The JavaScript interpreter will read in this line of text (or source code) and interpret it. The first
thing it will do is evaluate the right hand part of the statement after the " = ". This is the
expression 2 + 3 which the interpreter will evaluate to the number 5. The next thing it will do is
place the number 5 in the variable named a.

On its own, adding two plus three to get five and storing this number in a storage location named
a is not very exciting. But it does give an example of a simple JavaScript statement that contains
a simple expression. Statements can be more complicated and we will often need to look closely
at the expressions within them.

The Language="JavaScript" attribute

After Netscape introduced JavaScript, Microsoft introduced Visual Basic Script. Other scripting
langauges such as TCL may also be introduced. To make it simpler for the browser to determine
what programming language it is supposed to interpret the "language" attribute of the script tag
should always be used. In the example below <SCRIPT Language="JavaScript"> shows the
language is JavaScript. A browser that does not know how to interpret a language that is
specified in the script tag will not try.

<HTML>
<HEAD>
<TITLE>The Script Tag 2</TITLE>

<SCRIPT Language="JavaScript">
document.write("<P>JavaScript is not the only scripting
language ")
document.write("planned for the internet...</P>")
</SCRIPT>

</HEAD>

<BODY>
<H1>The Script Tag: Example 2</H1>

<SCRIPT Language="JavaScript">
document.write("<P>... so it is a good idea to declare the
language ")
document.write("you are using.</P>")
</SCRIPT>

</BODY>
</HTML>

COMMENT

Browsers that were distributed before the script tag was invented will correctly ignore tags they
do not "understand" such as the script tag. However, the JavaScript statements in between the
script tags will appear to these browsers as plain text. Most often older pre JavaScript browsers
will therefore render the JavaScript statements as paragraph text. This can be quite alarming if a
nicely designed page suddenly appears to someone as a long stream of meaningless code.

To get around this, the code can be hidden inside an HTML comment tag. An HTML comment
tag looks like this:

<!--This is a comment.-->

The opening <!-- part of the tag is usually placed on the next line right after the opening
<SCRIPT> tag and the closing part of the comment tag on the line just before the closing
</SCRIPT> tag. Just to make things more complicated the closing part of the HTML comment
tag must be preceded by the // characters that precede a JavaScript comment. Here is a short
example:

<SCRIPT Language="JavaScript">
<!--

// -->
</SCRIPT>

JavaScript statements are placed on the line after the <!-- and on lines before the // -->.

<HTML>
<HEAD>
<TITLE>The Script Tag 3</TITLE>

<SCRIPT Language="JavaScript">
<!-- //Hide Script from non-script browsers
document.write("<P>Browsers that do not understand the SCRIPT
tag " )
document.write("will ignore it and treat the script statements
")
document.write("inside the SCRIPT tags as HTML</P>")
// -->
</SCRIPT>

</HEAD>

<BODY>
<H1>The Script Tag: Example 3</H1>
<P>
<SCRIPT Language="JavaScript">
<!--
document.write("To do this we also surround the script
statements ")
document.write("with HTML comments. We also must preface the
closing ")
document.write("HTML comment tag with a JavaScript
comment //")
// -->
</SCRIPT>
</P>
</BODY>
</HTML>

Introducing the Document Object

One of JavaScript's strengths is its ability to work with objects. In object-oriented programming
and scripting languages, objects are a way to group or package together information and methods
of working with this information in a convenient way. In order to access or change the attributes
and contents of a Web page JavaScript provides a convenient object called the document object.
According to Netscape it "contains information on the current document, and provides methods
for displaying HTML output to the user." Here is a simple example broken down into four parts:

document.write("<P>Hello
World</P>")
document
An application object that contains information about the document loaded into a frame or
window. In the JavaScript documentation the information about an object is referred to as its
properties. Some of the properties of the document object can be changed others are read only.

 
The dot between the document object and the write() method is significant. The dot operator
allows you to access information (object properties) and methods for working with that
information in an object. The method or property of an object are on the right side of the dot
and the object is on the left side. For example, information about the document that contains
the script is available using the document object, the dot notation, and the names of properties
of the document object:

document.bgColor - makes it possible to get or set the background colour of the


document
document.location - contains the URL for the current document
document.lastModified - holds the date when the document was last modified on
server

write()
write() is a method (also called a function) belonging to the document object. write() will
output a string of text to the document. The round brackets following the word write are
required. Any JavaScript expression can be placed inside the round brackets. The expression will
be evaluated and the result converted, if necessary, to text to be written into the current Web
page.

"<P>Hello World</P>"
The double quoted text is a "literal" string of text including HTML markup. In this case the literal
text - the actual series of text characters - will be written into the current Web page.

Comments - Making Notes Inside Scripts

Introduction
Learning to read and understand source code is an important skill that takes some time and
practice to develop. It is important

 to help understand how other people have solved problems by reading their code;
 for correctly adapting other people's code for your own uses;
 for modifying and extending your own code as needed.
However, even trying to understand your own code after being away from it for some months
may be quite challenging. As your facility with a language improves, so will your ability to read
code. Even a skilled reader will find reading large amounts of code without the aid of some form
of documentation or descriptive text can still be very time consuming and difficult - even painful.
There are a number of things you should do to make understanding your code easier. These
include using descriptive variable names, formatting code so it is easier to read, and documenting
what you have done. JavaScript, like other languages, provides a way to include documentation
interspersed with JavaScript code to make the code easier to understand without interfering with
the execution of the script.

Comments
Comments are notes, usually written by the authors of a script, that documents how the script
works, how it can be used, and other information the writers of the script thought important to
note. Comments are text that is not interpreted by the JavaScript interpreter. To exclude
comments from being interpreted, they must be preceded by special characters or enclosed in
special characters.

//Single Line Comments

Two forward slashes // begin a comment that begins with the // and goes to the end of the line.
For example:

//Global Variables for the Quiz

var maxQuestions = 12 //Change this value if you want to allow more


questions.
var firstQuestion = 0 //Change this to any number from 0 to (maxQuestions -
1).

//Do Not edit code from this point on!

/*Multiline or Bracketed Comments */

The /* and */ characters can be used to enclose a comment. Here are some examples:

/* Global Variables for Quiz */

var maxQuestions = 12 /*Change this value if you want to allow more


questions.*/
var firstQuestion = 0 /*Change this to to any number from 0 to one less than
maxQuestions.*/

/* Do Not edit code from this point on! */

/**
* The checkAnswer(choice) method is called when the user selects an answer
* from a list of radio buttons. If the answer is correct the method returns
* true. If not it returns false. The method keeps track of the number of
* user guesses by incrementing a counter in the question object.
* The function expects one numeric parameter to be passed to it.
**/
function checkAnswer(choice){
this.guesses++
if (choice == this.answer)
return true
else
return false
}

While developing a script, comments are often left to the end to add to a source file. This is an
unfortunate practice as it increases the probability that few comments will ever be added to a
script as it nears completion. Adding comments as the script progresses is a good practice -
perhaps something like cleaning while you cook - the comments will be more complete and
writing them may help in clarifying what was being attempted as the work progresses.
Comments are particularly essential for scripts where numerous sections of code must work
together and where more complex tasks are being performed.

Variables and Values

Variables
A variable is a named area in computer memory that is used to store information and from which
information can be retrieved. As JavaScript is a relatively high-level language, it is not necessary
to know most of the details of how information is stored in memory by a JavaScript interpreter.
JavaScript provides for the automatic creation of variables whenever values are assigned to them.
Here is a very short example showing how the assignment operator ( = ) is used to assign a value
to a variable:

x = 3.4

A JavaScript interpreter will read this single line of code and do something like this:

1. break the text into three parts called tokens; Tokens are the separate words, names, and
symbols that have some meaning in JavaScript. In the statement above the tokens are:

x
=
3.4

2. evaluate the right most token 3.4 as a number value;


3. determine the centre token is the assignment operator and that the value 3.4 is to be assigned
to a variable;
4. if a variable named x does not already exist it is created;
5. the number 3.4 is stored in the variable named x.

In short, just by writing x = 3.4 a variable named x is both created and has a value stored in it.

Variables can also hold text in the form of a sequence (or "string") of characters:

y = "Let's go for lunch!"

In this case y is the variable that will hold the string. The = indicates that the string following it
should be stored in the variable y. The double quotes are used to indicate that the sequence of
characters within them is a literal string of text characters and not variable names or other
JavaScript to be interpreted. Strings may also be enclosed in single quotes. Note the single quote
inside the double quotes in this example is treated as a literal character.

Here are a few lines of code:

x = 3.4
y = "Let's go for lunch!"
x = y

In the last line of this example, the value stored in y is being assigned to x. The JavaScript
interpreter will copy the value in y into x. The 3.4 value that was in x will no longer exist and
both x and y will contain strings that contain the same characters: Let's go for lunch! If you
have experience with strongly typed languages such as Pascal, Java, or C++, or lower level
languages such as C, this can be a little confusing. In those languages a variable may only hold a
certain type of data. For example an integer or a string but not either at different times.
JavaScript is a "loosely typed" language. A variable may hold a number, string or other values at
different times.

Rules to Make this Work

How does the JavaScript interpreter tell the difference between a variable name like y and a
string of characters that are to be taken as a literal string of text such as "Let's go for
lunch!"? The quotes indicate that what is inside them are literally just a sequence of text
characters. And since variable names are not allowed to start with a quote character, there is no
problem. How does the interpreter tell the number 3.4 is a value and x is a variable? Because
JavaScript provides rules on what is a valid variable name and a valid number value. Variable
names must start with a letter or underscore _ character. The letters can be any upper or lower
case letter. After the first character, variable names may also contain numbers. Literal number
values must begin with a number, a decimal point followed by a number, or a + or - followed by
a number or decimal point followed by a number. Here are a few examples:

x1 = 3.14159
x2 = .5
x3 = -24e3
The e is another allowed character in a number that permits writing numbers in scientific
notation. -24e3 is that same as -24 × 103 or -24000.

Since a variable name cannot contain an = character the assignment operator is recognized as an
operator by the JavaScript interpreter. As mentioned, when the interpreter "reads" a line of code
it breaks it into separate pieces called tokens based on these types of rules. The line x1 =
3.14159 has three tokens: x1 is a variable, = is the assignment operator; and 3.14159 is a
numeric value.

Variables can store two other types of simple values: the two boolean values true or false and
the special null value. Here is an example of using Boolean values that is not very useful:

test = false
if (test) alert("test is true")

The Boolean value false is assigned to the variable test. How do we know false is not a
variable name? It is a reserved word. There are many words that cannot be used for variable
names because they have a special meaning in JavaScript. Other reserved words you can't use for
variable names include: var, function, Array, for, new, this, while, and import. There are
many others. In the previous short example an alert with the message "test is true" will
never appear because test contains the Boolean value false. If statements are described later.
Here is a more realistic bit of code:

if (a < 10) alert("a is too small")

In this case the expression a < 10 will be evaluated (is the value stored in a less than ten?). If a
is less than 10 the true value will be returned and the alert dialog will appear. If a is not less than
10 it will not. The actual literal Boolean values true and false are not always seen in scripts.
Usually, expressions are evaluated to produce a value of true or false and an action is taken, or
not taken, as a result.

Finally, the null value is a special value (and reserved word) that indicates that a variable does
not contain a usable value such as a number, string, or Boolean value. To make a variable null
assign null to it:

x = null

There are other more complex data types in JavaScript but numbers, strings, the two Boolean
values and null, are considered JavaScript's basic types of data.

Declaring a Variable

It is possible to declare a variable before actually assigning a value to it. To do this use the
special keyword var:

var x1
This means that there is a variable named x1 but that it has no value stored in it. In other words
it's contents are undefined. It is also possible to declare a variable explicitly and assign it a value
in one line:

var x1 = 'He said "be seeing you" as he left.'

Why bother when you get the same effect without using var? The short answer is that creating
variables with var inside a function creates variables that exist only inside the function and this
will be very useful later.

Problems with Variables


A loosely typed language may seem easier to use and more convenient than a strongly typed
language. Strongly typed languages require that every variable is declared as capable of holding
only one type of primitive value before it can be used. This is useful in avoiding all sorts of
errors because software tools (compilers and syntax aware editors) can catch many coding errors
very easily. Here are some errors you may run into as a result of JavaScript's loose typing. These
two short examples involve a simple typing error. Instead of typing x1, x has been typed once in
each example by mistake.

Typos Can Create New Variables


var x1 = 'He said "be seeing you" as he left.'
document.write(x1)
x = "New Message"
document.write(x1)

The intention here was to display two messages. First x1 is assigned a message that is written
into a Web page, then, x1 is supposed to be assigned a different message which will also be
written into the page. Unfortunately, the first message will show up twice in the document. Why?
Because of the typing error. The x = "New Message" creates a new variable named x when
what was intended was to assign another string to x1. Leaving the 1 off the variable name
resulted in a new variable being created. Since the string "New Message" was assigned to the
wrong variable, x1 still contains the original string which will be written into the document a
second time.

Accessing Undefined Variables


var x1 = 'He said "be seeing you" as he left.'
document.write(x)

This causes a runtime error. That is, a browser running this script will stop executing the script
and report the error: "Error: 'x' is undefined." Since x was never declared and never had a value
assigned to it, it does not exist and so cannot contain a value that can be written into the
document.

 
Making Decisions

Doing Something under Certain Conditions


In the random image project, a sequence of JavaScript statements were used to write an image
tag into a document. The JavaScript interpreter executed each statement in the order that it was
written in the HTML document. Every time the page is loaded or reloaded into a browser the
same sequence - in the same order - of statements are executed. Every general purpose
programming language has facilities to optionally execute statements. To do this some test
condition is evaluated to see if the optional statement should be executed. As a simple example,
suppose you wanted to write into a Web page the greeting Good Morning if the time of day
where your Web page was being browsed was before noon. It turns out this is fairly easy to do:

<HTML>
<HEAD>
<TITLE>Example of using a Date object and an if statement.</TITLE>
</HEAD>
<BODY>
<PRE>

This script provides an example of using the Date object to obtain


the hour of the day. The hour is used to write out a Good Morning
greeting if the time of day is before noon(12 hours).

<SCRIPT Language="JavaScript">

now = new Date() //create a Date object named: now

hour = now.getHours() //hours range from 0 to 23.

if (hour < 12)


document.writeln("Good Morning.")

</SCRIPT>
</PRE>
</BODY>
</HTML>

Here is a step-by-step description of this works:

now = new Date()

JavaScript provides a Date object that makes dealing with dates and times relatively easy. In this
line a new Date object named now is created using the new object creation operator. This is a
little different from how objects have been used in the examples up until now. String objects can
be created by assigning literal text to a variable and then treating that variable as though it has
properties and methods. The document and Math objects are created by the browser and
interpreter environments and are ready to use by any script executed by them. The Date object
however is designed to provide a way to create Date objects for a given date or time. The sample
line creates a Date object named now that contains the date and time when the now Date was
created. Like the String, document, and Math objects the Date object provides numerous useful
methods for working with dates and times.

hour = now.getHours()

Just one of the useful methods provided by the Date object is the getHours() method.
getHours()returns the hour of the time stored in the now variable. The hour is between 0
(midnight) and 23 (11 PM). If the time was between noon and less than 1 PM (13 hours)
getHours() will return 12.

if (hour < 12)


document.writeln("Good Morning.")

The simplest if statement has the standard format:

if (expression) statement

The expression part of the if statement is always placed inside round brackets following the if
keyword and is evaluated by the JavaScript interpreter to return a value of true or false. If the
expression is true then the statement following the expression is executed. If it is not, then the
statement is NOT executed. In the example, the expression being evaluated is hour < 12. It
contains three tokens:

 hour is the variable that contains the hour - any integer value from 0 through 23.
 < is the less than operator. The less than operator compares the numeric values on either side of
it. If the first numeric value is less than the last one the operator returns a true value. If the first
value is not less than the last one then false is returned.

If the hour is between 0 and 11 then these values are less than 12 and the statement
document.writeln("Good Morning.") will be executed. If the hours 12 to 23 occur the
statement will not be executed and no Good Morning greeting will appear in the Web page. If
you try running this script before twelve and again after noon you will see this. No Good
Morning message will occur from noon on - that is, provided the system time is correct on your
computer.

Here is a flow chart that shows each step in the execution of this script.
Style

Simple if statements can be written in either of the following formats. The statement to be
executed if the expression in brackets is true can be placed on the same line :

if (expression) statement

or on the next line:

if (expression)
statement
When the second form is used, the statement to be executed is usually indented by a few spaces
to show that it is part of the if statement. The indentation is to make the script easier to read by
anyone who has to work on it in the future. While it is not necessary for the JavaScript
interpreter it is necessary to make the code human readable.

Statement Blocks

The if statement may also contain a statement block that is to be executed if the expression
evaluates to true. A statement block is a series of statements to be executed that are surrounded
by curly braces:

if (expression){
statement1
statement2
statementn
}

The statement block is shown in bold. If statements always contain a statement or statement
block. A statement that contains other statements is also called a compound statement.

Doing Something or Other


Often we want to do something if an expression evaluates to true and something else if the
expression evaluates to false. Here is a simple example:

<HTML>
<HEAD>
<TITLE>Example of using a Date object and an if else
statement.</TITLE>
</HEAD>
<BODY>
<PRE>

This script provides an example of using the Date object to obtain


the hour of the day. The hour is used to write out a Good Morning
greeting if the time of day is before noon(12 hours) otherwise a
generic welcome message is written into the page.

<SCRIPT Language="JavaScript">

now = new Date() //create a Date object named: now

hour = now.getHours() //hours range from 0 to 23.

if (hour < 12)


document.writeln("Good Morning.")
else
document.writeln("Welcome.")
</SCRIPT>
</PRE>
</BODY>
</HTML>

This example uses an if else statement. This is a compound statement where the statement
immediately after the expression is executed if the expression is true and the statement after the
else keyword is executed if the expression is false. Here is a flowchart showing step-by-step
how the script works.
Statement blocks may be used in place of either statement:

if (expression){
statement1
statement2
statementx
}
else {
statementa
statementb
statementn
}

The positioning of the curly braces {} is designed to make the blocks visible and is one of many
coding styles. While many styles are possible it is important to choose one style and stick with it
to make your code readable.

Working with if Statements and Numbers

Exercises

This introduction and the exercise at the bottom of the page are designed to help you become
more familiar with using:

 if statements;
 if else statements;
 comparison operators such as: <, <=, >, >=, ==, and != when used with numbers;
 and introduces the else if construct and the
 logical operators && and ||.

Comparison Operators
The following table provides some examples of what boolean value is returned (true or false)
when two numbers are compared. Unless, you are already familiar with C, C++, Perl, or Java
operators take a moment to read through each table and assure yourself that the results makes
sense. Note that if hour contains a string (and not a number) the JavaScript interpreter will
attempt to convert it to a number before making the comparison.

Less than ( < )

Statement result
hour = 2 true
result = hour < 3

hour = 2 false
result = hour < 2

hour = 2 false
result = hour < 1

Less than or equal ( <= )

Statement result

hour = 2 true
result = hour <= 3

hour = 2 true
result = hour <= 2

hour = 2 false
result = hour <= 1

Greater than ( > )

Statement result

hour = 2 false
result = hour > 3

hour = 2 false
result = hour > 2

hour = 2 true
result = hour > 1

Greater than or equal ( >= )

Statement result

hour = 2 false
result = hour >= 3

hour = 2 true
result = hour >= 2

hour = 2 true
result = hour >= 1

Equal ( == )

Statement result

hour = 2 false
result = hour == 3

hour = 2 true
result = hour == 2

hour = 2 false
result = hour == 1

Not equal ( != )

Statement result

hour = 2 true
result = hour != 3

hour = 2 false
result = hour != 2

hour = 2 true
result = hour != 1

Caveats
For the most part the comparison operators behave exactly as you might expect them to with
numbers. There is one important caveat however. The following table gives a simple example of
this:
Decimal Places Expression Result

1 return = 4.9 == 5.0 false

2 return = 4.99 == 5.0 false

3 return = 4.999 == 5.0 false

4 return = 4.9999 == 5.0 false

5 return = 4.99999 == 5.0 false

6 return = 4.999999 == 5.0 false

7 return = 4.9999999 == 5.0 false

8 return = 4.99999999 == 5.0 false

9 return = 4.999999999 == 5.0 false

10 return = 4.9999999999 == 5.0 false

11 return = 4.99999999999 == 5.0 false

12 return = 4.999999999999 == 5.0 false

13 return = 4.9999999999999 == 5.0 false

14 return = 4.99999999999999 == 5.0 false

15 return = 4.999999999999999 == 5.0 false

16 return = 4.9999999999999999 == 5.0 true

17 return = 4.99999999999999999 == 5.0 true

18 return = 4.999999999999999999 == 5.0 true

19 return = 4.9999999999999999999 == 5.0 true


20 return = 4.99999999999999999999 == 5.0 true

It is possible for us to conceive of a number such as Pi that has an infinite number of decimals.
However no one has ever written out all the decimal values of Pi because the task could never be
completed and would take up an infinite amount of space to write down all the digits. Similarly
computers must process operations on numbers quickly and store numbers in a limited amount of
memory. JavaScript stores numbers using the standard 8 byte IEEE floating-point numeric
format. This means that there are limits to the size and precision of numbers. Integer numbers
will behave exactly as you expect if you want to compare integers or do integer math (calculate
with integers and that result in integers) where the numbers and results of any calculations only
range between -231 and -231 - 1. For the most part we can ignore problems of precision. The
exceptions are when we use very small or very large numbers or when we must compare
numbers that may have rounding errors or have lost precision because of size. In this case we
cannot use a simple == test and must instead test numbers to see if they are adequately close to
each other.

Greetings for Different Times of Day


On the previous page

now = new Date()


hour = now.getHours()

if (hour < 12)


document.writeln("Good Morning.")

was used to produce a greeting that would only be visible in the morning. If we, somewhat
arbitrarily, define the following times of day (by the hour) we can provide a slightly more
complete greeting:

Time of Day Hours

Morning 0 ~ 11

Afternoon 12 ~ 17

Evening 18 ~ 23
 

If we try to write out a separate greeting for each time period in the day then writing out a
greeting for the morning and evening is not a problem:

now = new Date() //create a Date object named: now

hour = now.getHours() //hours range from 0 to 23.


//0 is midnight to before 1 AM.

if (hour < 12)


document.writeln("Good Morning.")

if (hour > 17)


document.writeln("Good Evening.")

However, writing out a greeting for the afternoon cannot be done in the same way with just the
comparison operators. What is needed is some way to test for a time period that is not part of the
ranges that have already been tested. There are different ways to do this. Here is one of them:

if (hour < 12)


document.writeln("Good Morning.")
else if (hour > 17)
document.writeln("Good Evening.")
else
document.writeln("Good Afternoon.")

In this example the first else is followed by another if else statement. While the formatting
above is the standard way to write if else if else... type constructions the following indentation
shows better what is happening:

if (hour < 12)


document.writeln("Good Morning.")
else
if (hour > 17)
document.writeln("Good Evening.")
else
document.writeln("Good Afternoon.")

The first if else statement has two statements. The first one is executed if hour is less than 12.
The second statement is executed if hour is not less than 12. This statement is another if else
statement. It in turn tests if the hour is greater than 17. If it is, the evening message is written into
the document, and if it is not, the afternoon message is written out. Since the afternoon message
is only written out if all the if tests return false it will be written out at the correct time of day.
Here is the same code with curly brackets so that you will recognize the else if construction with
statement blocks. Even though the curly brackets only contain one statement the code is still
legal. Each bracket could contain many statements if necessary:

if (hour < 12) {


document.writeln("Good Morning.")
}
else if (hour > 17) {
document.writeln("Good Evening.")
}
else {
document.writeln("Good Afternoon.")
}

Logical Operators
Another way to determine if it is the afternoon would be to do the following:

if (hour > 11 && hour < 18)


document.writeln("Good Afternoon.")

The logical and operator && returns true if the values on both sides of it are true. Otherwise it
returns false. In this case hour > 11 must evaluate to true as must hour < 18 for the and
operator to return true. In JavaScript the comparison operators are always evaluated before the
logical operators so that this works properly. Here is a table showing the possibilities:

hour > hour < hour > 11 && hour <


Statement 11 18 18

hour = 2
if (hour > 11 && hour < 18) false true false
document.writeln("Good
Afternoon.")

hour = 14
if (hour > 11 && hour < 18) true true true
document.writeln("Good
Afternoon.")

hour = 19
if (hour > 11 && hour < 18) True false false
document.writeln("Good
Afternoon.")

When both hour > 11 and when hour < 18 evaluate to true the && operator returns true. In
the other cases it returns false. While it does take more comparisons than the previous example
that used the else if construct, the same script could be written:

if (hour < 12)


document.writeln("Good Morning.")

if (hour > 11 && hour < 18)


document.writeln("Good Afternoon.")

if (hour > 17)


document.writeln("Good Evening.")
The logical or operator || is often used in a similar way to the && operator except that it returns
true if either expression returns true. Here is a table of values:

Statement result

true
(true || false)

(false || true) true

true
(true || true)

(false || false) false

Finally, even though we may remember the significance of the numbers 12, 11, 18, and 17 as
parts of the day, it is not likely that someone returning to this script in the future would. These
values are basically constants. They do not change throughout the life of the script. To make the
script more readable we might consider creating some new variables to hold some of these
values:

morning = 0 //Morning begins at midnight?


noon = 12 //Afternoon begins at noon.
evening = 18 //Evening begins at 6 PM.

Here is a complete example:

<HTML>
<HEAD>
<TITLE>Examples of using a Date object and the if and
if else statements.</TITLE>
</HEAD>
<BODY>
<PRE>

This script provides examples of using the Date object


to obtain the hour of the day. The hour is used to
print different messages at different times during
the day.

<SCRIPT Language="JavaScript">

now = new Date() //create a Date object named: now

hour = now.getHours() //hours range from 0 to 23.


//0 is midnight to before 1 AM.

noon = 12 //Afternoon begins at noon.


evening = 18 //Evening begins at 6 PM.

if (hour < noon)


document.writeln("Good Morning.")
else if (hour < evening)
document.writeln("Good Afternoon.")
else
document.writeln("Good Evening.")

</SCRIPT>
</PRE>
</BODY>
</HTML>

Note: the morning = 0 variable was not needed and that since we have excluded the hours 0
through 11 in the first if statement we do not have to excluded them again by using: if (hour >
11 && hour < 18) in the second if statement.

Exercise
Given the arbitrary labeling of the following periods in a day:

Time of Day Hours

Night 0~5

Morning 6 ~ 11

Afternoon 12 ~ 17

Evening 18 ~ 23

1. Extend the script above to correctly handle the time periods listed.
2. While less efficient, write a second version of the script that uses if statements without any if
else statements. You will need to make extensive use of the && operator.
3. Test your scripts carefully. To do this add a line right after the line hour = now.getHours()
where you set hour to a test value. For example: hour = 2. Change the test value you set hour
to, and run the script. Make sure that the script works correctly under every possible condition
by setting hour to different values. Consider testing with values such as 0, 2, 5, 6, 8, 11, 12, 15,
17, 18, 20 and 23. Are these numbers likely to provide a good test? Why? Finally, don't forget to
remove (or comment out) the test line so that the script does what it is supposed to do.

 
Summary of Selection Statements

This page shows some of the common ways to write if, if else, if else if else.., and
switch statements. These are all called selection statements as they control which statements are
executed depending on some condition.

if
if (expression) statement
if (expression)
statement
if (expression) {
statement1
statement2
statementn
}

if else
if (expression) statement1; else statement2
if (expression) statement1
else statement2
if (expression)
statement1
else
statement2
if (expression) {
statement1
statement2
}
else {
statement_x
statement_y
}

if else if else if...


if (expression1) {
statement1
}
else if(expression2) {
statement2
}
else if (expression3) {
statement3
}
else {
default statement
}
switch
The switch statement was introduced in JavaScript 1.2 and is included for completeness.

switch (expression) {
case 19:
statement
break
case true:
statement
break
case "hello":
statement
break
default:
statement
break
}

Here is a script that demonstrates some of these


structures:
Read through the last set of if else if else... statements, then try it. Is the result what you
expected?

<HTML>
<HEAD><TITLE>Examples of if, if else, and else if in
JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT Language="JavaScript">
<!--
document.write("<H3>Simple if statements</H3>")
document.write("<P>")
var x = 2
if (x == 2) document.write("x is 2")
document.write("</P>")

document.write("<P>")
x = 3
if (x == 2) document.write("x is 2")
document.write("</P>")

document.write("<H3>Simple if else statement</H3>")


document.write("<P>")
x = 10
if (x < 10) {
document.write("x is less than 10")
}
else {
document.write("x is not less than 10")
}
document.write("</P>")

document.write("<H3>if else if else if else...


statements</H3>")
document.write("<P>")
x = 10
if (x < 10) {
document.write("x is less than 10")
}
else if (x > 10) {
document.write("x is greater than 10");
}
else {
document.write("x is equal to 10");
}

document.write("</P>");

// -->
</SCRIPT>

</BODY>
</HTML>

Loops: Repeating Statement Execution

Every programming language provides a method to do things repeatedly. For example when
checking for valid user data, it may be necessary to examine every character of a string, one
character at a time, until the end of the string is reached. Typically this is done inside a loop
statement of some sort using a variable as a counter to keep track of which character is to be
checked. The counter variable may be incremented by one, each time through, so that the first
character is examined the first time through the loop, the second character the second time, and
so forth. Being able to repeatedly execute a statement or compound statement is an essential
feature of programming.

The simplest loop statement is probably the while statement:

while(expression) statement

As long as the JavaScript expression inside the round brackets evaluate to true the statement is
executed. More typically while loops contain a block or compound statement often (also referred
to as the loop body) shown here in bold:

while(expression){
statement
statement
statement
}
Before the compound statement or loop block is executed, the expression in the round brackets is
evaluated. If it is true the block is executed. When the block is finished executing, the expression
is reevaluated. If it is true the block is executed again. This process continues until the expression
evaluates to false. At that point the loop block is not executed, the while loop is complete, and
the next statement after the loop can be executed. The following is a very simple while loop:

<HTML>
<HEAD>
<TITLE>Simple While Loop with Counter Variable</TITLE>
</HEAD>

<BODY>
<PRE>Output from a simple while loop with a counter variable:
<SCRIPT Language="JavaScript">
<!--

counter = 0
while (counter < 5){
document.writeln(counter)
counter++
}

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>

Controlling the Loop


In this example, the Loop is controlled by the counter variable. It is part of the expression:
counter < 5. Here is the script again:

counter = 0
while (counter < 5){
document.writeln(counter)
counter++
}

The following describes how this particular while loop works:

counter = 0

Before executing the loop statement the counter variable is set to zero. This insures the loop
body will be executed at least once because zero is less than 5.

while (counter < 5)


The expression counter < 5 is evaluated. Since zero is less than five, the expression evaluates
to true, and the loop block will be executed.

document.writeln(counter)

Inside the loop block the first statement is executed, writing out the current value of the
counter variable.

counter++

The counter variable is incremented by 1. In other words if it was zero when before this
statement is executed, it will be equal to one afterwards. As this is the last statement in the
block the while expression will be reevaluated. And since, 1 is less than 5 the loop block will be
executed again.

This loop ends when the counter variable is incremented to five. At that point it is no longer
less than five and the loop block will not be executed again.

Flow Charts
While flow charts have fallen out of fashion as higher level languages have become popular, the
following flow chart below is provided to help make clear each step in the while loop example.
By following the arrows and remembering the current value of counter the looping mechanism
may become more obvious. If you are at all unsure how loops work, try "walking through" the
flow chart one step at a time. Keep track of the value of counter and see how many times you
loop until the script is done.
The cycle in the flow chart where the expression is true, the document is written to, the counter
incremented, and the expression is evaluated again..., forms a sort of visual "loop" in the flow
chart. Hence the name.

Infinite Loops
It is all too easy to create a loop that will go on forever executing the loop block. Whether done
by accident or deliberately the result is that the Web page will never complete loading, the
browser's controls/buttons may freeze, or the browser may crash altogether. Here is an example
of an infinite loop that was likely created by mistake:

counter = 0
while (counter < 10){
document.writeln(counter)

}
Since the counter variable is never changed inside the loop it will always be less than ten. The
counter++ statement or something similar was forgotten. If you try this in a document you may
have to use your operating system to shut down your browser. Here is an infinite loop that has
been written on purpose:

while (true){
document.writeln("Some message..")
}

Note that the test expression is simply the true value.

Checking Every Character in a String


While validating text strings is described elsewhere on this site, here is a short example that
prints out each character of a string on a separate line. Note the test in the while loop uses the
length property of the string object. Also, as the counter goes through values 0, 1, 2, etc. it is
used in the charAt() method of the string object to retrieve the character in that position in the
string. The character is stored in the chr variable and written out to the document in the next
line. In this example the string is Hello World which has a length of 11 characters in positions
0 through 10. Since counter is initially set to 0 and is incremented by one at the end of each
loop, counter will be set to the values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10 and the body of the loop
will be executed. However, afert counter is set to 11 the test counter < str.length will fail
and the loop body will not be executed again.

<HTML>
<HEAD>
<TITLE>Examining Every Character in a String</TITLE>
</HEAD>

<BODY>
<PRE>Examining every character in a string:
<SCRIPT Language="JavaScript">
<!--

str = "Hello World"


counter = 0
while (counter < str.length){
chr = str.charAt(counter)
document.writeln(chr)
counter++
}

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>
The chr variable contains a one character string - unlike languages like C where a single
character is a different datatype. A small embellishment to this script might be to write out the
value of the counter variable and the character at the same time. For completeness, the length of
the string is written out when the loop ends. Output from this script shows the position of each
character in the string and then the strings length:

<HTML>
<HEAD>
<TITLE>Examining Every Character in a String</TITLE>
</HEAD>

<BODY>
<PRE>Examining every character in a string:
<SCRIPT Language="JavaScript">
<!--

str = "Hello World"


counter = 0
while (counter < str.length){
chr = str.charAt(counter)
document.writeln("Character in position " + counter + ": " +
chr)
counter++
}

document.writeln("The string length is: " + str.length)

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>

The for Loop

A common operation is to set a variable to zero (or some other value) before entering a loop. In
the case of a while loop some expression will be evaluated and if the expression evaluates to
true the loop body is executed. After the loop body or block is executed the variable is
incremented or otherwise changed and the expression is evaluated again. The while loop below
shows a variable that is set to zero and then incremented by one after each time the loop body is
executed. When the counter variable is set to 10 the expression returns false and the loop exits.

counter = 0
while(counter < 10) {
document.writeln("Counter is: " + counter)
counter++
}
This pattern is so common most languages provide a for loop of some type to make it easier to
write:

for (initial statement; expression; end statement) statement


initial statement

This statment is executed before looping begins.

expression

This expression is evaluated to true or false. If true, the loop body is entered.

end statement

This statement is executed after the loop body has been executed, but before the expression is
evaluated again.

for (counter=0; counter < 10; counter++) {


document.write("Counter is: " + counter)
}

The example while and for loops shown here are equivalent.

<HTML>
<HEAD><TITLE>Examples of using JavaScript loops</TITLE>
</HEAD>
<BODY>
<PRE>
Sample file showing a while and for loop with a
counter variable looping through values 0 through 9.

<SCRIPT Language="JavaScript">
<!--
counter = 0

document.writeln("With the while loop:")

while(counter < 10) {


document.writeln("Counter is: " + counter)
counter++
}

document.writeln("With the for loop:")

for (counter=0; counter < 10; counter++) {


document.writeln("Counter is: " + counter)
}

// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>
The variable name in these examples has been counter. The name of the variable was chosen to
illustrate what it was being used for. However, it is much more common to see the variable i
used for this purpose. i stands for iterator and of course saves typing... Finally, it is worth noting
that in both the examples given so far the loop exists when the condition being tested for is no
longer true. In this case when counter is no longer less than ten. However in both cases the
counter variable still exists and is now equal to ten. Here are similar examples:

<html>
<head>
<title>i During and After a Loop</title>
</head>

<body bgcolor="#FFFFFF">
<PRE>
<SCRIPT Language="JavaScript">
<!--
document.writeln("Counting from 0 to 9 with a while loop.")

i = 0
while (i < 10){
document.writeln("Inside the loop i is: " + i)
i++
}

document.writeln("After exiting the loop i is: " + i)

document.writeln("\nCounting from 0 to 9 with a for loop.")


for (i = 0; i < 10; i++){
document.writeln("Inside the loop i is: " + i)
}

document.writeln("After exiting the loop i is: " + i)

//-->
</SCRIPT>
</PRE>
</body>
</html>

Here is the output from this script:

Counting from 0 to 9 with a while loop.


Inside the loop i is: 0
Inside the loop i is: 1
Inside the loop i is: 2
Inside the loop i is: 3
Inside the loop i is: 4
Inside the loop i is: 5
Inside the loop i is: 6
Inside the loop i is: 7
Inside the loop i is: 8
Inside the loop i is: 9
After exiting the loop i is: 10

Counting from 0 to 9 with a for loop.


Inside the loop i is: 0
Inside the loop i is: 1
Inside the loop i is: 2
Inside the loop i is: 3
Inside the loop i is: 4
Inside the loop i is: 5
Inside the loop i is: 6
Inside the loop i is: 7
Inside the loop i is: 8
Inside the loop i is: 9
After exiting the loop i is: 10

JavaScript Functions

Introduction
JavaScript provides a function named parseInt() that converts, where possible, a string to a
number. Here is a statement that shows one way it can be used:

result = parseInt("4.73 Hello")

In this case the string "4.73 Hello" will be checked by the parseInt() function to see if it
begins with text that can be converted to an integer. In this case it does, so the number 4 will be
assigned to the variable result. JavaScript provides a similar function named parseFloat()
that will attempt to convert a string to a number that may include a fractional part. For example:

result = parseFloat("4.73 Hello")

will result in the number 4.73 being assigned to the variable result. If either function does not
find text it can convert to a number at the beginning of the string it returns a special number
value NaN that means "not-a-number."

Each one of these functions can be thought of as a set of prewritten statements or segment of
code that are made available to be executed as necessary. Each is designed to perform a specific
task. In the case of parseFloat() and parseInt() the actual code that is executed is made
available by the JavaScript interpreter. Executing the function is also referred to as "invoking" it
or "calling" it. For this to work each code segment or function must have:
 a name, for example: parseInt, in order to execute or call the function by name as needed,
 a way to be passed or sent information to work on - such as the string "4.73 Hello",
 the option to "return" a value that in effect takes the place of the function name in the calling
statement.

The JavaScript interpreter knows that a function is to be executed when it finds a name followed
immediately by round brackets. The individual data items to be "passed" to the function are
placed inside the round brackets. They are called parameters and are separated by commas when
there is more than one of them.

Defining Functions Within Scripts


An important part of JavaScript is the ability to create new functions within scripts. These
functions are named segments of JavaScript statements. These statements usually have a single
purpose, such as performing a complex calculation or verifying the data entered into an HTML
form. Functions can be passed copies of variables or references to objects to work with. Just as
with built in functions, this is done in the parameter list. JavaScript functions that you define can
be placed inside script tags anywhere in the document. However, they should be placed in the
head of the document to guarantee they are loaded before being called from script statements in
the body of the document. Here is the format for defining a JavaScript function:

function functionName(parameter_1, parameter_2, .. parameter_n){


statement1
statement2
statementn
}

The keyword function precedes the name of the function. A function name is like a variable
name in that it must start with a character and must not be the same as a JavaScript key word.
The parameter list is a comma separated list of variable names inside round brackets immediately
following the function name. The statements to be executed when the function is called are
contained inside the function body and are contained within curly braces.

Here is a function that finds the maximum value of two numbers. Note that the function
determines which number is largest and returns the largest value using the return statement.
The value returned will take the place of the function in the calling expression - see the example
below.

function getMax(n1, n2){


if (n1 < n2)
return n2
else
return n1
}

Here is an example of how this function might be used.

<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT Language="JavaScript">
<!--

function getMax(n1, n2){


if (n1 < n2)
return n2
else
return n1
}

// -->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT Language="JavaScript">
<!--

document.write("<P>")
document.write("The largest number of 5 or 6 is: " + getMax(5, 6))
document.write("</P>")

// -->
</SCRIPT>
</BODY>
</HTML>

The function definition is in the head of the document and is read by the JavaScript interpreter
before the call to the function later in the body of the document. When the interpreter reads the
function definition it prepares the function so that it can be called within statements that follow it
but does not execute any of the statements in the function definition. Later, when the interpreter
reads the function call getMax(5, 6) shown in bold it:

1. passes the two values, 5 and 6 into the parameter list of the getMax function. These two values
are copied into the variables n1 and n2 respectively;
2. the if statement in the function definition is executed with the result that;
3. the value of the larger variable is returned. In this case in the statement return n2 returns the
number 6.

The function is complete - no further statements in the function are executed - when a return
statement is executed or when the last statement in the function is executed. In this case the
return statement ends the function and it returns with the value 6. The value returned by the
function replaces the function in the write statement. So that

document.write("The largest number of 5 or 6 is: " + getMax(5, 6))

in effect becomes
document.write("The largest number of 5 or 6 is: " + 6)

Finally, the string and number are concatentated and the string

The largest number of 5 or 6 is: 6

is written into the document.

JavaScript is an easy-to-use language that can be embedded in HTML pages to make them more
interactive and dynamic. JavaScript enables site designers with moderate programming skills to
add capabilities and functionality to Web pages, including instant user feedback, advanced form
processing, pop-up windows, advanced frame applications, and much more. In this course, you
learn the basic elements of the JavaScript language and several techniques to take your Web
pages to the next level of sophistication.

A function consists of the function keyword, the name of the function followed by a pair of parenthesis and lastly, the

JavaScript statement/s enclosed by curly braces.

You can give any name to the function as long as it is not a JavaScript reserved keyword. (The list of reserved

keywords can be found here.)

The function name can contain only alphanumeric characters (alphabet and digits) and the underscore. Also, the

name cannot begin with a numeral.

You might also like