You are on page 1of 6

10/11/2009 Learning JavaScript - if Statement, Boo…

Check this Freebie out!


I n t e rn e t A cce ss - Fre e Tria ls a n d S p e cia ls
NetZero, Juno, PeoplePC, EarthLink, AOL and more!

if Statement, Boolean, Functions and Variable Scope


(Lesson 5)

This lesson introduces you to two essential constructs of the JavaScript


language, the if s ta te me nt and the func tio n.
n

The if s ta te me nt is used to make decisions in JavaScript. Bo o le a n


o p e ra to rs are also discussed in this lesson because they are used in along
with the if statement.

The func tio n allows you to repeat specific JavaScript statements anytime you
want by calling the same statements without writing new ones. For example, if I
want to add two numbers at several different locations in my program, I can just
write the code one time and designate it as a function. Then I can call that
function anytime I want to add two numbers. Understand that the two numbers do
not have to be the same but can be specified at the time that the function is
called.

The final topic of this lesson is v a ria b le s c o p e . Scope determines what parts
of your program can read and change the contents of a variable.

if Statement
The if statement is one of the most used features of JavaScript. It is basically the
same in JavaScript as it is in other programming languages. If you are new to
programming, you should spend some time understanding how the if statement
works.

You use the if statement in JavaScript to make decisions. The syntax for it is as
follows:

if (condition){
statements
}

The if keyword identifies this as an if statement. The condition in the parenthesis


( ) is evaluated to determine if true, and if so then the statements inside the
curly braces { } are executed, otherwise they are skipped and the programs
continues with the first line after the if statement.

An optional else statement can be included with the if statement as follows:

if (condition){
statements
}
else{
statements
}

In this case, the statements inside of curly brackets { } after the else
keyword are executed if the condition of the if statement is false.
javascriptmall.com/learn/lesson5.htm 1/6
10/11/2009 Learning JavaScript - if Statement, Boo…

Take a look at the following table which shows the results expected from the if
statement for different conditions. In this table x and y are two variables that have
been initialized to a value.

if statement Results

condition returns true if


x == y x and y are equal
x != y x and y are not equal
x>y x is greater than y
x >= y x is greater or equal to y
x<y x is less than y
x <= y x is less than or equal to y

I have posted a script containing a simple if s ta te me nt in our electronic


chalkboard below. Let's use it to test the if s ta te me nt to discover how it works
with each of the conditions shown in the "if Statement Results" table.

Electronic Chalkboard
<HTML>
<HEAD></HEAD>
<BODY bgcolor="CCFFFF">

<P>Testing if statement<BR>
<SCRIPT language="JavaScript"><!--
var num = 4

if(num == 4){
document.write("<B>Satisfied!</B><BR>")
}
//--></SCRIPT>

Test Reset

Take a close look at the script. It contains a variable num which is initialized to 4
and an if s ta te me nt that is true if num == 4.
4 Note that this is the condition
shown in the first row of our table. When you press Test, the HTML code is
loaded into a small pop-up window so you can see the results. So press Test
now and you will see the following in the pop-up window.

Testing if statement
Satisfied!
rest of program starts here

Change the value of the num variable to some number other than 4, for instance
try 3 (i.e. change the line v a r num = 4 to v a r num = 3).3 Now the requirements
of the if s ta te me nt will not be satisfied and you will get the following when you
press Test:

Testing if statement
rest of program starts here

javascriptmall.com/learn/lesson5.htm 2/6
10/11/2009 Learning JavaScript - if Statement, Boo…
Thus, the value of our variable num must be equal to 4 for the code between the
curly braces of the if statement to be executed. Any other value of the variable
will cause this code to be ignored.

Now lets test the second condition in our table. We want the if statement to be
satisfied when num is not equal to 4. Change the if c o nd itio n for our script to
num != 4,4 i.e. replace num == 4 with it. Then test it by setting the variable num to
different values. The results should be the opposite from our first case.

To test the third condition in the table, we want the if statement to be satisfied if
num is greater than 4. So replace the if c o nd itio n for our script with
num > 4. 4 Now test it with several values for num. You will find that the if condition
is satisfied for the values 5 and 10 but not for 1 or 4.

Replacing the if c o nd itio n with num >= 4 will result in almost the same results
as our previous case except the if statement will now also be satisfied when
num = 4.

Try the last two conditions in our table, num < 4 and num <= 4. 4 This means that
the variable num will need to be less than 4 in the first case and less than or
equal to 4 in the second case for the if statement to be satisfied.

Here is a simple problem for you to solve using an if statement. You will also be
using the else statement to solve this problem. I recommend that you save your
results because you will be modifying it in one of your class assignments.
Suppose you must get a grade of 70 or better to get a passing grade for this
class. Write a script that will test to see if you passed and will display the results
in the browser. You may want to compare my solution and source with yours
after you get it completed and tested.

Boolean Operators
Suppose you wanted the previous script to display a letter grade instead of
passed/failed. You would want to display A for a 90 or above, B for a grade 80
or above but less than 90 and ETC. To determine a B you could nest if
statements as shown below. This can get real messy and require a lot of code.

if (grade < 90){


if (grade >= 80){
document.write('You got a "B"')
}
}

A better way is to use the a nd o p e ra to r,


r &&. Here is a rewrite of the script using
the and operator.

