Javascript Lesson 3

Foreword

This lesson introduces you to two essential constructs of the JavaScript language, the if statement and the function.
The if statement is used to make decisions in JavaScript. Boolean operators are also discussed in this lesson because they are used in along with the if statement.
The function 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.

3.1 The if statement

The if statement is one of the most used features of JavaScript. It is the same in JavaScript as it is in other programming languages like Java and C.
You use the if statement to make decisions. The syntax for it is as follows:

 if (condition){
   statements
   }

The if keyword identifies this as an if statement.
The condition between 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 after the else keyword are executed if the condition of the if statement is false.

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.

Condition:Returns true if:
x == yx and y are equal
x != yx and y are not equal
x > yx is greater than y
x >= yx is greater than or equal to y
x < yx is less than y
x <= yx is less than or equal to y

Now it is time to try something out. Copy the code below and use it to test the if statement.

<script language="JavaScript">
<!-- hide from old browsers

var number = 23

if(number == 23){
  document.write("Statisfied.")
  }
else{
  document.write("Not statisfied.")
  }

//-->
</script>

The result should be: Statisfied.

Take a close look at the script. It contains a variable number which is initialized to 23
and an if statement that is true if number == 23.

Change the value of the number variable to some number other than 23.
Now the requirements of the if statement will not be statisfied and this will be the result:

Not statisfied.

Thus, the value of our variable number must be equal to 23 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 and automatically go to the else statement.

Now lets try the other conditions:

  • We want the if statement to be satisfied when number is not equal to 23. Change the condition for our script to

    number != 23

    Then test it by setting the variable number to different values.
    The results should be the opposite from our first case.


  • We want the if statement to be satisfied if number is greater than 23. Change the condition for our script to

    number > 23

    Then test it by setting the variable number to different values.
    You will notice that the if statement will only be executed when the value of number is greater than 23.


  • Now try all the other conditions on your own:
    • number >= 23
    • number < 23
    • number <= 23

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.
Suppose you must be 140cm or more to be allowed to enter a rollercoaster.
Write a script that will test to see if you are allowed to enter the rollercoaster and will display the result in the browser.

Solution:

<script language="JavaScript">
<!-- hide from old browsers

var height = 160

if(height >= 140){
  document.write("You are allowed to enter the rollercoaster!")
  }
else{
  document.write("You are not allowed to enter the rollercoaster!")
  }

//-->
</script>

3.2 Boolean Operators

Suppose you wanted the previous script to display if the child needs to be accompanied by a parent or not.
You would want to display "Allowed to go alone" for 160cm or greater,
"Needs to be accompanied by a parent" for 140cm or greater but less than 160cm
and "Not allowed to enter" for less than 140cm.
To determine a "Needs to be accompanied by a parent" you should use the and operator.
(You could also use a double if statement, but that could get real messy.)
Here is what the script code should be:

<script language="JavaScript">
<!-- hide from old browsers

var height = 170

if(height >= 160){
  document.write("Allowed to go alone!")
  }
if(height < 140){
  document.write("Not allowed to enter!")
  }
if(height >= 140 && height < 160){
  document.write("Needs to be accompanied by a parent!")
  }

//-->
</script>

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 or operator, ||, which combines two conditions such that the if statement is satisfied if either condition is true.
The third boolean operator is the Not Operator, which makes a condition that returns true, false and vice versa.

3.3 Functions

What if you wanted to use our rollercoaster script for more than one person?
You would have to repeat it for each person. This would make the script verry long if there were more than a very few persons.
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 values 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 variables 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 value 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:

<script language="JavaScript">
<!-- hide from old browsers

 function numberAdder (number1, number2){
   var numberSum = number1 + number2
   document.write(numberSum)
   }

//-->
</script>

You would place this function in the head section.
You then can call the function from anywhere in your document.
In this example, lets call it from within the body of the document like this:

<script language="JavaScript">
<!-- hide from old browsers

  numberAdder(16, 23)

//-->
</script>

To call the function more than once, you should do this:

<script language="JavaScript">
<!-- hide from old browsers

  numberAdder(16, 23)
  document.write("<br>")
  numberAdder(4, 42)
  document.write("<br>")
  numberAdder(15, 156)
  document.write("<br>")
  numberAdder(123, 345)

//-->
</script>

Now you know all this, try to make a html document yourself and put the two scripts at the right place.
(The function code in the Head part and the code that calls the function in the Body part)

After doing this, you could try to change the document.write(numberSum) from the function code to:

return numberSum

And change the numberAdder(16, 23) (and all the others) from the script that calls the function to:

document.write(numberAdder(16, 23))

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

3.4 Scope of Variables

A variable that is defined outside of a function is a global variable.
A variable that is defined inside of a function is a local variable.

Global variables can be used anywhere in the document.
They can be declared in the Head section and used in any function, or even in the Body section.

Local variables can only be used in the function that declares them.

Before continuing to the next lesson, make sure you know how to use if statements and functions.

I would also advise that you try to write a script where you make a function in the Head section of the document and that you call it in the body part of the document.
Why don't you try to make numberMultiplier or a numberDivider?

Home | Code | Learn
© 2007-2008 ProgLogic, all rights reserved. | ProgLogic.com is created by Stijn Strickx. | e-mail