Download as pdf or txt
Download as pdf or txt
You are on page 1of 136

JavaScript

Client-side dynamic documents

1
JavaScript Capabilities
• Add content to a web page dynamically.
• Alter a web page in response to user
actions.
• React to user events.
• Interact with frames.
• Manipulate HTTP cookies

2
JavaScript is not Java
• JavaScript is a very simple scripting
language.
• Syntax is similar to a subset of Java.
• Interpreted language.
• Uses objects, but doesn't really support
the creation of new object types

3
Language Elements
• Variables
• Literals
• Operators
• Control Structures
• Objects

4
More JavaScript Basics
<script language=“JavaScript”>
document.write(“Hello, World!”);
</script>

• We can put as many commands inside


of the <script> container as we like.
• The “write” method will write whatever
data we want to the document, allowing
it to appear on the screen.
5
JavaScript in HTML Documents

• We can put JavaScript is either the


HEAD of BODY of a document.
• Even with a “write” command in the
HEAD of the document, the text will still
appear in the BODY of the document.

6
Embedding HTML in JavaScript Output

• We can put as much (or as little) HTML


as we like in with our JavaScript.
• The HTML that we put in with our
JavaScript will be used to mark up the
document.
• We must “print” the HTML elements –
we cannot just “put” them around the
JavaScript commands.
7
Embedding (cont’d)

• Yes:
document.write (“<b>”);
document.write (“Hello, World!”);
document.write (“</b>”);
• No:
<b>
document.write (“Hello, World!”);
</b>
8
More JavaScript Basics…
• Although multiple “write()” commands
may be used, HTML will still ignore the
different lines and put the words
together.
• If we want to force a new line to start, we
have to use <br>.
• If we want a new paragraph, we have to
use <p>.
9
Example
document.write(“Hello,”);
document.write(“How are you?”);
• This above text will appear all on one line.
If we want the text to be on different lines,
we have to do the following:

document.write(“Hello,”);
document.write(“<br>How are you?”);
10
What is a Variable?
• A variable is a “named storage spot”
where we can store information. It is a
little like a box where we can
temporarily put information that we want
to use later on.
• Variables are very useful when
programming – they allow us to retrieve
information from the user and use it at a
later point in time.
11
Prompting For & Storing User Input

• In order to prompt the user for


information, we can use the “prompt()”
function.
• We can store the result of the prompt()
function in a variable.
• The information entered by the user will
be stored in the variable name for use
at a later point in time.
12
Prompting and Storing (cont’d)
• The order in how we do this is
important.
• First, we have to create the variable.
We can do this using the following
command:
var name;
• Where “var” tells us that it is a variable
and “name” is the name of the variable.
There is now a spot in the computer that
is going to hold information, and that
spot is called “name” 13
Prompting and Storing (cont’d)
• Once we have declared the variable, we
can prompt the user for information and
store it in the variable:
name=prompt(“Enter your name.”);
• This will take information from the user
and will store it in the variable “name”.
We will be able to access the variable at
a later point in time to use the
information retrieved from the user.
14
Using Variable to Retrieve Info
• If we want to use information stored in a
variable, all we have to do is use the variable
where we want the data.
document.write(name);
• Note that we do not use quotes around name
when using the variable. If we used quotes,
the computer would think that we wanted to
print the word “name” on the screen. By just
using name, it uses the value stored in that
variable.
15
An Example

<script language=“JavaScript”>

var name;
name=prompt(“Please enter your name”);
document.write(“Hello, ”);
document.write(name);
</script>
16
More Prompting
• When we use the “prompt()” function,
we can also enter default information
into the field. This is done by using a
second parameter.
prompt(“Question”, “default
text”);
• The “default text” will appear in the
editable field where the user is
supposed to put their data.
17
Multiple Variables
• We can use multiple variables when
using JavaScript. This means that we
are able to handle multiple different
inputs from the user.
• Once we have access to the different
variables, we can use them how we
wish.
• It is important to point out that a variable
can be use as many times as needed.
18
Multiple Variable Declaration
• We can declare multiple variables two
different ways:
– One per line:
• var first_name;
• var last_name;
– Both on the same line:
• var first_name, last_name;

