Comparison Operators and if else by 826T9IJJ

VIEWS: 13 PAGES: 45

									http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript TUTORIAL for beginners
This tutorial is intended for beginners who understand HTML and basic webpage designs and
who want to enhance the "interactive features" of webpage using Javascript.

If you are a mathematical kind of person and want jump coding, skip this introduction and go
directly to the next page . Otherwise go ahead and read on.

Pre Requisite


If you are not accustomed to HTML, we suggest that you take a quick beginnners HTML
Tutorial . It does not take much time.

INTRODUCTION


Javascript is an easy-to-use programming language that can be embedded within your web
pages. Assume that you want to create a web page that calculates and displays the Body Mass
Index (BMI) for a person of given height and weight. A simple HTML will not be able to do
that. Javascript will come handy in such situation. Javascript can enhance the dynamics and
interactive features of your page by allowing you to perform calculations, check forms, write
interactive games, add special effects, customize graphics selections, create security
passwords and more.

What is JavaScript?

* JavaScript adds interactivity to HTML pages
* JavaScript is a lightweight scripting programming language
* A JavaScript is usually embedded directly into HTML pages
* JavaScript is an interpreted language. The scripts execute without preliminary compilation.
* No License is required to use Javascript

Drifference between Java and Javascript

Java and Javascript have almost nothing in common except for the name. Java was developed
by Sun Microsystems.Javascript was invented by Brendan Eich at Netscape (with Navigator
2.0), and has appeared in all Netscape and Microsoft browsers since 1996. Java is a powerful
and much more complex programming language - in the same category as C and C++.

Java is coded in a similar fashion to C++, with separate header and class files, compiled
together prior to execution. It is powerful enough to write major applications and insert them
in a web page as a special object called an "applet." Java has been generating a lot of
excitment because of its unique ability to run the same program on IBM, Mac, and Unix
computers. Java is not considered an easy-to-use language for non-programmers.

                                                                                       1
http://www.referencedesigner.com/tutorials/js/js_22.php



Javascript is much simpler to use than Java.

Your First Hello World Javascript



No Special compiler, interpreter or server side installation is required to start running
javascript. It means that you can start writing javascript on a text editor and open it in a
browser. Let up jump start and write the following code in a text file.

<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>



The text in the blue is the part of the normal html code and the text in the red is part of the
javascript. Save the file as, say, hello.htm. If you open the file in a browser it will produce the
following.

Hello World!


Try the Example online


You may like to make changes into the example and see how the things work. Since
javascript is supported by all the browsers, you may just write them in a text file and open in
a browser to see how it looks like. You may also like to make changes and see the effect
online at the link below. The page will open in a new Window.

Javascript Hello World Example

Explanation


The <script> tag is used to insert a JavaScript into an HTML page. Inside the <script> tag we
use the "type=" attribute to define the scripting language. So, the <script
type="text/javascript"> and </script> tells where the JavaScript starts and ends.

The word document.write is a standard JavaScript command for writing output to a page.

By entering the document.write command between the tags, the browser will recognize it as a


                                                                                           2
http://www.referencedesigner.com/tutorials/js/js_22.php


JavaScript command and execute the code line. In this case the browser will write Hello
World! to the page:

Browsers that do not support JavaScript


If a browser do not support Javascript, it will display the whole content of the javascript that
is written between <script> and</script>. To prevent this an HTML comment tag <!-- just
before the first JavaScript statement, and a --> (end of comment) after the last JavaScript
statement is added as shown below.

<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>




