Register | Login
Friday, July 04, 2008

Sections
  
About Us
  
Hosting Provided by Server Intellect
Partners
Downloads
  
 WWWCoder.com Resource Directory

Introduction to JavaScript Part II
2/7/2005 8:05:59 PM

The second part of this introductory tutorial to JavaScript, here we cover functions, loops, and conditional statements in JavaScript.

By Gary Newell

Conditions

Variables enable you to store information and arrays enable you to store multiple pieces of information.

Programming really comes into its own by using logic and controlling the flow of data.

So what is this topic all about?

Take a simple login screen. If the user enters a correct username and password then you will want them to be able to enter your site but if they don't then you want the exact opposite.

Therefore a condition is:

IF STATEMENT IS TRUE

DO THIS

OTHERWISE

DO THIS

END IF

The following example shows a very basic log in screen using JavaScript.

<html>
<head>
<title>JavaScript Fundamantals - Example 8</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">
function login()
{
var name = document.form1.username.value;
var pword = document.form1.pword.value;
if (name == "admin" && pword == "space")
{
document.write("<h1>You entered the correct password</h1>");
}
else
{
document.write("<h1>You entered an incorrect password</h1>");
}
}
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<form name="form1">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" size="15"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pword" size="15"></td>
</tr>
</table>
<input type="submit" onClick="login()">
</form>
</body>
</html>

JavaScript Example 8 - Simple Login

The code in bold is the important part of the example.

In JavaScript and if statement has the following structure:

if (....) { statements } else { statements }

The actual conditions themselves are also important.

The == means is equal to.

If in the above example the code was

if (name ="admin" && pword ="space")
{
document.write("<h1>You entered the correct password</h1>");
}

The output would always be "You entered the correct password".

The reason for this is that when declaring variables the = symbol is used to assign a value to a variable and so in the if statement above you are effectively setting name to be admin and password to be space. This means the statement is true.

  • The two == symbols together stands for is equal to.
  • The > symbol stands for is greater than
  • The < symbol stands for is less than
  • The >= symbols together stand for is greater or equal to
  • The <= symbols together stand for is less than or equal to
  • The ! symbol stands for not and so != stands for not equal to.

You may have noticed in the example above the && symbol. This stands for AND. Therefore the above statement reads if name is equal to admin and pword is equal to space output "you entered the correct password".

Two | | symbols together stands for OR and can be used as follows

if (name =="admin") && (pword =="space" || pword == "erase")
{
document.write("<h1>You entered the correct password</h1>");
}

The above code translates into the following IF name is equal "admin" AND password is equal to "space" or "erase" then display "you entered the correct password".

The brackets () are very important and placing them incorrectly can change the whole logic of a script.

if (name =="admin" && pword =="space") || (pword == "erase")
{
document.write("<h1>You entered the correct password</h1>");
}

The above code is completely different from the previous code and translates into the following:

IF name is equal to "admin" and password is equal to "space" OR the password is equal to "erase" display "you entered the correct password". This means that as long as you enter the word erase into the password it doesn't matter what you enter into the username box.

Finally in this section there is a function called isNaN();

This function tests whether a variable contains a number or not. This is useful when validating that someone has entered the correct information onto a form as is shown by the following example.

<html>
<head>
<title>JavaScript Fundamantals - Example 9</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">
function checkage()
{
var age = document.form1.age.value;
if (isNaN(age))
{
document.write("<h1>Your age must be numeric</h1>");
}
}
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<form name="form1">
<table>
<tr>
<td>Enter Your Age</td>
<td><input type="text" name="age" size="3"></td>
</tr>
</table>
<input type="submit" onClick="checkage()">
</form>
</body>
</html>

JavaScript Example 9 -Age Check

If you run the above example and enter a letter into the age box and press the submit query button you will be told that you must enter a numeric age.

Loops

Loops are a very valuable commodity within any programming language as they enable you to run the same code over and over again.

There are two types of loop

  • The FOR loop enables you to perform the same portion of code a set number of times.
  • The WHILE loop enables you to perform the same portion of code until a condition occurs.

The FOR loop was used in the array section earlier on in this tutorial. Remember the example that collected 10 names and then sorted them into alphabetical order?

<html>
<head>
<title>JavaScript Fundamantals - Example 7</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<script language="JavaScript">
var names = new Array(10);
for (var idx=0;idx<10;idx++)
{
names[idx]=prompt("Please enter a name");
}
document.write("<h3>The names you entered were...</h3>");
document.write(names + "<br>" + "<h3>In alphabetical order...</h3>");
var namesort = names.sort();
document.write(namesort);
</script>
</body>
</html>

JavaScript Example 10 - The For Loop

The FOR loop has the following syntax:

for (iterations) { statements }

The iteration part is broken down as follows

var idx=0;

This is the starting value.

idx<10;

This states that the loop will run whilst the value of idx is smaller than 10.

idx++;

This increments idx each time round the loop so it starts at 0 and then becomes 1,2,3,4,5,6,7,8,9 and then the loop ends.

FOR loops are therefore very useful when collecting a finite number of items. You can see in the above example the statement

names[idx]=prompt("Please enter a name");

As this statement is within the loop idx has a different value each time around and so it actually means

names[0]=prompt("Please enter a name");

