Monday, February 13, 2017

Thursday, July 17, 2014

UNIT I
JAVASCRIPT
1.1 Introduction
JavaScript is:
  • JavaScript is a lightweight, interpreted programming language
  • Designed for creating network-centric applications
  • Complementary to and integrated with Java
  • Complementary to and integrated with HTML
  • Open and cross-platform
Client-side JavaScript:
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.

Advantages of JavaScript:

The merits of using JavaScript are:
·         Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
·         Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have forgotten to enter something.
·         Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
·         Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

Limitations with JavaScript:

We can not treat JavaScript as a full fledged programming language. It lacks the following important features:
·         Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
·         JavaScript can not be used for Networking applications because there is no such support available.
·         JavaScript doesn't have any multithreading or multiprocess capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.

 

JavaScript Syntax

A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
So simple syntax of your JavaScript will be as follows
<script ...>
  JavaScript code
</script>
The script tag takes two important attributes:
  • language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
  • type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".

<script language="javascript" type="text/javascript">
JavaScript code
</script>

Example:
               <html>
               <body>
               <script language="javascript" type="text/javascript">
               <!--
               document.write("Hello World!")
               //-->
               </script>  </body>
    </html>
Whitespace and Line Breaks:
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

Semicolons are Optional:

Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java.
<script language="javascript" type="text/javascript">
<!--
  var1 = 10
  var2 = 20
//-->
</script>
But when formatted in a single line as follows, the semicolons are required:
<script language="javascript" type="text/javascript">
<!--
  var1 = 10; var2 = 20;
//-->
</script>
Case Sensitivity:
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
So identifiers TimeTIme and TIME will have different meanings in JavaScript.

Comments in JavaScript:

JavaScript supports both C-style and C++-style comments, Thus:
·         Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
·         Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
·         JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.
·         The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

Example:

<script language="javascript" type="text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
 * This is a multiline comment in JavaScript
 * It is very similar to comments in C Programming
 */
//-->
</script>
JAVA Enabling
JavaScript in Internet Explorer:
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer:
  1. Follow Tools-> Internet Options from the menu
  2. Select Security tab from the dialog box
  3. Click the Custom Level button
  4. Scroll down till you find Scripting option
  5. Select Enable radio button under Active scripting
  6. Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.
JavaScript in Firefox:
Here are simple steps to turn on or turn off JavaScript in your Firefox:
  1. Follow Tools-> Options
from the menu
  1. Select Content option from the dialog box
  2. Select Enable JavaScript checkbox
  3. Finally click OK and come out
To disable JavaScript support in your Firefox, you should not select Enable JavaScript checkbox.
JavaScript in Opera:
Here are simple steps to turn on or turn off JavaScript in your Opera:
  1. Follow Tools-> Preferences
from the menu
  1. Select Advanced option from the dialog box
  2. Select Content from the listed items
  3. Select Enable JavaScript checkbox
  4. Finally click OK and come out
To disable JavaScript support in your Opera, you should not select Enable JavaScript checkbox.
Warning for Non-JavaScript Browsers:
If you have to do something important using JavaScript then you can display a warning message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
   document.write("Hello World!")
//-->
</script>
<noscript>
  Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if user's browser does not support JavaScript or JavaScript is not enabled then message from </noscript> will be displayed on the screen.

JavaScript Placement in HTML File

There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most preferred ways to include JavaScript in your HTML file.
·         Script in <head>...</head> section.
·         Script in <body>...</body> section.
·         Script in <body>...</body> and <head>...</head> sections.
·         Script in and external file and then include in <head>...</head> section.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

JavaScript in <body>...</body> section:

If you need a script to run as the page loads so that the script generates content in the page, the script goes in the <body> portion of the document. In this case you would not have any function defined using JavaScript:
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This will produce following result:
Advertisements
 
Hello World
This is web page body

JavaScript in <body> and <head> sections:

You can put your JavaScript code in <head> and <body> section altogether as follows:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result:
Advertisements
 
Hello World

JavaScript in External File :

You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute:
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write your all JavaScript source code in a simple text file with extension ".js" and then include that file as shown above.
For example, you can keep following content in filename.js file and then you can use sayHellofunction in your HTML file after including filename.js file:
function sayHello() {
   alert("Hello World")
}