if (grade < 90 && grade >= 80){


document.write('Grade is a "B"')
}

The and operator, && , allows you to combine two conditions so that both must
be true to satisfy the if condition. Another Boolean operator is the o r o p e ra to r,
r
||, which combines two conditions such that the if statement is satisfied if either
condition is true. The third boolean operator is the N o t Op e ra to r,
r !, which
makes a condition that returns true, false and vice versa.

javascriptmall.com/learn/lesson5.htm 3/6
10/11/2009 Learning JavaScript - if Statement, Boo…
Look again at the above script and notice that phrase 'Grade is a "B"'
contains both double quotes and single quotes. This is the way you can put
quotes inside of quotes in JavaScript.

Functions
What if you wanted to use our grading script for more than one student? You
would have to repeat it for each student. This could get quite lengthy if there
were more than a very few students. You can however use a function to contain
the script and call it every time your need it. Here is the syntax for a function.

function name (parameters){


statements
}

The function keyword identifies this as a function. The parameters in the


parenthesis ( ) provide a means of passing v a lue s to the function. There
can be as many parameters separated by commas as you need. It is perfectly
ok to have a function with no parameters. These parameters are v a ria b le s
which are used by the JavaScript statements inside the curly braces { }. The
var keyword is not needed to declare the parameters in a function as variables
because they are automatically declared and initialized when the function is
called. The function can return a v a lue by using the return keyword.

You should put your functions in the HEAD section of your document. Functions
will work if you put them in the BODY section. However, a function must be
loaded prior to the statement that calls it. Putting all functions in the HEAD
section is the way to insure this.

The best way to demonstrate a function is with an example. Suppose we want to


make a function that we can call anytime to add two numbers together. Here is
one way of writing the function.

function myAdder (num1, num2){


var total = num1 + num2
document.write(total)
}

You would place this function inside some <SCRIPT> tags in the head section.
You then can call the function from anywhere in your document. In this example,
lets call it from within some <SCRIPT> tags in the body of document like this.

myAdder(23, 56)

Lab Time - Lab -

Lets try this function in our lab. Type the above myAdder() function between
some <SCRIPT> tags in the HEAD section (note that the script tags are not
automatically placed in the HEAD section for you, so you will have to put them
there yourself). Then place the call to the function in the <SCRIPT> tags in the
BODY. The results when your press Test should be 79.

Add the following two lines to the script in the BODY section to demonstrate how
to call the function a second time:

document.write("<BR>")

javascriptmall.com/learn/lesson5.htm 4/6
10/11/2009 Learning JavaScript - if Statement, Boo…
myAdder(100, 480)

Ok lets try a variation to the function that we wrote in our last lab experiment. This
time we will let the function return the value rather than print it to the document.
Then, we will print the returned value to the document from the BODY section.
Modify our function in the head section so that it looks like this:

function myAdder (num1, num2){


var total = num1 + num2
return total
}

Here is the modified code that re p la c e s the script in the BODY section.

document.write(myAdder(23, 56))
document.write("<BR>" + myAdder(100, 480))

When you test this new version, the results should be the same as we got
above. You will want to use the first method sometime and the second on others.
It will all depend on exactly what you are doing.

In our last lab experiment, there is no need to have the variable total in the
function. Out last modification for this exercise will be to modify the function as
shown below.

function myAdder (num1, num2){


return num1 + num2
}

There are no modifications needed in the BODY section. When you press the
test button, the results will be the same.

Scope of Variables
A variable that is defined outside of a function is a g lo b a l variable. A variable
that is defined inside of a function is a lo c a l variable. What does this mean?
Glo b a l variables can be used anywhere in the document that is currently
loaded in the browser. They can be declared in the HEAD section and used in
any function or even in the BODY section. Lo c a l variables can only be used in
the function that declares them. Yes, you could leave the var keyword off of the
variables you declare inside of a function and they will then be global. I do not
recommend this.

Assignment
1. This problem involves modifying the pass/fail script that we developed
during our discussion of the if statement. Write a script that contains a
function that you can pass a grade as a parameter and have it display a
passed or failed condition. Demonstrate the functions by printing out the
pass/fail status for five students.
Solution Source

2. Make a further modification to our pass/fail function so that the results are
returned to the portion of the BODY section that called it and then
displayed in the document.
javascriptmall.com/learn/lesson5.htm 5/6
10/11/2009 Learning JavaScript - if Statement, Boo…
Solution Source

3. Make a final modification to the script that we did in problems 1 and 2 so


that a letter grade is displayed instead of pass or fail. This letter grade
should be based on the following:
A is a grade of 90 or greater
B is a grade of 80 or greater, but less that 90
C is a grade of 70 or greater, but less than 80
F is any grade below 70
I recommend that you add a few more student names and grades so that
the script is adequately tested.
Solution #1 Source #1 Solution #2 Source #2 Solution #3 Source #3
As shown here, there are many solutions to most problems. There are many others in
addition to these 3.

Try I n t e rn e t Ca ll M a n a g e r
Like having another phone line for about one quarter the cost!
Caller id, web voice mail, personalized message and More!
Never miss another phone call while on-line.

[ Top of Page | Contents ]

© 1999 - 2004 by Ray Stott - All Rights Reserved.

javascriptmall.com/learn/lesson5.htm 6/6

You might also like