names[1]=prompt("Please enter a name");

names[2]=prompt("Please enter a name");

and so on.

The WHILE loop is used when you don't know how many times you want the loop to be performed and you only want to end the loop when a certain condition is met as the following example shows:

<html>
<head>
<title>JavaScript Fundamantals - Example 11</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<script language="JavaScript">
var num1 = Math.floor(Math.random()*101)+1;
var num2 = 144;
while (num2!=num1)
{
num2=prompt("Guess a number between 1 and 100");
if (isNaN(num2))
{
alert("Enter a number");
}
else
{
if (num2<num1)
{
alert("Too Small");
}
else
{
if (num2>num1)
{
alert("Too Big");
}
}
}
}
alert("well done");
</script>
</body>
</html>

 

JavaScript Example 11- Guessing Game

The above example is the simple guessing game where you have to guess a number between 1 and 100.

num1 is given a random number.

The while loop then goes around and asks the user to enter a number which is placed in num2. When num1 and num2 match the loop is ended.

The format for a WHILE loop is

while (condition not met) { statements }

Sometimes you may wish to break out of a while loop and so there is a command called break; which enables you to do this.

In the above example there are a large number of nested IF statements. A nested IF statement is an IF statement within another IF statement as follows:

IF (statement)

{

if (statement)

{

}

}

The nested IF statements were necessary because firstly the code needs to check whether the user has entered a number, then it needs to check whether the number is too high and finally it needs to check if its too low.

The continue; statement is used to skip around the rest of the loop missing out all the following statements. This means that if the user had entered the word "CAT" when asked for a number the following checks did not need to be made.

Therefore the code could be made easier to read as follows:

<html>
<head>
<title>JavaScript Fundamantals - Example 11</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<script language="JavaScript">
var num1 = Math.floor(Math.random()*101)+1;
var num2 = 144;
while (num2!=num1)
{
num2=prompt("Guess a number between 1 and 100");
if (isNaN(num2))
{
alert("Enter a number");
continue;

}

if (num2<num1)
{
alert("Too Small");

continue;
}

if (num2>num1)
{
alert("Too Big");
continue;

}
}
alert("well done");
</script>
</body>
</html>

Functions

Have you ever heard the term reinventing the wheel? Without functions that is exactly what you would be doing.

Functions enable you to create sections of code that can be called again and again.

Throughout this tutorial you have seen instances of functions as follows:

document.write();

isNaN()

alert()

It is at this point in time that its worth learning about external files. All the examples that you have seen so far have been included inline with the rest of the HTML. It is possible to link an external file to a HTML file. The external file usually contains a list of functions that can be called from within a HTML script.

<html>
<head>
<title>JavaScript Fundamentals</title>
<script language="JavaScript" SRC="external.js">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

Within external.js you do not have to specify the <SCRIPT> and </SCRIPT> tags as these are implied already.

Within external.js you can now create any functions you wish to call and its a useful place to have a library of commonly used routines.

So what does a function look like

function checkage(age)
{
if (age<18)
{
return false;
}
else
{
return true;
}

The above function checkage takes a value called age and then if the age is less than 18 it returns the value false otherwise it returns the value true.

You can perform any code you wish in a function.

The following is the actual structure of a function.

function functionname([argument,argument2,argument3])
{
statements;

[return true;]
}

The parts between [] are optional.

To call a function you just specify the name of the function and supply any arguments that the function needs. The following example asks the user for their age and then tells them whether they are old enough to view the site.

<html>
<head>
<title>JavaScript Fundamantals - Example 12</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">

function checkage(age)
{

if (age < 18)
{
return false;
}
else
{
return true;
}

}

</script>
</head>

<body bgcolor="#FFFFFF" text="#000000">

<script language="JavaScript">
var age = prompt("Enter your age");
if (checkage(age))
{
alert("You are old enough");
}
else
{
alert("You are not old enough");
}
</script>
</body>
</html>

JavaScript Example 12 - Age Check

In the above example the user is asked to enter their age. The IF statement then calls the checkage function which returns true or false. If the user is over 18 then they are told they are old enough otherwise they are told they are not.

The function may not seem all that useful but for adult sites that need to check on people's ages the function can be called from anywhere. All the person coding their page has to do is provide a number in the age field.

They could work out the age from a date of birth field.

The final thing to mention in this section is the lifetime of a variable.

A variable declared outside of a function is called a global variable and can be used by any part of the script at any time.

A variable declared inside of a function is called a local variable and dies when the function has finished running.

Although in the example above the variable age was passed to the checkage function which also used the variable age they are two separate variables as the following script shows:

 

 

<html>
<head>
<title>JavaScript Fundamantals - Example 13</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">

function checkage(age)
{

if (age < 18)
{
return false;
}
else
{
return true;
}

}

</script>
</head>

<body bgcolor="#FFFFFF" text="#000000">

<script language="JavaScript">
var myage = prompt("Enter your age");
if (!checkage(myage))
{
document.write("you are too young");
document.write(age);
}

</script>
</body>
</html>

JavaScript Example 13 - Age Check

If you ran the above example and expected the age to be the number you entered for myage then you'd be wrong. What you actually get is nothing except the words "you are too young". The variable age has not been declared outside of the function checkage and so has no value.

 


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970