19
Retrieving Multiple Pieces of Data

var first_name, last_name;


first_name=prompt(“First name?”);
last_name=prompt(“Last name?”);
document.write(first_name);
document.write(“ “);
document.write(last_name);

20
Variable Naming

• We can assign many different names for


variables, helping us to keep track of
what is actually stored in the variable.
• It is important to choose appropriate
names, as that will help us to keep track
of the data.
• There are a few naming rules that we
have to follow.
21
Variable Naming Rules
• Names can be composed of:
– letters
– numbers
– the underscore.
• Names cannot:
– have spaces or special characters
– start with a number
• Names are also case sensitive!
22
Examples
• var first_name;
• var first name;
• var FirstName;
• var firstname;
• var name1;
• var 1name;
• var first&name;
23
Storing Strings
• We have stored words in the variables
such as our first name and our last
name.
• These pieces of information were
collections of characters. We refer to
these collections of characters as
strings.
• A string is any collection of characters
that we find on the keyboard.
24
Storing Numbers
• We can also store numbers in our
variables.
• In order to store numbers, we have to
tell the computer (using JavaScript) that
the data stored in the variable is a
number and not a string.
• If we do not tell the computer that we
have a number, it will treat the digits like
a string.
25
Value Representation
• In order to help us understand the
difference between a string value and a
numeric value, we usually show our
strings surrounded by quotes (“).
• Quotes are often used to represent
strings.
• number = “45”;  a “string” of two
digits
• number = 45;  the integer 45
26
Reading Input
• When we prompt for information from
the user, it is always stored as a string.
• Some math operations might work with
the variables, but not all.
• When in doubt, the computer will treat
any input as a string.
• We can convert string variables to
numeric variables.

27
Number Types
• There are two different types of
numbers: floats and ints.
• A float is a number with a decimal point
(a floating point number).
• An int is a number without a decimal
point (an integer).
• If we want to convert a string to a
number, we have to decide which
numeric type we want to convert it to.
28
Floats
• In order to convert strings to floats, we use a
function called parseFloat()
• We parse the number from the string
variable. This removes the number from the
string, storing it as a numeric value.
• The parse function will even remove extra
characters that may happen to follow the
floating point number in the prompt field. It will
not remove characters that appear before the
first character.

29
parseFloat()

var x, y, answer;
x = prompt(“Enter a number”);
x = parseFloat(x);
y = prompt(“Enter a second number”);
y = parseFloat(y);
answer = x + y;
document.write(x, “ + ”, y, “ = “, answer);
30
Explanation
• We can use the values stored in x and y to
create a new value to store in answer.
• We can use all three variable again to write
information to the screen.
• When using the write command, we have the
option of including multiple items to be
written, as long as they are separated by a
comma.
• We have to include the appropriate spacing
for the output to look correct.
31
What about ints?
• We can get an integer from a string by
using the parseInt function.
• This function will retrieve an int from the
entered text.
• As with the parseFloat function, trailing
letters will be removed, while leading
letters will cause an error.
• parseInt will also remove anything to
the right of the decimal point.
32
parseInt vs. parseFloat

• If you enter 4.3f as the value into the


prompt, then “4.3f” will be stored in the
variable.
• If we use parseFloat, we will end up
with the variable value of 4.3
• If we use parseInt, we will end up with
the variable value of 4

33
What about other math
operations?

• subtraction “-” works fine


• division “/” works fine
• multiplication “*” works fine

• We can use these functions to do basic


math on our web pages.

34
What about “Strings”?

• We can perform math operations on


variables that are numbers, but do
these math operations work on strings?
• Do any of the math operations work with
strings?
• If math operations don’t work on strings,
what results do we get to tell us that we
have an error?
35
String Operations
• “+” will concatenate two strings
together, so if x=“bob” and y=“bill”,
x+y=“bobbill”
• “-”, “*”, and “/” will all fail. The result on
the screen for these equations will be
“NaN”.
• “NaN” stands for “Not a Number”, as the
result from these “equations” is not a
valid number.
36
Errors
• JavaScript will give us errors if we try to
do something that it doesn’t like.
• The errors may involve something
printed to the screen, or it may involve
nothing printed to the screen.
• We will need to be able to figure out
where the errors are and fix them.