1.2 JavaScript Variables and DataTypes

1.2.1 JavaScript DataTypes:
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types:
  • Numbers eg. 123, 120.50 etc.
  • Strings of text e.g. "This text string" etc.
  • Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.
In addition to these primitive data types, JavaScript supports a composite data type known asobject. We will see an object detail in a separate chapter.
1.2.2 JavaScript Variables:
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows:
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. For another variable you can assign a value the time of initialization as follows:
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type.
JavaScript Variable Scope:
JavaScript variable will have only two scopes.
  • Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.
  • Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Following example explains it:
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
   var myVar = "local";  // Declare a local variable
   document.write(myVar);
}
//-->
</script>
This produces the following result:
Local
JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in mind.
  • You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but_123test is a valid one.
  • JavaScript variable names are case sensitive. For example, Name and name are two different variables.
JavaScript Reserved Words:
The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

1.3 JavaScript Operators

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. JavaScript language supports following type of operators.
·         Arithmetic Operators
·         Comparision Operators
·         Logical (or Relational) Operators
·         Assignment Operators
·         Conditional (or ternary) Operators

The Arithmatic Operators:

There are following arithmatic operators supported by JavaScript language:
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by denumerator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9

The Comparison Operators:

There are following comparison operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> 
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< 
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.

 

The Logical Operators:

There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:               
Operator
Description
Example
&&
Called Logical AND operator. If both the operands are non zero then then condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false.

The Bitwise Operators:

There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
Operator
Description
Example
&
Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments.
(A & B) is 2 .
|
Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments.
(A | B) is 3.
^
Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
(A ^ B) is 1.
~
Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand.
(~B) is -4 .
<< 
Called Bitwise Shift Left Operator. It moves all bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.
(A << 1) is 4.
>> 
Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is equivalent to integer division by 4, and so on.
(A >> 1) is 1.
>>> 
Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero,
(A >>> 1) is 1.

The Assignment Operators:

There are following assignment operators supported by JavaScript language:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assigne value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A

The Conditional Operator (? :)

There is an oprator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:
Operator
Description
Example
? :
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y

The typeof Operator

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
Here is the list of return values for the typeof Operator :
Type
String Returned by typeof
Number
"number"
String
"string"
Boolean
"boolean"
Object
"object"
Function
"function"
Undefined
"undefined"
Null
"object"

1.4 Conditional Statements

JavaScript if...else Statements

JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain if..else statement.
JavaScript supports following forms of if..else statement:
·         if statement
·         if...else statement
·         if...else if... statement.

if statement:

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}
Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed. Most of the times you will use comparison operators while making decisions.

Example:

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
This will produce following result:
Qualifies for driving

if...else statement:

The if...else statement is the next form of control statement that allows JavaScript to execute statements in more controlled way.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}else{
   Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) in theif block, are executed. If expression is false then given statement(s) in the else block, are executed.

Example:

<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}else{
   document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
This will produce following result:
Does not qualify for driving

if...else if... statement:

The if...else if... statement is the one level advance form of control statement that allows JavaScript to make correct decision out of several conditions.

Syntax:                      

if (expression 1){
   Statement(s) to be executed if expression 1 is true
}else if (expression 2){
   Statement(s) to be executed if expression 2 is true
}else if (expression 3){
   Statement(s) to be executed if expression 3 is true
}else{
   Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if non of the condition is true then else block is executed.

Example:

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
   document.write("<b>History Book</b>");
}else if( book == "maths" ){
   document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
   document.write("<b>Economics Book</b>");
}else{
  document.write("<b>Unknown Book</b>");
}
//-->
</script>
This will produce following result:
Maths Book

 

JavaScript Switch Case

Syntax:

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression.
switch (expression)
{
  case condition 1: statement(s)
                    break;
  case condition 2: statement(s)
                    break;
   ...
  case condition n: statement(s)
                    break;
  default: statement(s)
}

Example:

Following example illustrates a basic while loop:
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
            break;
  case 'B': document.write("Pretty good<br />");
            break;
  case 'C': document.write("Passed<br />");
            break;
  case 'D': document.write("Not so good<br />");
            break;
  case 'F': document.write("Failed<br />");
            break;
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
This will produce following result:
Entering switch block
Good job
Exiting switch block

Example:

Consider a case if you do not use break statement:
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
  case 'B': document.write("Pretty good<br />");
  case 'C': document.write("Passed<br />");
  case 'D': document.write("Not so good<br />");
  case 'F': document.write("Failed<br />");
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
This will produce following result:
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block

1.4.2 JavaScript while Loops

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.

Syntax:

while (expression){
   Statement(s) to be executed if expression is true
}
The purpose of a while loop is to execute a statement or code block repeatedly as long asexpression is true. Once expression becomes false, the loop will be exited.

Example:

Following example illustrates a basic while loop:
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
  document.write("Current Count : " + count + "<br />");
  count++;
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

The do...while Loop:

The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax:

do{
   Statement(s) to be executed;
} while (expression);

Example:

Let us write above example in terms of do...while loop.
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Loop stopped! 

1.4.3 JavaScript for Loops

The for Loop

The for loop is the most compact form of looping and includes the following three important parts:
·         The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
·         The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
·         The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by a semicolon.

Syntax:

for (initialization; test condition; iteration statement){
     Statement(s) to be executed if test condition is true
}

Example:

Following example illustrates a basic for loop:
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
  document.write("Current Count : " + count );
  document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result which is similar to while loop:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

JavaScript for...in loop

Syntax:

for (variablename in object){
  statement or block to execute
}
In each iteration one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.


1.5. Dialog Boxes
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.

Alert Dialog Box:

An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:
<head>
<script type="text/javascript">
<!--
   alert("Warning Message");
//-->
</script>
</head>
Alert box gives only one button "OK" to select and proceed.

Confirmation Dialog Box:

A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.
If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:
<head>
<script type="text/javascript">
<!--
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
                 return true;
   }else{
      alert("User does not want to continue!");
                 return false;
   }
//-->
</script>
</head>

Prompt Dialog Box:

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you want to display in the text box (ii) A default string to display in the text box.
This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.
You can use prompt dialog box as follows:
<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>
1.6 Arrays
The Array object let's you store multiple values in a single variable.
Syntax:
Creating a Array object:
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows:
var fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows:
  • fruits[0] is the first element
  • fruits[1] is the second element
  • fruits[2] is the third element

Example : Array with sort Char
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.sort());
</script></body>
</html>
Example : Array with sort No
<html>
<body>
<script type="text/javascript">
function sortNumber(a, b)
{
return b - a;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
</script></body>
</html>
This will produce the Result as : 100,40,25,10,5,1
Multi Dimensional Array
JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops. 
The following code example illustrates the array-of-arrays technique. First, this code creates an array f. Then, in the outer for loop, each element of f is itself initialized as new Array(); thus f becomes an array of arrays. In the inner for loop, all elements f[i][j] in each newly created "inner" array are set to zero.
var iMax = 20;
var jMax = 10;
var f = new Array();
 
for (i=0;i<iMax;i++) {
 f[i]=new Array();
 for (j=0;j<jMax;j++) {
  f[i][j]=0;
 }
}

1.7 JavaScript Functions

Function Definition:

Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
  statements
}
//-->
</script>

Example:

A simple function that takes no parameters called sayHello is defined here:
<script type="text/javascript">
<!--
function sayHello()
{
   alert("Hello there");
}
//-->
</script>

Calling a Function:

To invoke a function somewhere later in the script, you would simple need to write the name of that function as follows:
<script type="text/javascript">
<!--
sayHello();
//-->
</script>

Function Parameters:

A function can take multiple parameters separated by comma.

Example:

Let us do a bit modification in our sayHello function. This time it will take two parameters:
<script type="text/javascript">
<!--
function sayHello(name, age)
{
   alert( name + " is " + age + " years old.");
}
//-->
</script>
Now we can call this function as follows:
<script type="text/javascript">
<!--
sayHello('Zara', 7 );
//-->
</script>

 

 

The return Statement:

A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

Example:

This function takes two parameters and concatenates them and return resultant in the calling program:
<script type="text/javascript">
<!--
function concatenate(first, last)
{
   var full;
 
   full = first + last;
   return  full;
}
//-->
</script>
Now we can call this function as follows:
<script type="text/javascript">
<!--
   var result;
   result = concatenate('Zara', 'Ali');
   alert(result );