The two forward slashes at the end of comment line (//) is the JavaScript comment symbol.
This prevents JavaScript from executing the --> tag.

Javascript Statements and Comments


We will now discuss the basic fabrics of javascripts. We will explore the nuts and bolts
syntax and structures in the next few chapters.

Javascript Statements


Take a look at the following line below again

document.write("This is a reference designer tutorial");

The line is called a javascript statement. It tells browser what to do. Statements are used in
JavaScript to control its program flow. "Usually", there is a semicolon at the end of each
executable statement. It is a good programming practise to add a semicolon at the end of the
statement to make it more readable. The semicolon is, however, optional , and you may find
examples without the semicolon at the end.

Javascript Code



                                                                                          3
http://www.referencedesigner.com/tutorials/js/js_22.php



The Javascript code or simply javascript is a sequence of the statements. Take a look at the
following javascript code.

document.write("<p>This is a reference designer tutorial Line 1</p>");
document.write("<p>This is a reference designer tutorial Line 2</p>");
document.write("<p>This is a reference designer tutorial Line 3</p>");

As expected this this produces the following lines

This is a reference designer tutorial Line 1
This is a reference designer tutorial Line 2
This is a reference designer tutorial Line 3


Javascript Comments


A single line comment in javascript starts with //. Take a look at the following example.

document.write("<p>This is a reference designer tutorial Line 1</p>");
document.write("<p>This is a reference designer tutorial Line 2</p>");
//document.write("<p>This is a reference designer tutorial Line 3</p>");

The third line is now a comment instead of a statement. As a result the above javascript code
produces following output.

This is a reference designer tutorial Line 1
This is a reference designer tutorial Line 2

Comments are also used to make the code more readable. Take the following example

// Name
document.write("<p>Name : Michael Johnson</p>");
// Address
document.write("<p>Address : 123 Main Street</p>");
document.write("<p>Austin, TX </p>");

The comments should be profusely used for better understanding of the code. The above code
produces the following result

Name : Michael Johnson
Address : 123 Main Street
Austin, TX


Multiline Comments


                                                                                       4
http://www.referencedesigner.com/tutorials/js/js_22.php



If we have multiple lines that we want to comment, then we can elcose them between /* and
*/. Take a look at the following example

/*
**********************************************
This is just another example
To show you how to use a multiline
comment
**********************************************
*/

document.write("<p>This is a reference designer tutorial Line 1</p>");
document.write("<p>This is a reference designer tutorial Line 2</p>");
document.write("<p>This is a reference designer tutorial Line 3</p>");


The above javascript code produces following output.

This is a reference designer tutorial Line 1
This is a reference designer tutorial Line 2
This is a reference designer tutorial Line 3


Comments at the end of Line


Sometimes, to preserve the continuity of readability, especially during mathematical
statements, it is a good practice to put comments at the end of a line or a statement.


document.write("<p>This is a reference designer tutorial Line 1</p>"); //this is line 1
document.write("<p>This is a reference designer tutorial Line 2</p>"); // this is line 2
document.write("<p>This is a reference designer tutorial Line 3</p>"); // this is line 3


This makes the progam more readable in many circumstance. As expected it produces the
following result.

This is a reference designer tutorial Line 1
This is a reference designer tutorial Line 2
This is a reference designer tutorial Line 3


In actual practice we will be using a mix of all three comments to make program more
readable. Many programming practice decorate the coding using * at the start of functions etc
and give it a better look.



                                                                                           5
http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript Variables and Operators


We will start this chapter wil the simple example below that takes in length and breadth of a
rectangle and calculates and displays the area of the rectangle. Take a look at the following
example.

<html>
<body>
<script type="text/javascript">
<!--
length = 20 ;
width = 10 ;
area = length * width;
document.write(" Area of rectangle is ", area);
//-->
</script>
</body>
</html>



If you "run" the above javascript code you should see the following output

Area of rectangle is 200

This was expected. You may like to try this example at the following link. Try making
changes and see what works and what breaks.

Javascript Rectangle Area Example

Let us now understand two fabrics of javascripts that we have already used in the above
example - the variables and the operators.

JavaScript Variables


As you might have already guessed, the length, width and the area are the variables. The
variables are the containers to store value or information.

You will also like to keep in mind two simple rules for naming a variable.

* Variable names are case sensitive - so area is different from Area.

* They must begin with a letter or the underscore character - so 1length is an invalid variable
name.
* JavaScript is case-sensitive, variable names are case-sensitive.

Declaring JavaScript Variables

                                                                                        6
http://www.referencedesigner.com/tutorials/js/js_22.php



Take a look at the following three equivalent examples. All three are equivalent but differ in
the way the variables are declared.


length = 20 ;
width = 10 ;
area = length * width;
document.write(" Area of rectangle is ", area);


var length = 20 ;
var width = 10 ;
var area = length * width;
document.write(" Area of rectangle is ", area);


var length = 20 ;
var width = 10 ;
area = length * width;
document.write(" Area of rectangle is ", area);


We can create a variable with a var statement

var length = 20;

We can however create a variable name without a var statement

length = 20;

The variable name is on the left side of the expression and the value you want to assign to the
variable is on the right.

Let us now take a look at the operators. Look the following line in the above example

area = length * breadth ;

The * is a multiplication operator. You should also note that = is a assignment operator. The
purpose of the assignment operator is to "assign" the value. The value on the right of the =
operator is assigned the to variable on the left of the = operator.

Arithmetic and Assignment Operators


We will start this chapter wil the simple example below that shows the five arithmetic

                                                                                         7
http://www.referencedesigner.com/tutorials/js/js_22.php


operators.

Addition +
Subtraction -
Multiplication *
Division /
Modulus %

<html>
<body>
<script type="text/javascript">
<!--
/*
******************************************************************
Example Addition, Subtraction, multiplication operators
******************************************************************
*/
var x = 20 ;
var y = 10 ;

//Addition
p = x + y;
document.write(" x + y is ", p);
document.write("<br />");
//Subtraction
q = x - y;
document.write(" x - y is ", q);
document.write("<br />");
//Multiplication
r = x * y;
document.write(" x * y is ", r);
document.write("<br />");
//Division
s = x / y;
document.write(" x / y is ", s);
document.write("<br />");
//Modulus
x = 10 ;
y=6;
z = x % y;
document.write(" x % y is ", z);
document.write("<br />");
//-->
</script>
</body>
</html>



If you "run" the above javascript code you should see the following output

                                                                             8
http://www.referencedesigner.com/tutorials/js/js_22.php


x + y is 30
x - y is 10
x * y is 200
x / y is 2
x % y is 4

You can try to experiment it online at the following link ( opens in a new window).

Javascript Arithmetic Operator Example

This was expected. The Modulus operator % gives the remainder. So 5 % 2 is 1, 10 % 8 is 2
and 10 % 2 is 0.

Increment and decrement operators



Increment and decrement operators and increase values by 1. Historically, they bear
similarity to C language. The example below should clarify it

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Increment and Decrement operators
********************************************************
*/
var x = 20 ;
var y = 10 ;

//Increment
x++;
document.write(" x++ is ", x);
document.write("<br />");
//Decrement
y--;
document.write("y-- is ", y);
//-->
</script>
</body>
</html>



This gives out the following result

x++ is 21

                                                                                      9
http://www.referencedesigner.com/tutorials/js/js_22.php


y-- is 9

Try this example at the following link ( opens in a new window).

Javascript Increment and decrement Operator Example

Assignment operators


We have already seen one assignment operator "=" . The table below lists out these
assignment operators.

Operator Example                       Is equivalent to
=        x=y                           x=y
+=       x+=y                          x=x+y
-=       x-=y                          x=x-y
*=       x*=y                          x=x*y
/=       x/=y                          x=x/y
%=       x%=y                          x=x%y


Given below is an example that uses these arithmetic operators.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Assignment operators
********************************************************
*/
var x = 20 ;
var y = 10 ;

// x+=y is equivalent to x = x-y
x+=y;
document.write(" x+=y is ",x );
document.write("<br />");
x = 20;
y = 10;
x-=y;
// x-=y is equivalent to x = x-y
document.write("x-=y is ", x);
document.write("<br />");
x = 20;
y = 10;
x*=y;

                                                                                     10
http://www.referencedesigner.com/tutorials/js/js_22.php


// x*=y is equivalent to x = x*y
document.write("x*=y is ", x);
document.write("<br />");
x = 20;
y = 10;
x/=y;
// x/=y is equivalent to x = x/y

document.write("x/=y is ", x);
document.write("<br />");
x = 20;
y = 10;
x%=y;
// x%=y is equivalent to x = x%y
document.write("x%=y is ", X);
document.write("<br />");

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



This gives out the following result

x+=y is 30
x-=y is 10
x*=y is 200
x/=y is 2
x%=y is 0


The assignment operator x+=y looks confusing at first. You may prefer use x=x+y if you feel
comfirtable. But the programming community is notorious for brevity. So you will always
find examples and scripts that uses x+=y more often than not. An easy way to remember is
the x=+y is not valid. You can remember it like this
x = +y will assign +y to x which is not we wanted. So the other one x+=y obviously looks
coorect.

Try this example at the following link ( opens in a new window).

Javascript Assignment Operator Example

Comparison Operators and if else


Comparison operators are used for comparing the value of the variables. In conjunction with if and
                                                                                            11
http://www.referencedesigner.com/tutorials/js/js_22.php


else statements they make up the most important fabric of the javascript programming language.
Let us take an example

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example if ...else and conditional operator
********************************************************
*/
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
//-->
</script>
</body>
</html>




If you run the above script it should display "good morning" or "good evening" depending upon the
time when you play this code. The < ( less than) is a conditional operator.

You can try to experiment it online at the following link ( opens in a new window).

Javascript if else Example

The table below gives a list of the conditional operators.

Operator      Description                                    Example

==            is equal to                                    5==8 returns false

===           is equal to (checks for both value and type) x=5
                                                           y="5"



                                                                                           12
http://www.referencedesigner.com/tutorials/js/js_22.php


                                                            x==y returns true
                                                            x===y returns false
!=             is not equal                                 5!=8 returns true

>              is greater than                              5>8 returns false

<              is less than                                 5<8 returns true

>=             is greater than or equal to                  5>=8 returns false

<=             is less than or equal to                     7<=8 returns true




Conditional Statements

JavaScript has the following conditional statements, that are used to perform different actions for
different decisions.

if else Statements
< If the condition is true one block of statements ( if) is executed, otherwise else block is executed.
if (condition)
{
code to be executed; //if condition is true
}
else
{
code to be executes; // if condition is false
}

The example at the top of the page showed the if else construct.

if Statements
Use this statement if you want to execute some code only if a specified condition is true. The syntax
of i f statement is as follows
if (condition)
{
code to be executed; //if condition is true
}

The example below shows an if contruct.

<html>
<body>
<script type="text/javascript">


                                                                                                 13
http://www.referencedesigner.com/tutorials/js/js_22.php


<!--
/*
********************************************************
Example Increment and Decrement operators
********************************************************
*/
var d = new Date();
var time = d.getHours();
if (time < 12)
{
document.write("It is not past noon yet");
} document.write("Have a nice day"); //-->
</script>
</body>
</html>




Javascript switch statement


There are instances when you have to write a code which will have endless "if" ..."else if" ...
"else if" statements. While you can do like this, javascipt provide a switch statement that
makes the code look cleaner.

Let us look at the example the prints the day of the week.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example switch statement
********************************************************
*/
var day = new Date();
myday = day.getDay();
switch (myday)
{
case 0:
  document.write("Today is Sunday");
  break;
case 1:
  document.write("Today is Monday");
  break;
case 2:
  document.write("Today is Tuesday");

                                                                                         14
http://www.referencedesigner.com/tutorials/js/js_22.php


  break;
case 3:
  document.write("Today is Wednesday");
  break;
case 4:
  document.write("Today is Thursday");
  break;
case 5:
  document.write("Today is Friday");
  break;
default:
  document.write("Today is Saturday");
}

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



If you run the above script it should display the day of the week.

You can try this example online here.

Javascript switch Example

Javascript switch statement

For those who would like to refer to the Syntax of the switch statements here is it



switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}




                                                                                      15