37
Errors (cont’d)
• My personal suggestion:
– write your JavaScript in fairly small, logical
sections
– test each section to make sure that it works
– once one section works, move to the next
section
• If an error is introduced, then you will
know which lines of code have caused
the problem.
38
Errors (cont’d)
• If you are unsure of how some piece of
JavaScript works:
– you can look it up online to see how it
works
– you can write a small program and see
how it works
• By writing code to see how things work,
you can answer your own questions
quickly about JavaScript. It is a good
way to learn how to program. 39
Error Types
• There are three different types of errors:
– syntax errors
– logic errors
– user errors
• We must be able to determine the
difference between these errors in order
to be able to correct them.

40
Syntax Errors
• A syntax error is an error created by
incorrectly typing in JavaScript
statements.
• An example would be:
– write.document(“Hello, World!);
• The missing quote will cause this
statement to fail.
• Such statements may simply not work in
our browsers.
41
Logic Errors
• Logic errors occur when we make a mistake
in the logic of our statements.
• For example:
number = 50 + 100 / 2
number = (50 + 100) / 2
• If we really mean the second one and we type
in the first one, we will have a logic error.
• We have to be careful that the logic of the
program is correct.
42
User Errors

• User errors are caused when the user


enters in the wrong information.
• If we expect the user to enter in a
number and a letter is entered instead,
then this can cause lots of problems.
• There are ways that we can double-
check to see what the user has typed in,
helping to avoid this problem. We will
learn of these methods later.
43
Writing Readable Code
• Once again, writing readable code is
important. The easier it is to read, the
easier it will be to understand and to
find errors.
• We are able to write our programs in a
couple of different ways. We should
choose the method that makes the code
as easy to read as possible.
44
Variables & Statements
• We must declare our variables before
we use them in our program.
• It doesn’t make a difference where we
declare our variables, as long as they
are declared before they are used.
• In order to make our code more
readable, we should declare all of our
variables at the top of our program. It
makes the code easier to read.
45
Variables & Statements
variable declarations

program

programming statements

46
JavaScript Variables
• Un-typed!
• Can be declared with var keyword:
var foo;

• Can be created automatically by


assigning a value:
foo=1; blah="Hi Dave";

47
Variables (cont.)
• Using var to declare a variable results
in a local variable (inside a function).

• If you don't use var – the variable is a


global variable.

48
Literals
• The typical bunch:
– Numbers 17 123.45
– Strings "Hello Dave"
– Boolean: true false
– Arrays: [1,"Hi Dave",17.234]

Arrays can hold anything!

49
Operators
• Arithmetic, comparison, assignment,
bitwise, boolean (pretty much just like
C).

+ - * / % ++ -- == != > <
&& || ! & | << >>

50
Control Structures
• Again – pretty much just like C:
if if-else ?: switch

for while do-while

• And a few not in C


for (var in object)

with (object)
51
Objects
• An object is a definable thing, such as
a car. Objects are allowed to have other
objects – a car can have a trunk, the
trunk may have a spare tire.
• Since JavaScript is an object-oriented
language, we use dot syntax to specify
the relationship between objects.
• car.trunk.sparetire

52
Objects
• Objects have attributes and methods.
• Many pre-defined objects and object
types.
• Using objects follows the syntax of
C++/Java:
objectname.attributename
objectname.methodname()

53
Instance
• An instance is a particular incarnation
of an object.
• For example, I could represent students
in the class using class.student, where
an instance of the student object would
be a particular person.
• An instance of an object has all of the
same attributes as that object.
54
Objects
• In real life, and object is a tangible
“thing” – a car, a bike or a computer.
• As we can see, we like to name objects
so that we can talk about them.
• The object name doesn’t define the
object, but it acts as more of a reference
to the object itself.