//-->
</script>

JavaScript Nested Functions

Example:

Following is the example where we have nested two functions. This may be a bit confusing but it works perfectly fine:
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
   function square(x) { return x*x; }
   
   return Math.sqrt(square(a) + square(b));
}
//-->
</script>
Now you can call this function in usual way as follows:
<script type="text/javascript">
<!--
hypotenuse(1, 2);  // This will produce 2.2360
//-->
</script>
1.8 Built-in objects
 These built-in objects are available through both the client-side JavaScript and through LiveWire (Netscape's server-side application).
The three built-in objects are: the String object, the Math object, and the Date object. Each of these provides great functionality, and together they give JavaScript its power as a scripting language.
The String Object
The String object is used to manipulate a stored piece of text.
String objects are created with new String().
Syntax
var txt = new String(string);
String Object Methods
Method
Description
Returns the character at the specified index
Returns the Unicode of the character at the specified index
Joins two or more strings, and returns a copy of the joined strings
Converts Unicode values to characters
Returns the position of the first found occurrence of a specified value in a string
Returns the position of the last found occurrence of a specified value in a string
Searches for a match between a regular expression and a string, and returns the matches
Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
Searches for a match between a regular expression and a string, and returns the position of the match
Extracts a part of a string and returns a new string
Splits a string into an array of substrings
Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
Extracts the characters from a string, between two specified indices
Converts a string to lowercase letters
Converts a string to uppercase letters
Returns the primitive value of a String object
Example:
<html>
<body>
<script type="text/javascript">
var str="Hello world!";
document.write("First character: " + str.charAt(0) + "<br />");
document.write("Unicode of first character: " + str.charCodeAt(0) + "<br />");
document.write(str.indexOf("Hello") + "<br />");
document.write(str.toLowerCase()+"<br />");
document.write(str.toUpperCase()+"<br />");
document.write(str.valueOf()+"<br />")
var str1="Hello ";
var str2="Dharma!";
var str3=" Have a nice day!";
document.write(str1.concat(str2,str3)+ "<br />");
document.write(String.fromCharCode(72,69,76,76,79)+ "<br />");
document.write(str.lastIndexOf("Hello") + "<br />");
var str1="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
document.write(str1.match(patt1)+ "<br />");
document.write(str.replace("Microsoft", "W3Schools"));
document.write(str.search("W3SCHOOLS"));
document.write(str.substr(3)+"<br />");
document.write(str.substr(3,4));
</script>
</body>
</html>
Date Object
The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Method
Description
Returns the day of the month (from 1-31)
Returns the day of the week (from 0-6)
Returns the year (four digits)
Returns the hour (from 0-23)
Returns the milliseconds (from 0-999)
Returns the minutes (from 0-59)
Returns the month (from 0-11)
Returns the seconds (from 0-59)
Returns the number of milliseconds since midnight Jan 1, 1970
Returns the time difference between GMT and local time, in minutes
Returns the day of the month, according to universal time (from 1-31)
Returns the day of the week, according to universal time (from 0-6)
Returns the year, according to universal time (four digits)
Returns the hour, according to universal time (from 0-23)
Example
<html>
<body>
<script type="text/javascript">
var d=new Date()
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() +1)
document.write(".")
document.write(d.getFullYear())
document.write(".")
document.write(d.getHours())
</script>
</body>
</html>