http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript Pop up Boxes

Till now we have used only one kind of output statement - document.write. Javascript has
few more "interactive" output statements in the form of Pop up Boxes. There are three types
of Pop up Boxes - Alert box, Confirm Box and Prompt Box. Let us take a look at the Alert
Box.

Alert Box


A javascript alert box pops-up with a message and an 'OK' button. It displays an alert box
with a string passed to it. For example: alert() will display an empty dialog box with just the
'OK' button. The alert("Hello world") will display a dialog box with the message, 'Hello
world' and an 'OK' button.

Let us look at the example that simply displays the "Hello World" pop up box when loaded.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Pop up Box - "Hello World"
********************************************************
*/
alert("Hello world");

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



You can try this example online at the link below, which will open in a new window.

Javascript Alert Box Example


Alert Box - Another Example - Day of week


Here is another example which will simply pop up an alert box which will display the day of
week.

<html>
<body>

                                                                                         16
http://www.referencedesigner.com/tutorials/js/js_22.php


<script type="text/javascript">
<!--
/*
********************************************************
Example Pop up Box - "Day of week"
********************************************************
*/
var day = new Date();
myday = day.getDay();
switch (myday)
{
case 0:
  alert("Today is Sunday");
  break;
case 1:
  alert("Today is Monday");
  break;
case 2:
  alert("Today is Tuesday");
  break;
case 3:
  alert("Today is Wednesday");
  break;
case 4:
  alert("Today is Thursday");
  break;
case 5:
  alert("Today is Friday");
  break;
default:
  alert("Today is Saturday");
}


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