55
Objects (cont’d)
• When programming, we use “objects”
as a reference name for information that
we want to store.
• We use programming objects to store
information about real-life objects.
• We store object data by storing
information about the individual
attributes or properties of the object in
question.
56
Object Information
• For example, if we have a green
bowling ball that weighs 3kgs, we know
that:
– the bowling ball color is green
– the bowling ball shape is round
– the bowling ball weight is 3kgs
• In each of these cases, we are
associating an attribute with a piece of
data describing that attribute.
57
Creating an Object
• In JavaScript, we can create an Object
using a function. In this case, we can
create a bowling ball object:
var bball = new Object();
• This code creates a new object called
bball.
• The “new Object()” function is called a
constructor function because it is used
to construct a new object.

58
Storing Object Information

• If we have an object called bball, we


can store information about that object:
bball.color = “blue”;
bball.shape = “round”;
bball.weight = “3”;
bball.holes = “true”;
• We can store as much information as
we want about bowling balls.
59
Object Information
• We associate the properties of the
object with the object using a “.”
• This allows us to associate the
parameter to a particular object.
• For example, we could easily store the
color of multiple different objects. Using
the object name will help us keep track
of the information.

60
Object Info (cont’d)

• bball.color=“green”;
• car.color=“red”;
• If we were to say:
– document.write(color);, we wouldn’t
know which color to print out.
• Instead, we can refer to the information
based on the object:
– document.write(bball.color);
– document.write(car.color);
61
Object Attributes
• We can add as many attributes to an
object as we like.
• It is advisable to keep the number of
attributes to the minimum needed.
• We should also declare all of the
attributes in the same location, making it
easier to keep track of them.

62
Primitive Types
• Considering that an object is an new
type of variable, we can now refer to
ordinary variables as primitive types.
• A primitive type is a one of the regular
variables that we can store.
• There are three primary primitive
types – numbers, strings and Booleans.

63
Compound Objects
• A compound object is an object where
some of the attributes are other objects.
• For example, one attribute of a person
object might be their name.
• name itself can also be an object, as it
can be comprised of a first, middle and
last name.
• In this case, the object name is an
attribute of the object person.
64
Compound Objects (cont’d)
parent child

first

Name middle

Person last

Age

65
Using Compound Objects
• We can use compound objects in the
same way that we used variables.
• The advantage of compound objects
falls with the ability to logically manage
the object.
• We are able to store all of our related
information in a logical object.

66
More Objects
• The document object is a compound
object.
• The document object is part of the
larger window object. Each of these
objects has attributes that we can
access.

67
The Window Object
• window.closed (Boolean)
• window.location (String)
• window.history.length (Number)

68
The document Object
• The document object is special in the
window, so there is no need to specify
the parent “window” object.
• This allows us to use
“document.bgColor” instead of
“window.document.bgColor”.
• There are many other document
attributes that we can access.
69
document attributes
• document.bgColor (String)
• document.fgColor (String)
• document.URL (String)
• document.lastModified (String)
• document.linkColor (String)
• document.vlinkColor (String)

70
Object Methods
• A method is a function an object can use to
perform various tasks.
• We have already seen an object method –
the write method associated with the
document object.
• The write method is used to tell the
document object to add some information to
the page.
• This is why we say document.write(“foo”);
71
Object Methods (cont’d)
• Methods are a powerful method of
modifying objects.
• Creating methods for objects that we
have created is out of the scope of this
course, but we will take advantage of
those methods available to us from the
window, document and other objects.

72
window.confirm()
• The confirm() method of the window
object will ask the user a question and
get a result – either true or false,
depending on which button they push.
• We can store the results of the question
in a variable. We can use the variable
later in the program to perform some
action.
73
Example
var question;
question = window.confirm(“This is a question
where you have to answer OK or Cancel. OK is
true, Cancel is false. Do you understand?”);
if (question){
document.write(“You understood.”);
}
else{
document.write(“You didn’t understand.”);
}
74
window.location
• window.location is responsible for
telling the window to load a new
webpage.
• If we say
window.location=http://www.csuhayward.e
du, we will be transported to the
Hayward homepage.

