Upload
minnu-merin-abraham
View
223
Download
0
Embed Size (px)
Citation preview
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 1/39
JavaScript programing statements (source code) may only be placed in certain locations withinHTML 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 HTMLdocument.</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 JavaScriptWhen the browser is reading in an HTML document it needs to be able to determine what text isHTML 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 illustratedabove. 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:
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 2/39
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 youload 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 containsa simple expression. Statements can be more complicated and we will often need to look closelyat the expressions within them.
The Language="JavaScript" attribute After Netscape introduced JavaScript, Microsoft introduced Visual Basic Script. Other scriptinglangauges 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>
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 3/39
</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 browserswill therefore render the JavaScript statements as paragraph text. This can be quite alarming if anicely 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 commenttag must be preceded by the // characters that precede a JavaScript comment. Here is a shortexample:
<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 browsersdocument.write("<P>Browsers that do not understand the SCRIPT
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 4/39
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 methodsof 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>HelloWorld</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.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 5/39
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 containsthe 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 onserver
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 HTMLmarkup. 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
y to help understand how other people have solved problems by reading their code;
y for correctly adapting other people's code for your own uses;
y for modifying and extending your own code as needed.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 6/39
However, even trying to understand your own code after being away from it for some monthsmay 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 formof 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 documentingwhat you have done. JavaScript, like other languages, provides a way to include documentationinterspersed 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 tonote. 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 morequestions.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 thanmaxQuestions.*/ /* Do Not edit code from this point on! */ /*** The checkAnswer(choice) method is called when the user selects an answer
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 7/39
* 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
elsereturn 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.
ariables 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 valueto 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;
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 8/39
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 levellanguages 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 textcharacters. 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? BecauseJavaScript 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 bya number or decimal point followed by a number. Here are a few examples:
x1 = 3.14159x2 = .5x3 = -24e3
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 9/39
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 anoperator 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 anumeric 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 = falseif (test) alert("test is true")
The Boolean value false is assigned to the variable test. How do we know false is not avariable 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 ais 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 doesnot 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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 10/39
This means that there is a variable named x1 but that it has no value stored in it. In other wordsit'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 thiswill 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 holdingonly 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. Thesetwo short examples involve a simple typing error. Instead of typing x1, x has been typed once ineach 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 nameresulted 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 asecond 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 scriptand 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 thedocument.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 11/39
Making Decisions
Doing Something under Certain Conditions
In the random image project, a sequence of JavaScript statements were used to write an imagetag 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 thesame sequence - in the same order - of statements are executed. Every general purpose
programming language has facilities to optionally execute statements. To do this some testcondition 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 daywhere 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 obtainthe hour of the day. The hour is used to write out a Good Morninggreeting 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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 12/39
little different from how objects have been used in the examples up until now. String objects canbe 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 andinterpreter 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 wascreated. Like the String, document, and Math objects the Date object provides numerous usefulmethods 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. Itcontains three tokens:
y hour is the variable that contains the hour - any integer value from 0 through 23.
y < 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.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 13/39
St yle
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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 14/39
When the second form is used, the statement to be executed is usually indented by a few spacesto 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 JavaScriptinterpreter 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 surroundedby curly braces:
if (expression){ statement1
statement2
statementn
}
The statement block is shown in bold. If statements always contain a statement or statementblock. 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 elsestatement.</TITLE></HEAD><BODY><PRE> This script provides an example of using the Date object to obtainthe hour of the day. The hour is used to write out a Good Morninggreeting if the time of day is before noon(12 hours) otherwise ageneric 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.")
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 15/39
</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-stephow the script works.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 16/39
Statement blocks may be used in place of either statement:
if (expression){ statement1
statement2
statementx
}
else { statementa
statementb
statementn
}
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 17/39
The positioning of the curly braces {} is designed to make the blocks visible and is one of manycoding 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:
y if statements;
y if else statements;
y comparison operators such as: <, <=, >, >=, ==, and != when used with numbers;
y and introduces the else if construct and the
y 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 = 2result = hour < 3
true
hour = 2
result = hour < 2
false
hour = 2result = hour < 1
false
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 18/39
Less than or equal ( <= )
Statement result
hour = 2result = hour <= 3
true
hour = 2result = hour <= 2
true
hour = 2result = hour <= 1
false
Greater than ( > )
Statement result
hour = 2result = hour > 3
false
hour = 2result = hour > 2
false
hour = 2
result = hour > 1
true
Greater than or equal ( >= )
Statement result
hour = 2result = hour >= 3
false
hour = 2result = hour >= 2
true
hour = 2result = hour >= 1
true
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 19/39
Equal ( == )
Statement result
hour = 2result = hour == 3
false
hour = 2result = hour == 2
true
hour = 2result = hour == 1
false
Not equal ( != )
Statement result
hour = 2result = hour != 3
true
hour = 2result = hour != 2
false
hour = 2
result = hour != 1
true
Caveats
For the most part the comparison operators behave exactly as you might expect them to withnumbers. 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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 20/39
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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 21/39
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 numericformat. 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 (calculatewith 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. Theexceptions 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 toeach other.
Greetings for Different Times of DayOn 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 agreeting for the morning and evening is not a problem:
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 22/39
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 theranges 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.")
elsedocument.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 indentationshows better what is happening:
if (hour < 12) document.writeln("Good Morning.")
else if (hour > 17)
document.writeln("Good Evening.")
elsedocument.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 intothe 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 stilllegal. 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.")
}
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 23/39
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 thelogical operators so that this works properly. Here is a table showing the possibilities:
Statement hour >
11 hour <
18 hour > 11 && hour <
18
hour = 2
if (hour > 11 && hour < 18)document.writeln("Good
Afternoon.")
false true false
hour = 14if (hour > 11 && hour < 18)
document.writeln("GoodAfternoon.")
true true true
hour = 19if (hour > 11 && hour < 18)
document.writeln("GoodAfternoon.")
True false false
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 examplethat 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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 24/39
(true || false)true
(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. Thesevalues 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 objectto obtain the hour of the day. The hour is used toprint different messages at different times duringthe 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)
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 25/39
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 toremove (or comment out) the test line so that the script does what it is supposed to do.
Summary of Selection Statements
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 26/39
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 areexecuted depending on some condition.
if
if (expression) statementif (expression)
statementif (expression) {
statement1statement2statementn
}
if else
if (expression) statement1; else statement2if (expression) statement1else statement2if (expression)
statement1else
statement2if (expression) {
statement1statement2
}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.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 27/39
switch (expression) {case 19:
statementbreak
case true:statementbreak
case "hello":statementbreak
default:statementbreak
}
Here is a script that demonstrates some of thesestructures:
Read through the last set of if else if else... statements, then try it. Is the result what youexpected?
<HTML><HEAD><TITLE>Examples of if, if else, and else if inJavaScript</TITLE></HEAD><BODY>
<SCRIPT Language="JavaScript"><!--document.write("<H3>Simple if statements</H3>")document.write("<P>")var x = 2if (x == 2) document.write("x is 2")document.write("</P>")
document.write("<P>")x = 3if (x == 2) document.write("x is 2")document.write("</P>")
document.write("<H3>Simple if else statement</H3>")document.write("<P>")x = 10if (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>")
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 28/39
x = 10if (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 whenchecking for valid user data, it may be necessary to examine every character of a string, onecharacter 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 bechecked. 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, andso 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 isexecuted. 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
statementstatement
}
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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 29/39
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 = 0while (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.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 30/39
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, thefollowing 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 mechanismmay become more obvious. If you are at all unsure how loops work, try "walking through" theflow 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.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 31/39
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, thebrowser'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 = 0while (counter < 10){
document.writeln(counter) }
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 32/39
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 hasbeen 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 thestring. 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 eachloop, 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 = 0while (counter < str.length){
chr = str.charAt(counter)document.writeln(chr)counter++
} // --></SCRIPT></PRE></BODY></HTML>
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 33/39
The chr variable contains a one character string - unlike languages like C where a singlecharacter 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 eachcharacter 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 = 0while (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 isincremented 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++
}
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 34/39
This pattern is so common most languages provide a for loop of some type to make it easier towrite:
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>
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 35/39
</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 nolonger 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 = 0while (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.
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 36/39
Inside the loop i is: 0Inside the loop i is: 1Inside the loop i is: 2Inside the loop i is: 3Inside the loop i is: 4Inside the loop i is: 5Inside the loop i is: 6Inside the loop i is: 7Inside the loop i is: 8Inside the loop i is: 9After exiting the loop i is: 10 Counting from 0 to 9 with a for loop.Inside the loop i is: 0Inside the loop i is: 1Inside the loop i is: 2Inside the loop i is: 3Inside the loop i is: 4Inside the loop i is: 5
Inside the loop i is: 6Inside the loop i is: 7Inside the loop i is: 8Inside the loop i is: 9After exiting the loop i is: 10
JavaScript Functions
Introduction
JavaScript provides a function named parseInt() that converts, where possible, a string to anumber. 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
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 37/39
task. In the case of parseFloat() and parseInt() the actual code that is executed is madeavailable 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:
y a name, for example: parseInt, in order to execute or call the function by name as needed,
y
a way to be passed or sent information to work on - such as the string "4.73 Hello",y 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 areplaced 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. Thesefunctions 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 HTMLform. 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 canbe 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 inthe body of the document. Here is the format for defining a JavaScript function:
function functionName(parameter_1, parameter_2, .. parameter_n){statement1statement2statementn
}
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 arecontained 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 examplebelow.
function getMax(n1, n2){if (n1 < n2)
return n2else
return n1}
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 38/39
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 itbut 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 thefunction replaces the function in the write statement. So that
8/7/2019 JavaScript programing statements
http://slidepdf.com/reader/full/javascript-programing-statements 39/39
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 moreinteractive 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, youlearn the basic elements of the JavaScript language and several techniques to take your Webpages 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.