If you run the above script it should display the day of the week in a pop up box.

You can try this example online at the link below, which will open in a new window.

Javascript Alert Box - Day of week Example




                                                                                      17
http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript Confirm Box


The Javascript confirm box differs from a regular alert box in that, it provides two choices for
the user: 'OK' and 'CANCEL' to confirm or reject the request. The confirm statement takes a
string that will be displayed with the text box along with the OK and the Cancel Button. In
addition it will return a value. The returned value will be true if OK button is pressed. The
returned value will be false if Cancel button is pressed. We can use a variable and an if
statement to determine if the 'OK' or 'CANCEL' button is clicked..

Let us look at the example that simply displays a confirm box and diplays an alert box with a
message "You said :OK" if the user presses OK button. It will display an alert box with a
"You said : Cancel", if the user presses Cancel Button.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example confirm Box
********************************************************
*/
var answer = confirm("Do you want continue ?");
if (answer)
alert("You said: Ok");
else
alert("You said: Cancel");
//-->
</script>
</body>
</html>



You can try this example online at the link below, which will open in a new window.

Javascript confirm Box Example

Confirm Box - Another Example - Directing to another
link

Here is another example which displays a confirm box and asks user if he wants to get
directed to another news link. If the user presses OK it takes to a news link.

<html>
<body>
<script type="text/javascript">
                                                                                        18
http://www.referencedesigner.com/tutorials/js/js_22.php


<!--
/*
********************************************************
Example confirm box - directing to another link
********************************************************
*/
var answer = confirm("Do you want to search something in google ?");
if (answer)
window.location = "http://www.google.com";
else
alert("You said: Cancel");

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


window.location makes you jump to another web link assigned to it.

You can try this example online at the link below, which will open in a new window.

Javascript confirm Box - Redirect to another location Example



Javascript Prompt Box


Prompt uses a text field to enter a value. It also has 'OK' and 'CANCEL' buttons.

The text input to the prompt can be stored in a variable.

Let us look at the example that simply displays a prompt box and diplays an alert box with a
message. The message displayed in the alert box will depen upn the user input in the prompt
box.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Prompt Box
********************************************************
*/
var name = prompt("What is your name?", "Type your name here");
alert("Your name is: "+name)


                                                                                      19
http://www.referencedesigner.com/tutorials/js/js_22.php


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



You can try this example online at the link below, which will open in a new window.

Javascript Prompt Box - Example

For Loop


The for loop is useful when we want to execute the same statement for a large number of
times. Let us assume that we want to covert degree fahrenheit into degree celcius.
The formula for cooverting degree celcius into degree fahrenheit is

C = 5 * (F-32)/9

Let us assume that we want to calculate and print the value of the degree Celcius for values of
degree fahrenheit from 31 to 40. We can do it as shown in the example below.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Converting Degree Fahrenheit into degree Celcius
********************************************************
*/
var F = 31;
var C = 0.56 * (F-32);
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 32;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

var F = 33;
var C = 0.56 * (F-32);
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 34;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

var F = 35;

                                                                                       20
http://www.referencedesigner.com/tutorials/js/js_22.php


var C = 0.56 * (F-32);
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 36;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 37;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 38;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 39;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

F = 40;
C = 0.56 * (F-32) ;
document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

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


The program will produce the desired result. However, the same statement is repeated again
and again. In such case the for loop is used. Let us write the same program using a for loop.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Area of Rectangle - Using functions
********************************************************
*/


var F, C;
for ( F= 31; F<=40; F++)
{

C = 0.56 * (F-32);

document.write(F , " deg F is equivalent to ", C, " deg C "," <p>");

                                                                                       21
http://www.referencedesigner.com/tutorials/js/js_22.php


}
//-->
</script>
</body>
</html>



Inside the for loop, enclosed in brackets ( ), we initialise the variable F to 31. The condition
(F <=40) is then evaluated. Since F is less than equal to 40, the statements inside the for loop
are executed.

After executing the statement, the javascript executes the statement F++,which increases the
value of F to 32. It then again test the condition (F<=40). Since it is true again, the statements
inside the for loop is executed again.

This goes on till the value of F becomes larger than 40. At this point, the statement
immediately following the for loop is executed.

We have defined a function which will calculate the area of the rectangle. Let us take a look
at the fuction again.

You can try this example online at the link below, which will open in a new window.

Javascript for loop - Example

Having looked at the example, let us take a look at the formal definition of the for loop.

for (Initialization statements; Condition; Updation statements)
{
...
statements
...
}

When the JavaScript interpreter comes across a for loop, it executes the initialization
statements and then checks the condition. Only when the condition returns 'true', the
interpreter enters the loop. After the first iteration, the updation statements are executed and
then the condition is evaluated again. This continues till the condition returns 'false' and the
loop stops. Some important points to note are:

* The initialization statements are executed once; only when the for loop is encountered.
* After execution of initialization statements, the condition is evaluated.


                                                                                          22
http://www.referencedesigner.com/tutorials/js/js_22.php


* After every iteration, the updation statements are executed and then the condition is
checked.

While Loop