75
window.history
• We can also use the window history to
go back to previous webpages.
• For example, if we want to bring the
user back to the page they just arrived
from, we can use window.history.go(-
1); to bring them back one page. We
can go back as many pages as we like.

76
Properties
• Object can have properties. These
properties are responsible for identifying
and storing information about the object.
• For example, in the example of
class.student, each instance of
student would have a property called
name.
• We can access the property using the
dot syntax for class.student.name
77
Values
• We can set the values of object
properties for instances of an object.
• In our student example, we can set the
name of the student in the following
way:
– class.student.name = “Frank”;
• Likewise, we can apply this to our
document object:
– window.document.bgColor=“red”;
78
Accessing Values...
• If we include an image in our webpage and
give it a name, we can access it as a
property.
• <img src=“image.jpg”
name=“testPic” alt=“picture”>
can be accessed by:
• document.testPic.src=“image.jpg”

79
Accessing Values…

• Likewise, if we set the background color


of our webpage to grey using:
<body bgColor=“grey”>

• We can also access that same property


using:
document.bgColor=“grey”
80
Events
• In real life, objects can encounter
events.
• An event is some action that has
happened.
• If we can identify an event that may
happen to a webpage, we can watch for
that event to happen.
• One example would be to watch where
the mouse is placed on the screen.
81
Event Handlers

• When we see an event happen, we


have to handle the event.
• One such event is mouseover, when
the mouse is placed over an object in
the webpage.
• This event can trigger an action, such
as changing the picture that the mouse
is over.
82
Mouseover Event

• Our event handler is responsible to doing


something when the event has happened.

<a href=“#”
onmouseover=“document.bgColor=‘green’;”>
This is some text</a>

• This will change the background color to


green when we put the mouse over the link.

83
onmouseout event

• We can also make things happen when


the mouse is removed from the object
(like when the mouse is removed from
on top of the link or picture).
• This is known as the “onmouseout”
event, and works in the same way.
• There are other mouse events that we
will talk about later…
84
Variables
• We have already seen some variables
used in our simple programs.
• We can set the value of a variable to
whatever we want, and we can use the
variable wherever we would use the
value.
• Variables can be reused as many times
as we want in a program.
85
Arrays
• An array is just an ordered collection of
data.
• If we want to store 10 pieces of similar
information, an array is easier than
coming up with 10 unique variable
names.
• Arrays are indexed with a number.
var pets = new Array();
pets[0] = “Fluffy”
pets[1] = “Sparky” 86
Arrays (cont’d)
• Arrays usually start at 0 and go from
there.
• Some programmers like to start their
arrays at 1 as they believe that this is
“more natural” and easier to
understand.
• As long as you are consistent, it doesn’t
really make a difference (although I do
prefer to start arrays at 0)
87
Methods
• Methods are actions that are
associated with objects. These actions
are often triggered by events or called in
the middle of a program.
• For example, the document object has
a method called write which takes care
of putting information to the browser.
• We call the method using the dot
notation –
document.write(“text”);
88
Functions
• A function is a group of statements that
have been collected together to perform
a specific task.
• Functions are grouped in such a way
that they can be reused many times in a
single program.
• We can “call” a function in the same
way that we would call a method, just by
using the function name.
89
Array Objects

• Arrays are supported as objects.

• Attribute length

• Methods include:
concat join pop push reverse sort

90
Array example code

var a = [8,7,6,5];

for (i=0;i<a.length;i++)
a[i] += 2;

b = a.reverse();

91
Many other pre-defined object types

• String: manipulation methods


• Math: trig, log, random numbers
• Date: date conversions
• RegExp: regular expressions
• Number: limits, conversion to string

92
Predefined Objects
• JavaScript also includes some objects
that are automatically created for you
(always available).
– document
– navigator
– screen
– window

93
The document object
• Many attributes of the current
document are available via the
document object:
Title Referrer
URL Images
Forms Links
Colors