Math Object
The Math object allows you to perform mathematical tasks.
Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without creating it.
Syntax
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
Property
Description
Returns PI (approx. 3.14159)
Returns the square root of 1/2 (approx. 0.707)
Returns the square root of 2 (approx. 1.414)
Returns the absolute value of x
Returns the arccosine of x, in radians
Returns the arcsine of x, in radians
Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
Returns the arctangent of the quotient of its arguments
Returns x, rounded upwards to the nearest integer
Returns the cosine of x (x is in radians)
Returns the value of Ex
Returns x, rounded downwards to the nearest integer
Returns the natural logarithm (base E) of x
Returns the number with the highest value
Returns the number with the lowest value
Returns the value of x to the power of y
Returns a random number between 0 and 1
Rounds x to the nearest integer
Returns the sine of x (x is in radians)
Returns the square root of x
Returns the tangent of an angle
Example
<html>
<body>
<script type="text/javascript">
document.write("abs"+Math.abs(7.25) + "<br />");
document.write("acos"+Math.acos(0.64) + "<br />")
document.write("asin"+Math.asin(0.64) + "<br />")
document.write("atan2"+Math.atan2(8,4)+ "<br />");
document.write("ceil"+Math.ceil(0.60) + "<br />");
document.write("cos"+Math.cos(3) + "<br />");
document.write("floor"+Math.floor(0.60) + "<br />")
document.write("log"+Math.log(1) + "<br />");
document.write("max"+Math.max(-5,10) + "<br />");
document.write("pow"+Math.pow(0,0) + "<br />");
document.write("rount"+Math.round(0.60) + "<br />");
document.write("random"+Math.random() + "<br />");
document.write("sin"+Math.sin(3) + "<br />");
document.write("sqrt"+Math.sqrt(9) + "<br />");
</script>
</body>
</html>
1.9 Array Objects

Array Properties

Here is a list of each property and their description.
Property
Description
Returns a reference to the array function that created the object.
Index
The property represents the zero-based index of the match in the string
Input
This property is only present in arrays created by regular expression matches.
Reflects the number of elements in an array.
The prototype property allows you to add properties and methods to an object.

Array Methods

Here is a list of each method and its description.

Method
Description
Returns a new array comprised of this array joined with other array(s) and/or value(s).
Returns true if every element in this array satisfies the provided testing function.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Calls a function for each element in the array.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Joins all elements of an array into a string.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Creates a new array with the results of calling a provided function on every element in this array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array and returns the new length of the array.
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
Removes the first element from an array and returns that element.
Extracts a section of an array and returns a new array.
Returns true if at least one element in this array satisfies the provided testing function.
Represents the source code of an object
Sorts the elements of an array.
Adds and/or removes elements from an array.
Returns a string representing the array and its elements.
Adds one or more elements to the front of an array and returns the new length of the array.
1.9. User Defined Object
All user-defined objects and built-in objects are descendants of an object called Object. .
The new Operator:
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
Example:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "C++"; // Assign properties to the object
book.author = "Balagurusami";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
JavaScript document object model
The DOM (Document Object Model) gives you generic access to most elements, their styles and attributes in a document.
Each HTML document loaded into a browser window becomes a Document object.
The Document object provides access to all HTML elements in a page, from within a script.
 The Document object is also part of the Window object, and can be accessed through the window.document property.       
Collection
Description
Returns an array of all the anchors in the document
Returns an array of all the forms in the document
Returns an array of all the images in the document
Returns an array of all the links in the document
Anchors
The anchors collection returns an array of all the anchors in the current document.
Syntax
document.anchors[].property
Example
<html>
<body>
<a name=" java ">java</a><br />
<a name="c++">C++</a><br />
<script type="text/javascript">
document.write(document.anchors.length);</script></p>
</body>
</html>
 forms
The forms collection returns an array of all the forms in the current document
Syntax
document.forms[].property
Example
<html>
<body>
<form name="Form1"></form>
<form name="Form2"></form>
<p>Number of forms:
<script type="text/javascript">
document.write(document.forms.length);
</script></p>
</body>
</html>
images
The images collection returns an array of all the images in the current document.
Syntax
document.images[].property
Example:
<html>
<body>
<img border="0" src="a.jpg" width="150" height="113" />
<img border="0" src="b.jpg" width="152" height="128" />
<p>Number of images:
<script type="text/javascript">
document.write(document.images.length);
</script></p></body> </html>
Links
The links collection returns an array of all the links in the current document.
 The links collection counts