The JavaScript while loop consists of a condition and the statement block.

while (condition)
   {
   ...statements...
   }

The condition is evaluated. If the condition is true the statements are evaluated. If the
statement is false we exit from the while loop.

Let us take a simple example below that prints the number from 0 to 10.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example While loop
********************************************************
*/
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
//-->
</script>
</body>
</html>



The example defines the while loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. The value of i will increase by 1 each time the loop runs.

You can try this example online at the link below, which will open in a new window.

Javascript while loop - Example


                                                                                            23
http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript Functions


Let us assume that you want to calculate and print the area of a rectangle for 5 different sets
of length and breadth values. The problem is easy. You can do that by writing the same code
again and again for 5 different values as follows
<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Area of Rectangle
********************************************************
*/
length1 = 20 ;
width1 = 10 ;
area1 = length1 * width1;
document.write(" Area of rectangle 1 is ", area1,"<p>");

length2 = 30 ;
width2 = 20 ;
area2 = length2 * width2;
document.write(" Area of rectangle 2 is ", area2,"<p>");

length3 = 5 ;
width3 = 3 ;
area3 = length3 * width3;
document.write(" Area of rectangle 3 is ", area3,"<p>");

length4 = 10;
width4 = 8 ;
area4 = length4 * width4;
document.write(" Area of rectangle 4 is ", area4,"<p>");

length5 = 15;
width5 = 12;
area5 = length4 * width4;
document.write(" Area of rectangle 5 is ", area5,"<p>");
//-->
</script>
</body>
</html>


The program will produce the desired result. It will calculate the area of the rectangle for 5
different sets of values of the length and width.

We can however use function to solve the problem. The example below solves the same
problem using functions
                                                                                         24
http://www.referencedesigner.com/tutorials/js/js_22.php


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example Area of Rectangle - Using functions
********************************************************
*/
function rectangle_area(length, breadth)
{
var area = length * breadth ;
return area;
}

//-->
</script>
</head>


<body>
<script type="text/javascript">
<!--
var length = new Array();
length[0] = 20;
length[1] = 30;
length[2] = 5;
length[3] = 10;
length[4] = 15;
var width = new Array();
width[0] = 10;
width[1] = 20;
width[2] = 3;
width[3] = 8;
width[4] = 12;
var i; var find_area ;
for ( i = 0; i<=4; i++)
{
find_area = rectangle_area(length[i], width[i]);
document.write(" Area of rectangle ", i+1, " is ", find_area,"<p>");
}
//-->
</script>
</body>
</html>



We have defined a function which will calculate the area of the rectangle. Let us take a look
at the fuction again

                                                                                      25
http://www.referencedesigner.com/tutorials/js/js_22.php



function rectangle_area(length, breadth)
{
var area = length * breadth ;
return area;
}

rectangle_area is the name of the function. The length and breadth are the arguments of the
function. The following line calculates the area.

var area = length * breadth ;

And the calculated value is returned by the function in the following line

return area;

The function rectangle_area is called as follows

find_area = rectangle_area(length[i], breadth[i]);

Note that the value returned by the function is assigned to the variable find_area.

You can try this example online at the link below, which will open in a new window.

Javascript function - Example

Functions are very useful when the same task need to be done again and again. It can also be
used to enhance the "modularity" of the code. So a long script can be broken into small peices
and each peice is called where required. The increase the understanding of the code.

When not to Use Functions


Functions has slight overhead in loading in execution. In most cases the gain because of the
smaller size of the code as a result of use of functions outweight the losses due to the
overhead. But there may be instances where it may be otherwise and you may not like to use
functiuons.

Javascript Break and Continue statements

The break break and continue are used inside the for and/or while loop to alter the normal
flow of sequence of the loop.

Break statements

The break statement will break the loop. If there are any statements beyond the loop, it will
continue executing the code that follows after the loop.

Break Statement Example
                                                                                        26
http://www.referencedesigner.com/tutorials/js/js_22.php



<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example While loop
********************************************************
*/
var i=0;
while (i<=10)
{
if (i==3)
{
break;
}
square_i = i*i ;
document.write("The square of " +i +" is " +square_i );
document.write("<br />");
i=i+1;
}
//-->
</script>
</body>
</html>



The example defines the while loop that starts with i=0. The loop will continue to run by
incrementing i. When i becomes 3 the loop will break. It will therefore produce the result as
follows.


The square of 0 is 0
The square of 1 is 1
The square of 2 is 4


Continue statements

The continue command will break the current loop and continue with the next value.

Continue Statement Example


<html>
<body>
<script type="text/javascript">

                                                                                       27
http://www.referencedesigner.com/tutorials/js/js_22.php


<!--
/*
********************************************************
Example Continue statement
********************************************************
*/
var i=0;
while (i<=10)
{
if (i==3)
{
i = i +2; continue;
}
square_i = i*i ;
document.write("The square of " +i +" is " +square_i );
document.write("<br />");
i=i+1;
}
//-->
</script>
</body>
</html>



The example defines the while loop that starts with i=0. The loop will continue to run by
incrementing i. When i becomes 3 the loop will not execute. We also note that we assigned i
= i + 2. So the loop continues to run after assigning the value of i to 5. It will therefore
produce the result as follows.


The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100


Javascrip for ..in statements

The javascript for ..in and continue used to loop through the elements of an array. It is also
used to loop through the elements of the object. We will learn it with arrays now. Later on we
will have opportunity to use it with objects when we learn that

for .. in Syntax

                                                                                       28
http://www.referencedesigner.com/tutorials/js/js_22.php