94
document methods
• document.write() like a print
statement – the output goes into the
HTML document.

document.write("My title is" +


document.title);

string concatenation!

95
JavaScript Example
<HEAD>
<TITLE>JavaScript is fun!</TITLE>
</HEAD>
<BODY>
<H3>I am a web page and here is my
name:</H3>
<SCRIPT>
document.write(document.title);
</SCRIPT>
<HR>
96
JavaScript and
HTML Comments
<SCRIPT>
<!--
document.write("Hi Dave");
document.bgColor="BLUE";
-->
</SCRIPT>

97
JavaScript Functions
• The keyword function used to define
a function (subroutine):

function add(x,y) {
return(x+y);
}

98
JavaScript Events
• JavaScript supports an event handling
system.
– You can tell the browser to execute
javascript commands when some event
occurs.
– Sometimes the resulting value of the
command determines the browser action.

99
Simple Event Example
<BODY BGCOLOR=WHITE onUnload="restore()">
<H5>Hello - I am a very small page!</H5>
<SCRIPT>
savewidth = window.innerWidth;
saveheight = window.innerHeight;
function restore() {
window.innerWidth=savewidth;
window.innerHeight=saveheight;
}
// Change the window size to be small
window.innerWidth=300; window.innerHeight=50;
document.bgColor='cyan';
</SCRIPT>

100
Buttons
• You can associate buttons with JavaScript
events (buttons in HTML forms)
<FORM>
<INPUT TYPE=BUTTON
VALUE="Don't Press Me"
onClick="alert('now you are in trouble!')“ >
</FORM>

101
Some Events (a small sample)
onUnLoad
Window events
onLoad
onClick
onMouseUp Button events
onMouseDown
onDblClick
onMouseOver Link events

102
Document Object Model
• Naming hierarchy used to access
individual elements of a HTML
document.
• Netscape D.O.M. is a little different than
IE D.O.M.
• Easy to use if you name all entities:
– Forms, fields, images, etc.

103
DOM example
<FORM ID=myform ACTION=…
Please Enter Your Age:
<INPUT TYPE=TEXT ID=age NAME=age><BR>
And your weight:
<INPUT TYPE=TEXT ID=weight
NAME=weight><BR>
</FORM>

From javascript you can get at the age input


field as: document.myform.age.value

104
Form Field Validation
• You can have JavaScript code that
makes sure the user enters valid
information.
• When the submit button is pressed the
script checks the values of all necessary
fields:
– You can prevent the request from
happening.
105
Checking Fields
function checkform() {
if (document.myform.age.value == "") {
alert("You need to specify an age");
return(false);
} else {
return(true);
}
}

Needs to return true or false!


106
The Form
<FORM METHOD=GET ACTION=foo.cgi
NAME=myform
onSubmit="return(checkform())">

AGE: <INPUT TYPE=TEXT NAME=Age>


<INPUT TYPE=SUBMIT>
</FORM>

107
Important Note about Form Validation

• It's a good idea to make sure the user


fills out the form before submitting.

• Users can bypass your form – they can


create requests manually (or their own
forms).

108
Decision-Making Code

109
Outline
• Boolean variables
• How to compare values
• The “if” structure
• The “if …else” structure

110
Boolean Variables
• A Boolean variable is a variable that is
able to hold one of two values:
– true
– false
• Boolean variables are used to answer
simple questions that we can pose in a
program.
– If the answer is “true”, we do something.
– If the answer is “false”, we do something
else.
111
Creating Booleans
• var x;
• x = false;
• This means that “x” will store the value
of “false”.
• Note:
– it is not a string
– it is not a number

112
Comparing Values
• If we compare two values together, we
can determine what their relationship is.
• Once we determine their relationship,
we can store that information using a
Boolean.
• Assume three variables: x, y and z:
z = (x < y)
– If x < y, then z will be true.
– If x > y, then z will be false.
113
Comparing Values
• We can compare in different ways:
Operator Operation
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equals
!= not equals
114
Examples

if x=2 and y=3, then if:


z = (x<y); z will be true
z = (x<=y); z will be true
z = (x>y); z will be false
z = (x>=y); z will be false
z = (x==y); z will be false
z = (x!=y); z will be true
115
Comparing Strings

• We can use the “equals” operator (==)


to compare two strings.
• We can check to see if two strings are
the same:
– name1 = “Bob”;
– name2 = “Fred”;
result = (name1 == name2);
result = (name1 != name2);
116
Logic Operators

• Now that we are able to work with


Boolean variables, we need to be able
to deal with multiple Booleans.
• We may need to make multiple
comparisons and then decide, based on
the results, what we should do.
• This requires using logical operations.

117
Logical Operations
Operator Operation Performed
&& AND: true if both values are true
|| OR: true if either value is true
! NOT: negates the value

• These operations can be used on any two


Boolean values and will result in a Boolean
value itself.
118
“AND” Logic Table

Expression Resulting Value


true&&true true
true&&false false
false&&true false
false&&false false

119
“OR” Logic Table
Expression Resulting Value
true||true true
true||false true
false||true true
false||false false

120
Putting it together

• The logic tables require two Booleans.


• Since any comparison that we make
results in a Boolean, we can use these
comparisons in logic operations where
needed.
• These logic operations and Booleans
will come in handy when we have to
make decisions.
121
The “if” Statement

• One key decision statement is the “if”


statement.
• The “if” statement allows us to
determine the value of a Boolean and,
based on that value, either execute or
skip some section of code.
• This is the easiest way to control which
code we are going to run.
122
How “if” Works

if (Boolean expression) {
statement;

statement;
}

123
An “if” Example

var number;
number=prompt(“Enter a number”);
if (number < 10) {
document.write(“Your number is < 10”);
}
if (number > 10) {
document.write(“Your number is > 10”);
}
124
The “if” Example

• For our example:


– if the number is less than 10, we get one
response
– if the number is greater than 10, we get
another response
– if the number is equal to 10, what
happens?

125
An “if … else” Structure

• The “if … else” structure is similar to an


“if” structure, except that it has a second
part associated with it.
• The “else” portion catches all of that
cases that are not associated with the
“if” Boolean.
• This allows us to cover two different
cases in the same structure.
126
The “if … else” Structure

if (Boolean statement) {
statement;

}
else {
statement;

}
127
An “if … else” Example
var number;
number=prompt(“Please input a number”);
if (number < 10){
document.write(“Your number is < 10”);
}
else {
document.write(“Your number is >= 10”);
}
128
More on “if”

• “if” and “if …else” statements are the


basic building blocks to decision-making
code.
• They are the basic method used to
control which code will be executed and
which will be skipped.
• This allows the user to input information
that will effect how the program will act.
129
Some Possible Problems

• One key problem when dealing with


variables is making sure that you are
comparing what you want to compare.
• From the perspective of users entering
input, you should be careful that the
user enters in the “correct” information.
• If you are trying to compare numbers
and the user enters letters, it could
cause trouble.
130
An Example

• If we try to compare a number entered


by the user, but the user enters a string,
then the comparison will still “happen”.
• You may try to use the “number”
entered by the user later, but because it
is a string, it will cause errors.
• Your results may not turn out to be what
you want.
131
Checking Input

• We can check input from the user with a


function called “isNaN()”
• This function allows us to determine if
the parameters is “NaN”.
• Now that we can determine if a value is
a number, we will be able to ask the
user to re-enter information that we
think is correct.
132
Checking Input Example
var number, test;
number=prompt(“Enter a number”);
test = isNaN(number);
if (test) {
document.write(“The input was a string”);
}
else {
document.write(“The input was a number”);
}
133
What about bad input?

• If we receive bad input from the user,


we can warn them that the input is
incorrect with an “alert”.
• An alert will create a pop-up dialog
along with some text. The box will stay
on the screen until they click “OK”.
• This is one way to give the user some
information.
134
An “alert” Example

alert (“This is an alert on the screen!”);

135
End of Lecture

136

You might also like