<a href=""> tags and <area> tags.
Syntax
document.links[].property
Example
<html>
<body>
<a href="images.html">Images</a>
<p>Number of areas/links:
<script type="text/javascript">
document.write(document.links.length);
</script>
</p>
</body>
</html>
Window object
The JavaScript Window Object is the highest level JavaScript object which corresponds to the web browser window.
Using JavaScript, we can manipulate windows in a variety of ways, such as open one, close it, reload its page, change the attributes of the new window etc.
Open method
The open() method opens a new browser window.
Syntax
window.open(URL,name,specs)
URL -pecifies the URL of the page to open
name -Specifies the target attribute or the name of the window.
specs -A comma-separated list of items.
Reload window
To reload a window, use this method:
window.location.reload()
Close Window
The closed property returns a Boolean value indicating whether a window has been closed or not.
Syntax
window.close()
Example: Window object
<html>
<head>
<script type="text/javascript">
function openWin()
{
myWindow=window.open("","","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin()
{
myWindow.close();
}
function Relo()
{
myWindow.location.reload()
}
</script>
</head>
<body>
<input type="button" value="Open 'myWindow'" onclick="openWin()" />
<input type="button" value="Close 'myWindow'" onclick="closeWin()" />
<input type="button" value="Reload" onclick="Relo()" />
</body>
</html>
Other window objects
print()Prints the content of the current window
resizeBy()Resizes the window by the specified pixels
moveBy()Moves a window relative to its current position
moveTo()Moves a window to the specified position
Navigator Object
The navigator object contains information about the browser.
Property
Description
Returns the code name of the browser
Returns the name of the browser
Returns the version information of the browser
Determines whether cookies are enabled in the browser
Returns for which platform the browser is compiled
Returns the user-agent header sent by the browser to the server
The Navigator object is designed to contain information about the version of Netscape Navigator which is being used. However, it can also be used with Internet Explorer. All of its properties, which are read-only, contain information about different aspects of the browser.
Navigator Syntax
navigator.appCodeName
navigator.appName
navigator.appVersion
navigator.cookieEnabled
navigator.platform
navigator.userAgent
Example
<html>
<body>
<script type="text/javascript">
document.write("Browser CodeName: " + navigator.appCodeName);
document.write("<br /><br />");
document.write("Browser Name: " + navigator.appName);
document.write("<br /><br />");
document.write("Browser Version: " + navigator.appVersion);
document.write("<br /><br />");
document.write("Cookies Enabled: " + navigator.cookieEnabled);
document.write("<br /><br />");
document.write("Platform: " + navigator.platform);
document.write("<br /><br />");
document.write("User-agent header: " + navigator.userAgent);
</script></body>
</html>
Screen object
The screen object contains information about the visitor's screen.
There is no public standard that applies to the screen object, but all major browsers support it.
Property
Description
Returns the height of the screen (excluding the Windows Taskbar)
Returns the width of the screen (excluding the Windows Taskbar)
Returns the bit depth of the color palette for displaying images
Returns the total height of the screen
Returns the color resolution (in bits per pixel) of the screen
Returns the total width of the screen
Screen Syntax
screen.availHeight
screen.availWidth
screen.colorDepth
screen.height
screen.pixelDepth
screen.width
Example
<HTML>
<BODY>
<script type="text/javascript">
document.write("Available Height: " + screen.availHeight);
document.write("</br>Available Width: " + screen.availWidth);
document.write("</br>Color Depth: " + screen.colorDepth);
document.write("</br>Total Height: " + screen.height);
document.write("</br>Color resolution: " + screen.pixelDepth);
document.write("</br>Total Width: " + screen.width);
</script>
</BODY>
</HTML>
Form Object
form object is a Browser object of JavaScript used to access an HTML form. If a user wants to access all forms within a document then he can use the forms array.
The form object is actually a property of document object that is uniquely created by the browser for each form present in a document.
The properties and methods associated with form object are used to access the form fields, attributes and controls associated with forms.
Properties of Form Object:
  • action
  • elements[]
  • encoding
  • length
  • method
  • name
  • target
  • button checkbox
  • FileUpload
  • hidden
  • password
  • radio
  • reset
  • select
  • submit
  • text
  • textarea
action:
This property is a read or write property and its value is a string.
elements[]:
It contains all fields and controls present in the form. The user can access any element associated with the form by using the looping concept on the elements array.
encoding:
This property is a read or write property and its value is a string. This property helps determine the way of encoding the form data.
length:
This denotes the length of the elements array associated with the form.
method:
This property is a read or write property and its value is a string. This property helps determine the method by which the form is submitted.
name:
name property of form object denotes the form name.
target:
This property denotes the name of the target window to which form it is to be submitted into.
button:
The button property of form object denotes the button GUI control placed in the form.
checkbox:
checkbox property of form object denotes the checkbox field placed in the form.
select:
select property of form object denotes the selection list object placed in the form.
submit:
submit property of form object denotes the submit button field that is placed in the form.
text:
text property of form object denotes the text field placed in the form.
textarea:
textarea property of form object denotes the text area field placed in the form.
Example of form objet
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" >
<br>Gender
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button3" onClick=0>
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button4" onClick=0>
<br>Language know<br>
<INPUT TYPE="checkbox" NAME="check2" Value="Check2">Tamil<BR>
<INPUT TYPE="checkbox" NAME="check3" Value="Check3">English<BR>
</br>
This is Text Area
<TEXTAREA NAME="myarea" COLS="40" ROWS="5">
</TEXTAREA>
</br>
List Items
<SELECT NAME="list" SIZE="1">
<OPTION>This is item 1
<OPTION>This is item 2
</SELECT>
</br>
<FORM>
<INPUT TYPE="file" NAME="elementName">
</FORM>
</FORM>
</BODY>
</HTML>
1.10 EVENTS
JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page.
When the page loads, that is an event. When the user clicks a button, that click, too, is an event. Another example of events are like pressing any key, closing window, resizing window etc.

onclick Event Type:

This is the most frequently used event type which occurs when a user clicks mouse left button. You can put your validation, warning etc against this event type.

Example:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result and when you click Hello button then onclick event will occur which will trigger sayHello() function.
Say Hello

onsubmit event type:

Another most important event type is onsubmit. This event occurs when you try to submit a form. So you can put your form validation against this event type.
Here is simple example showing its usage. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true the form will be submitted otherwise it will not submit the data.

Example:

<html>
<head>
<script type="text/javascript">
<!--
function validation() {
   all validation goes here
   .........
   return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

onmouseover and onmouseout:

These two event types will help you to create nice effects with images or even with text as well. The onmouseover event occurs when you bring your mouse over any element and theonmouseout occurs when you take your mouse out from that element.

Example:

Following example shows how a division reacts when we bring our mouse in that division:
<html>
<head>
<script type="text/javascript">
<!--
function over() {
   alert("Mouse Over");
}
function out() {
   alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
HTML 4 Standard Events
The standard HTML 4 events are listed here for your reference. Here script indicates a Javascript function to be executed agains that event.
Event
Value
Description
onchange
script
Script runs when the element changes
onsubmit
script
Script runs when the form is submitted
Onreset
script
Script runs when the form is reset
onselect
script
Script runs when the element is selected
Onblur
script
Script runs when the element loses focus
onfocus
script
Script runs when the element gets focus
onkeydown
script
Script runs when key is pressed
onkeypress
script
Script runs when key is pressed and released
onkeyup
script
Script runs when key is released
Onclick
script
Script runs when a mouse click
ondblclick
script
Script runs when a mouse double-click
onmousedown
script
Script runs when mouse button is pressed
onmousemove
script
Script runs when mouse pointer moves
onmouseout
script
Script runs when mouse pointer moves out of an element
onmouseover
script
Script runs when mouse pointer moves over an element
Onmouseup
script
Script runs when mouse button is released

1.11 Cookies

Cookies are small amounts of data stored by the web browser. They allow you to store particular information about a user and retrieve it every time they visit your pages.Each user has their own unique set of cookies.
syntax
set.cookie = "name=value; expires=date; path=path; domain=domain; secure";
name=value This sets both the cookie's name and its value.
Ex : username=AAAA
expires=date This optional value sets the date that the cookie will expire on. The date should be in the format returned by the the toGMTString()   method of the Date object – Greenwith Mean Time(DD-MM-YY)
expires=13/06/2003 00:00:00
domain=domain This optional value specifies a domain within which the cookie applies. Only websites in this domain will be able to retrieve the cookie
Ex : domain=google.com
secure : This optional flag indicates that the browser should use SSL when sending the cookie to the server. This flag is rarely used.
 JavaScript escape() function to encode the valuebefore storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
Example
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>

1.12. Timer Events
With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

window.setInterval("javascript function", milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter of setInterval() should be a function.
The second parameter indicates the length of the time-intervals between each execution.

The setTimeout() Method

Syntax

window.setTimeout("javascript function", milliseconds);
The window.setTimeout() method can be written without the window prefix.
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
The first parameter of setTimeout() should be a function.

The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.