for (variable in object)
{
code to be executed
}
The code in the body of the for ... in loop is executed once for each property. The variable
argument can be a named variable, an array element, or a property of the object.

Example


<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example for ..in
********************************************************
*/
var x;
var uscities = new Array();
uscities[0] = "Boston";
uscities[1] = "Chicago";
uscities[2] = "Austin";
for (x in uscities)
{
document.write(uscities[x] + "<br />");
}
//-->
</script>
</body>
</html>



The example will loop through all values of the array uscities. It will therefore produce the
result as follows.



Page Next Page


Boston
Chicago
Austin


Javascript Events

                                                                                         29
http://www.referencedesigner.com/tutorials/js/js_22.php


Events are actions that can be detected by JavaScript. For example - a mouse clicking, a
mouse hovering on a text. Based upon the detection of the events we can take some actions.

There is a long list of the events recognised by Javascript. We will cover some basic
javascript events and examples in this chapter.

onload event


The onload events is triggered when the user enters the page.

Example


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example onload event
********************************************************
*/
function alertmessage()
{
alert("Welcome to Javascript Tutorial");
}
//-->
</script>
</head>
<body>
</body onload="alertmessage()" >
</html>



Note the following structure

<body onload="alertmessage()" >

As soon as the body section starts the onload event is triggerred. The event transfers the
control to alertmessage. The alertmessage pops up an alert box.
An onload event is usually used to record the ip address, set cookies, check explorer and do
first time settings.

OnMouseOver event




                                                                                        30
http://www.referencedesigner.com/tutorials/js/js_22.php



< The onload events is triggered when the user hovers the mouse over an object. They are
often used to create animated buttons.

Example


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example OnMouseOver event
********************************************************
*/

//-->
</script>
<body>
<img src="beautifulgirl.jpg" width="100" onmouseover="alert('Dont touch beautiful
girl');return false">
</body >
</html>



Note the following structure
<img src="beautifulgirl.jpg" width="100" onmouseover="alert('Dont touch beautiful
girl');return false">

As soon as the mouse hovers over the image beautifulgirl.jpg OnMouseOver event is
triggerred. The event in turn calls a alert box and an alert message box pops up.box.

Javascript Objects - Introduction


An object in Javascript comprises of two things

1. A collection of properties (variables) and 2. Methods (functions) - all classed under a
single name.

Let us imagine that there is an object named circle. The object circle possesses three
properties: the x coordinate of its center, the y coordinate of its center and its radius.The
circle possesses some methods: CalculateArea , CalculateCircumference, MoveOrigin.

In JavaScript the obejects come under two broad categories - First you may create your own
objects for storing data and define and use the methods on it. Secondly, there are many "built-

                                                                                           31
http://www.referencedesigner.com/tutorials/js/js_22.php


in" objects which allow you to work with, manipulate, and access the Web page and Web
browser. These are known as the "Document Object Model".


Properties


Let us take a look at the following example that defines an object circle and three of its
properties - xcoordinates, ycoordinates , radius. It just prints out the radius of the circle

Example - A circle object with properties


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example Circle Object
********************************************************
*/
Circle=new Object();
Circle.xcoordinate=10;
Circle.ycoordinate=15;
Circle.radius=20;
document.write("The radius of the circle is " + Circle.radius );
//-->
</script>
</head>
<body>
</html>


You may try the above example online at the link below ( opens in a new window )

Javascript Circle Object Example

Note the line

Circle=new Object();


This defines a new Object that has the name Circle.

The next thing we do is - to define the properties of the object. Take a look at the table again
that defines three properties of the circle - the xcoordinates, ycoordinates and the radius.



                                                                                            32
http://www.referencedesigner.com/tutorials/js/js_22.php


Circle=new Object();
Circle.xcoordinate=10;
Circle.ycoordinate=15;
Circle.radius=20;

The example above prints the radius of the circle by assessing its radius property. This is one
way of creating the object. What happens if we need to create several instances of circle. In
the next page we will see how to create an object template from which instances of circle can
be created. We will then move on to learn methods.

Javascript Objects - Object Template


In the last page we looked at how to define a single Circle Object. In practice we would like
to define a template for the cicle object. We should be able to create the instances of the
circle as many times as possible.

The example below defines a template of the circle object and creates three instances of it.

Example - A circle object with properties


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example Circle Object Template and instances
********************************************************
*/
/*
********************************************************
Let us define the structure of the object circle.
********************************************************
*/
function circle(x,y,r)
{
this.xcoordinate=x;
this.ycoordinate=y;
this.radius=r;
}
/*
********************************************************
Let us create 3 instances of object circle
********************************************************
*/
circle1 =new circle(0,0,10);

                                                                                        33
http://www.referencedesigner.com/tutorials/js/js_22.php


circle2 =new circle(5,5,20);
circle3 =new circle(10,10,30);

document.write("The radius of the 1st circle is " + circle1.radius + " <p>");
document.write("The radius of the 2nd circle is " + circle2.radius + " <p>" );
document.write("The radius of the 3rd circle is " + circle3.radius + " <p>" );
//-->
</script>
</head>
<body>
</html>



Note the template to create an instance of an object


Circle=new Object();


The template is just a function. Inside the function we assign values to this.propertyName.
The "this" stuff refers the instance of the object at hand. As we create instances of the object,
we values get assigned.

The next thing we do is - to define the properties of the object. Take a look at the table again
that defines three properties of the circle - the xcoordinates, ycoordinates and the radius.

Circle=new Object();
Circle.xcoordinate=10;
Circle.ycoordinate=15;
Circle.radius=20;



The example above prints the radius of the circle by assessing its radius property. This is one
way of creating the object. What happens if we need to create several instances of circle ? In
the next page we will see how to create an object template from which instances of circle can
be created. We will then move on to learn methods.

You can try the example at the link below which will open in a new window

Example - Circle Object Template

In the next page we will create methods on the object circle. We will see how to create area
and circumference of the circle by writing methods.




                                                                                          34
http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript Objects - Mehod


In the last page we looked at how define the template of a circle and create instances of it.
Now we will define a method on the object circle. The method will calculate the area of the
circle. Let us take a look at the example

Example - A circle object with a method to calculate area


<html>
<head>
<script type="text/javascript">
<!--
/*
************************************************************
Example Circle Object - method to calculate area
************************************************************
*/

function circle(x,y,r)
{
this.xcoordinate=x;
this.ycoordinate=y;
this.radius=r;
this.area = calculatearea;
}
function calculatearea() {
return ( 3.14 * this.radius * this.radius );
}
/*
********************************************************
Let us create an instances of object circle
********************************************************
*/
circle1 =new circle(0,0,10);
document.write("The radius of the 1st circle is " + circle1.radius + " <p>");
/*
********************************************************
Let us call the area method
********************************************************
*/
document.write( 'The area of the circle is ' + circle1.area() );
//-->
</script>
</head>
<body>
</html>



                                                                                        35
http://www.referencedesigner.com/tutorials/js/js_22.php




Note the line

this.area = calculatearea;


defines a method on the object cicle. The calculatearea , in turn is a function that we have
defined subsequently.


You can try the example at the link below which will open in a new window

Example - Object Mehods

Let us take a look at another example which moves the origin of the circle by calling another
method move origin.

<html>
<head>
<script type="text/javascript">
<!--
/*
************************************************************
Example Circle Object - method to calculate area
************************************************************
*/

function circle(x,y,r)
{
this.xcoordinate=x;
this.ycoordinate=y;
this.radius=r;
this.moveorigin = move;
}
function move(dx,dy) {
this.xcoordinate = this.xcoordinate +dx; this.ycoordinate = this.ycoordinate +dy;
}
circle1 =new circle(0,0,10);
document.write("The original coordinates are " + circle1.xcoordinate +" ," +
circle1.ycoordinate +" <p>");
/*
********************************************************
Let us call the move method
********************************************************
*/
circle1.moveorigin(5,7);
document.write("The new coordinates are " + circle1.xcoordinate +" ," + circle1.ycoordinate
+" <p>");
//-->

                                                                                         36
http://www.referencedesigner.com/tutorials/js/js_22.php


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



You can try the example at the link below which will open in a new window

Example - Circle move origin

This completes the basic javascript tutorial. You may like to practice more and take up some
advanced topics in javascript tutorial.

Javascript In Built Objects


We have already seen how to create your own class and define methods in the class.
Javascript has a number of inbuilt classes. It has inbuild classes for nearly every comman
tasks that you can think of. You have to be just aware that they exist.

We have already seen that a calss comprises of Properties and Methods defined on the
properties. The Inbuild javascript classes have on a similar Properties and methods defined
upon them.

Let us take a look at the following line we have been using so frequently till now.


doucument.write("Hello");


The document is an object. The write() is a method of the object that takes an string argument
outputs it to screen. Let us take another example - this time an inbuilt string class.

<html>
<head>
<script type="text/javascript">
<!--
/*
************************************************************
Example - Javascript in built string class
************************************************************
*/

var txt="Hello";
document.write("The length of Hello is "+ txt.length + "<p>");

document.write(txt.toUppercase()+ "<p>");
</script>
</head>

                                                                                       37
http://www.referencedesigner.com/tutorials/js/js_22.php


<body>
</html>



The length is a property of the String Object. The toUppercase() is a method of the String
object that converts String to uppercase.

You can try the example at the link below which will open in a new window

Example - Javascript String Object

Javascript Date Objects


The Javascript Date object can be used to access and manipulate the local date and time.

Let us take a look at the following line. It will define a Date object called Datex.


var Datex=new Date()


Initially, the above Datex object will hold the current date and time. We can later on
manipulate the date and time using the methods available with the Date object. We can see it
in the following example which will do nothing but print the current date and time.

<html>
<body>
<script type="text/javascript">
/*
************************************************************
Example - Javascript Date Object
************************************************************
*/

var Datex=new Date();
document.write(Datex);

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



You can try the example at the link below which will open in a new window

Example - Javascript Print Current Date


                                                                                       38
http://www.referencedesigner.com/tutorials/js/js_22.php


Methods on Date Object


There are a number of Methods available in the Date Object. For example take a look at the
following code below which will set the date to 7 days or 1 week from the current date and
time.


var Datex=new Date(); Datex.setDate(xDate.getDate()+7);


The following example will set the date to Dec 10, 2008 using the setFullYear method.

There are a number of Methods available in the Date Object. For example take a look at the
following code below which will set the date to 7 days or 1 week from the current date and
time.


var Datex=new Date(); Datex.setFullYea(2008,12,10);


We will now take a look at an example that will print "Today is Holiday" if Today's day is
either Sat or Sunday and Will print "Today is Work day" otherwise.

<html>
<body>
<script type="text/javascript">
/*
************************************************************
Example - Javascript Date Object
************************************************************
*/

var Datex=new Date();

if (       (Datex.getDay() == 0) ||     (Datex.getDay() == 6) )
  {

       document.write("Today it is Holiday");
   }

else
   {

       document.write("Today it Workday");

       }

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


                                                                                      39
http://www.referencedesigner.com/tutorials/js/js_22.php




To test this program, set your system clock on your to Saturday or Sunday once and some
other day at other time. Note that Datex.getDay() will return 0 for Sunday 1 for Monday and
so on.

You can try this example online here

Example - Find if today is Holiday

Javascript Array


Let assume that we have to calculate the area of 5 rectangles. We can declare 5 variables each
for length and width and then another 5 variables for the area as follows.

Let us take a look at the following line. It will define a Date object called Datex.



var length1,length2,length3,length4,length5;
var breadth1,breadth2, breadth3,breadth4, breadth5;
var area1,area2, area3, area4,area5 ;


While this is pefectly correct way to define the variables in this way, javascript provides the
concept of array.Here is how you do the same thing using arrays.

<html>
<body>
<script type="text/javascript">
/*
************************************************************
Example - Javascript Array Object
************************************************************
*/

var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);

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



The statement var length = new Array(5) says that length is an array of 5 elements. The first
element is accessed usng length[0].

                                                                                         40
http://www.referencedesigner.com/tutorials/js/js_22.php



Let us now go ahead an write a program that will print the areas of 5 rectangles.



<html>
<body>
<script type="text/javascript">
<!--
var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);
var i;

length[0] = 10;
length[1] = 20;
length[2] = 30;
length[3] = 40;
length[4] = 50;

breadth[0] = 5;
breadth[1] = 15;
breadth[2] = 25;
breadth[3] = 35;
breadth[4] = 45;

for (i = 0; i <= 4; i++)
{
area[i] = length[i] * breadth[i];
document.write("Area [",i,"] = ");
document.write(area[i]);
document.write("<br/>");
}
//-->
</script>
</body>
</html>
If we execute the code we get the following output

Area   [0]   =   50
Area   [1]   =   300
Area   [2]   =   750
Area   [3]   =   1400
Area   [4]   =   2250



Arrays help organize the codes.Note that the array index starts from 0 and not 1. You can try
the example online at Example - Javascript Array



                                                                                       41
http://www.referencedesigner.com/tutorials/js/js_22.php


Javascript Array


Let assume that we have to calculate the area of 5 rectangles. We can declare 5 variables each
for length and width and then another 5 variables for the area as follows.

Let us take a look at the following line. It will define a Date object called Datex.



var length1,length2,length3,length4,length5;
var breadth1,breadth2, breadth3,breadth4, breadth5;
var area1,area2, area3, area4,area5 ;


While this is pefectly correct way to define the variables in this way, javascript provides the
concept of array.Here is how you do the same thing using arrays.

<html>
<body>
<script type="text/javascript">
/*
************************************************************
Example - Javascript Array Object
************************************************************
*/

var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);

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



The statement var length = new Array(5) says that length is an array of 5 elements. The first
element is accessed usng length[0].

Let us now go ahead an write a program that will print the areas of 5 rectangles.



<html>
<body>
<script type="text/javascript">
<!--
var length = new Array(5);
var breadth = new Array(5);

                                                                                         42
http://www.referencedesigner.com/tutorials/js/js_22.php


var area = new Array(5);
var i;

length[0] = 10;
length[1] = 20;
length[2] = 30;
length[3] = 40;
length[4] = 50;

breadth[0] = 5;
breadth[1] = 15;
breadth[2] = 25;
breadth[3] = 35;
breadth[4] = 45;

for (i = 0; i <= 4; i++)
{
area[i] = length[i] * breadth[i];
document.write("Area [",i,"] = ");
document.write(area[i]);
document.write("<br/>");
}
//-->
</script>
</body>
</html>
If we execute the code we get the following output

Area   [0]   =   50
Area   [1]   =   300
Area   [2]   =   750
Area   [3]   =   1400
Area   [4]   =   2250



Arrays help organize the codes.Note that the array index starts from 0 and not 1. You can try
the example online at Example - Javascript Array

Javascript Array


Let assume that we have to calculate the area of 5 rectangles. We can declare 5 variables each
for length and width and then another 5 variables for the area as follows.

Let us take a look at the following line. It will define a Date object called Datex.



var length1,length2,length3,length4,length5;
var breadth1,breadth2, breadth3,breadth4, breadth5;
                                                                                       43
http://www.referencedesigner.com/tutorials/js/js_22.php


var area1,area2, area3, area4,area5 ;


While this is pefectly correct way to define the variables in this way, javascript provides the
concept of array.Here is how you do the same thing using arrays.

<html>
<body>
<script type="text/javascript">
/*
************************************************************
Example - Javascript Array Object
************************************************************
*/

var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);

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



The statement var length = new Array(5) says that length is an array of 5 elements. The first
element is accessed usng length[0].

Let us now go ahead an write a program that will print the areas of 5 rectangles.



<html>
<body>
<script type="text/javascript">
<!--
var length = new Array(5);
var breadth = new Array(5);
var area = new Array(5);
var i;

length[0] = 10;
length[1] = 20;
length[2] = 30;
length[3] = 40;
length[4] = 50;

breadth[0] = 5;
breadth[1] = 15;
breadth[2] = 25;

                                                                                         44
http://www.referencedesigner.com/tutorials/js/js_22.php


breadth[3] = 35;
breadth[4] = 45;

for (i = 0; i <= 4; i++)
{
area[i] = length[i] * breadth[i];
document.write("Area [",i,"] = ");
document.write(area[i]);
document.write("<br/>");
}
//-->
</script>
</body>
</html>
If we execute the code we get the following output

Area   [0]   =   50
Area   [1]   =   300
Area   [2]   =   750
Area   [3]   =   1400
Area   [4]   =   2250



Arrays help organize the codes.Note that the array index starts from 0 and not 1. You can try
the example online at Example - Javascript Array




                                                                                       45

								
To top