8/22/2011
1
Java Script
1
What is JavaScript?
• JavaScript was designed to add interactivity to HTML pages.
• JavaScript is a scripting language.
• A scripting language is a lightweight programming language.
• JavaScript is usually embedded directly into HTML pages.
• JavaScript is an interpreted language (means that scripts execute without preliminary
compilation).
• Everyone can use JavaScript without purchasing a license.
Advantages of JavaScript
1. As Interpreted Language 8. Designed for Programming User Events
2. Embedded within HTML 9. Easy Debugging and Testing
3. Minimal Syntax – Easy to Learn 10. Platform Independence / Architecture
4. Quick Development Neutral
5. Designed for Simple, Small Programs
6. Performance
7. Procedural Capabilities2
8/22/2011
2
As Interpreted Language
JavaScript is an interpreted language, which requires no compilation steps. This provides an easy
development process. The syntax is completely interpreted by the browser just as it interprets
HTML tags.
Embedded within HTML
JavaScript does not require any special or separate editor for programs to be written, edited or
compiled. It can be written in any text editor like notepad, along with appropriate HTML tags,
and saved as filename.html. HTML files with embedded JavaScript commands can then be read
and interpreted by any browser that is JavaScript enabled.
Minimal Syntax – Easy to Learn
By learning just a few commands and simple rules of syntax, complete applications can be built
using JavaScript.
Quick Development
Because JavaScript does not require time-consuming compilations, scripts can be developed in a
short period of time. This is enhanced by the fact that many GUI interface feature, such as alerts,
prompts, confirm boxes, and other GUI elements, are handled by client side JavaScript, the
browser and HTML code.
Designed for Simple, Small Programs
It is well suited to implement simple, small programs. Such programs can be easily written and
executed at an acceptable speed using JavaScript. In addition, they can be easily integrated into a
web page.3
Performance
JavaScript can be written such that the HTML files are fairly compact and quite small. This
minimizes storage requirements on the web server and download time for the client. Additionally,
because JavaScript programs are usually included in the same file as the HTML code for a web
page, they require fewer separate network accesses.
Procedural Capabilities
Every programming language needs to support facilities such as Condition checking, Looping
and Branching. JavaScript provides syntax, which can be used to add such procedural capabilities
to web page coding.
Designed for Programming User Events
JavaScript supports Object / Event based Programming. JavaScript recognizes when a form
‘Button’ is pressed. This event can have suitable JavaScript code attached, which will execute
when the ‘Button Presses’event occurs
JavaScript can be used to implement context sensitive help. Whenever an HTML form’s ‘Mouse’
cursor ‘Mouse Over’ a button or a link on the page a helpful and informative message can be
displayed in the status bar at the bottom of the browser window.
Easy Debugging and Testing
Being an interpreted language, JavaScript script are tested line by line, and the errors are also
listed as they are encountered, i.e. an appropriate error message along with the line number is
listed for every error that is encountered. It is thus easy to locate errors, make changes, and test it
again without the overhead and delay of compiling. 4
8/22/2011
3
Platform Independence / Architecture Neutral
JavaScript is a programming language that is completely independent of the hardware on which it
works. It is a language that is understood by any JavaScript enabled browser. Thus, JavaScript
applications work on any machine that has an appropriate JavaScript enabled browser installed.
This machine can be anywhere on the network.
How to Writing JavaScript into HTML?
JavaScript syntax is embedded into an HTML file. A browser reads HTML files and interprets
HTML tags. Since all JavaScript need to be included as an integral part of an HTML document
when required, the browser needs to be informed that specific sections of HTML code is
JavaScript. The browser will then use its built – in JavaScript engine to interpret this code.
The browser is given this information using the HTML tags <script> . . . </script>. The <script>
tag marks the beginning of a snipped of scripting code. The paired <script> marks the end of the
snippet of scripting code.
Syntax:
<script language = “javascript”>
//Javascript code snippet written here
</script>
(OR)
<script type= “text/javascript”>
//Javascript code snippet written here
</script> 5
Building up JavaScript Syntax
Basic Programming Techniques
JavaScript offers the very same programming capabilities found in most programming languages.
Creating variables, constant, programming constructs, user defined functions and so on.
All these programming techniques can be used in JavaScript embedded in any HTML program.
These are the techniques that make JavaScript an exciting programming language that extends the
functionality of HTML and makes web pages interactive.
The <head>. . .</head> tags make an ideal place to create JavaScript variables and constants and
so on. This is because the head of an HTML document is always processed before the body,
Placing JavaScript memory variables, constants and user defined function. This is important
because any attempt to use a variable before it is defined, result in an error.
Variable are used to store values that can be used in other parts of a program. When naming
variables, it is good programming practice to structure a descriptive name.
Variable names can begin with an uppercase letter, lowercase letter, and underscore character or
dollar sign character. The remaining characters can consist of letters, the underscore character, the
dollar sign character of digits 0 to 9. Variables names are case sensitive.
JavaScript does not allow the data type of the variable to be declared when a variable is created.
The same variable may be used to hold different types of data at different times when the
JavaScript code snippet runs.
6
8/22/2011
4
JavaScript supports four primitives types of values and supports complex types such as arrays
and objects. Primitive types are types that can be assigned a single literal values such as number,
string or boolean value. Literals are fixed values, which literally provide a value in a program.
The Primitive data types that JavaScript supports are:
1. Number
2. Boolean
3. String
1.Number
Consists of integer and floating point numbers and the special NaN value. Integer literals
can be represented in JavaScript in decimal, hexadecimal, and octal form. Floating –
point literals are used to represent numbers that require the use of decimal point, or very
large or very small numbers that must be written using exponential notation. A Floating
– point number must consist of either a number containing a decimal point or an integer
followed by an exponent.
Ex: 33, 12.10, -35.8, 2E3, 0x5F
2. Boolean
Consists of the logical value true and false. JavaScript supports a pure Boolean type that consist
of the two values true and false. Logical operators can be used in Boolean expression. JavaScript
automatically converts the Boolean values true and false into 1 and 0 when they are used in
numerical expression
Data Types and Literal
7
3. String
Consists of string values that are enclosed in single or double quotes. JavaScript provides built –
in support for strings. A string is a sequence of zero ro more characters that are enclosed by
double (“) or single (‘) quotes. If a string begins with a double quote it must end with a double
quote. If a string begins with a single quote it must end with a single quote.
Ex: “Rahul”, ’Sakthi Nagar, Gandhigrammam’
4. Null
Consists of a single values, null, which identifiers a null, empty or nonexistent reference. The null
value is common to all JavaScript types. It is used to set a variable to an initial value that is
different from other valid values. Use of the null value prevents the soft of error that result from
using uninitialized variables, The null values is automatically converted to default values of other
types when used in an expression.
Type Casting
In JavaScript variables are loosely cast, The type of a JavaScript variable is implicitly defined
based on the literal values that are assigned to ti from time to time.
For instance, combining the string literal “Total amount is 1000”. By contrast, adding together the
numeric literal 10.5 and the string “20” result in the floating point integer literal 30.5. This
process is known as type casting
Creating Variables
In order to make working with data types convenient, variables are created, In JavaScript
variables can be created that can hold any type of data.8
8/22/2011
5
In order to use a variable, it is good programming style to declare it. Declaring a variable tells
JavaScript that a variable of a given name exists so that the JavaScript interpreter can understand
references to that variable name throughout the rest of the script.
Although it is possible to declare variables by simply using them, declaring variables helps to
ensure that programs are well organized and help keep track of the scope of the variables.
Variable can be declares using var command.
Syntax:
var <variable name> = value;
Example:
var first_name;
var last_name = “Sakhi”;
var phone = 9864;
Incorporating variables in a Script
<html>
<head>
<script language = “javascript”>
var name = “prompt(“Enter you name”,”Name”);
</script>
</head>
<body>
<script language = “javascript”>
document.write(“<h2>Hello” + name + “</h2>”);
</script>
</body>
</html>9
JavaScript Variable Scope:
The scope of a variable is the region of your program in which it is defined. 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:
10
8/22/2011
6
JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in mind.
1. You should not use any of the JavaScript reserved keyword as variable name.For example, break or boolean variable names are not valid.
2. JavaScript variable names should not start with a numeral (0-9). They must beginwith a letter or the underscore character. For example, 123test is an invalid variablename but _123test is a valid one.
3. JavaScript variable names are case sensitive. For example, Name and name aretwo different variables.
JavaScript Reserved Words:The following are reserved words in JavaScript. They cannot be used as JavaScriptvariables, functions, methods, loop labels, or any object names.
11
JavaScript Operators
What is an operator?
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.
1. Arithmetic Operators
2. Comparison Operators
3. Logical (or Relational) Operators
4. Assignment Operators
5. Conditional (or ternary) Operators
The Arithmetic Operators:
12
8/22/2011
8
The Assignment Operators
Miscellaneous Operator
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:
15
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.
16
8/22/2011
9
CONTROL STRUCTURES
17
JavaScript if...else Statements
While writing a program, there may be a situation when you need to adopt one path out of the
given two paths. So you need to make use of conditional statements that allow your program to
make correct decisions and perform right actions.
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:
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.18
8/22/2011
10
Example
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:
Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) in the if
block, are executed. If expression is false then given statement(s) in the else block, are executed.19
Example
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:
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.20
8/22/2011
11
Example
JavaScript Switch Case
You can use multiple if...else if statements, as in the previous chapter, to perform a multiway
branch. However, this is not always the best solution, especially when all of the branches depend
on the value of a single variable.
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. The interpreter checks each case
against the value of the expression until a match is found. If nothing matches, a default condition
will be used.21
The break statements indicate to the interpreter the end of that particular case. If they were
omitted, the interpreter would continue executing each statement in each of the following cases.
Example
22
8/22/2011
12
Example
Consider a case if you do not use break statement:
23
JavaScript while Loops
While writing a program, there may be a situation when you need to perform some action over
and over again. In such situation you would need to write loop statements to reduce the number
of lines.
JavaScript supports all the necessary loops to help you on all steps of programming.
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.
Syntax:
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.
Example:
Following example illustrates a basic while loop:
24
8/22/2011
13
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:
Note the semicolon used at the end of the do...while loop.
Example
Let us write above example in terms of do...while loop.25
JavaScript for Loops
The for loop is the most compact form of looping and includes the following three important
parts:
1. The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
2. 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.
3. 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.
26
8/22/2011
14
Syntax
Example
27
JavaScript for...in loop
There is one more loop supported by JavaScript. It is called for...in loop. This loop is used to loop
through an object's properties.
Because we have not discussed Objects yet, so you may not feel comfortable with this loop. But
once you will have understanding on JavaScript objects then you will find this loop very useful.
Syntax:
In each iteration one property from object is assigned to variablename and this loop continues till
all the properties of the object are exhausted.
Example:
Here is the following example that prints out the properties of a Web browser's Navigator object:
28
8/22/2011
15
29
JavaScript Loop Control
JavaScript provides you full control to handle your loops and switch statement. There may be a
situation when you need to come out of a loop without reaching at its bottom. There may also be
a situation when you want to skip a part of your code block and want to start next iteration of the
look.
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any loop
respectively.
The break Statement:
The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.
Example:
This example illustrates the use of a break statement with a while loop. Notice how the loop
breaks out early once x reaches 5 and reaches to document.write(..) statement just below to
closing curly brace:
30
8/22/2011
16
The continue Statement:
The continue statement tells the interpreter to immediately start the next iteration of the loop and
skip remaining code block.
When a continue statement is encountered, program flow will move to the loop check expression
immediately and if condition remain true then it start next iteration otherwise control comes out
of the loop.
Example:
This example illustrates the use of a continue statement with a while loop. Notice how the
continue statement is used to skip printing when the index held in variable x reaches 5:31
32
8/22/2011
17
Using Labels to Control the Flow
Starting from JavaScript 1.2, a label can be used with break and continue to control the flow
more precisely.
A label is simply an identifier followed by a colon that is applied to a statement or block of code.
We will see two different examples to understand label with break and continue.
Note: Line breaks are not allowed between the continue or break statement and its label name.
Also, there should not be any other statement in between a label name and associated loop.
Example 1:
33
Example 2
34
8/22/2011
18
JavaScript Functions
A function is a group of reusable code which can be called anywhere in your programme. This
eliminates the need of writing same code again and again. This will help programmers to write
modular code. You can divide your big programme in a number of small and manageable
functions.
Like any other advance programming language, JavaScript also supports all the features
necessary to write modular code using functions.
You must have seen functions like alert() and write() in previous chapters. We are using these
function again and again but they have been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section will explain you how to
write your own functions in JavaScript.35
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:
36
8/22/2011
19
Calling a FunctionTo invoke a function somewhere later in the script, you would simple need to write the name of
that function as follows:
Function ParametersTill now we have seen function without a parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those 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:
Note: We are using + operator to concatenate string and number all together. JavaScript does not
mind in adding numbers into strings.
Now we can call this function as follows:37
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.
For example you can pass two numbers in a function and then you can expect from the function
to return their multiplication in your calling program.
Example:
This function takes two parameters and concatenates them and return resultant in the calling
program:
38
8/22/2011
20
JavaScript Nested FunctionsPrior to JavaScript 1.2, function definition was allowed only in toplevel global code but
JavaScript 1.2 allows function definitions to be nested within other functions as well.
Still there is a restriction that function definitions may not appear within loops or conditionals.
These restrictions on function definitions apply only to function declarations with the function
statement.
Example:
Following is the example where we have nested two functions. This may be a bit confusing but it
works perfectly fine:
39
JavaScript - The Function() Constructor
The function statement is not the only way to define a new function but also, you can define your
function dynamically using Function( ) constructor along with the new operator.
Note: This is the terminology from Object Oriented Programming. You may not feel comfortable
for the first time, which is OK.
Syntax:
Following is the syntax to create a function using Function( ) constructor along
with the new operator.
40
8/22/2011
21
The Function() constructor expects any number of string arguments. The last argument is the
body of the function - it can contain arbitrary JavaScript statements, separated from each other by
semicolons.
Notice that the Function() constructor is not passed any argument that specifies a name for the
function it creates. The unnamed functions created with the Function() constructor are called
anonymous functions.
Example:
Here is an example of creating a function in this way:
41
JavaScript Global Functions
Global Function Description
escape This function takes a string argument and returns a string in which allspaces, punctuation, accent characters and any other character that isnot in the ASCII character set are encoded in a hexadecimal formatthat can be represented on all platforms.
eval This function takes a string argument representing JavaScript code toexecute. The JavaScript interpreter evaluates the code and executes itwhen the eval function is called. This function allows JavaScript codeto be stored as strings and executed dynamically.
isFinite This function takes a numeric argument and returns true if the value ofthe argument is not NaN, Number, POSITIVE_INFINITY or Number,NEGATIVE_INFINITY; otherwise, the function returns false
isNaN This function takes a numeric argument and returns true if the value ofthe argument is not a number; otherwise, it returns false. The functionis commonly used with the return values of parseInt or parseFloat todetermine whether the result is proper numeric value
parseFloat This function takes a string argument and attempts to convert thebeginning of the string into a floating-point value. If the conversion isunsuccessful, the function returns NaN; otherwise, it returns theconverted value returns NaN, and parseFloat returns the value 123.4542
8/22/2011
22
Global Function Description
parseInt This function takes a string argument and attempts to convert thebeginning of the string into an integer value. If the conversion isunsuccessful the function returns NaN; otherswise, it returns theconverted values returns NaN, and parseInt returns the integer value.This function takes and option second argument, from 2 to 36,specifying thre radix (base 2) of the number Base 2 indecates that thefirst arguent string is in binary format, base 8 indecates that the firstargument string is in octal format and base 16 indicates that the firstarguments string is in hexadecimal format.
unescape This function takes a string as its argument and returns a string inwhich all characters previously encoded with escape are decoded.
Example
43
<html>
<head>
<script language="javascript">
function Function_Integer()
{
var x = parseInt(prompt("Enter the X Value"));
var y = parseInt(prompt("Enter the Y Value"));
var z = x + y;
document.write("Addition of the Two Numbers:" + z);
}
</script>
</head>
<body onload="Function_Integer()">
</body>
</html
parseInt() – Global Function
44
8/22/2011
23
<html>
<head>
<script language="javascript">
function Function_Integer()
{
var x = parseFloat(prompt("Enter the X Value"));
var y = parseFloat(prompt("Enter the Y Value"));
var z = x + y;
document.write("Addition of the Two Numbers:" + z);
}
</script>
</head>
<body onload="Function_Integer()">
</body>
</html
parseFloat() – Global Function
45
eval() – Global Function
<html>
<head>
<script language="javascript">
function Function_Integer()
{
var x = parseInt(prompt("Enter the X Value"));
var y = parseInt(prompt("Enter the Y Value"));
var z = parseInt(prompt("Enter the Z Value"));
var z = eval("x + y * z");
document.write("Addition of the Two Numbers:" + z);
}
</script>
</head>
<body onload="Function_Integer()">
</body>
</html46
8/22/2011
24
isNaN() – Global Function
<script type="text/javascript">
document.write(isNaN(123)+ "<br />");
document.write(isNaN(-1.23)+ "<br />");
document.write(isNaN(5-2)+ "<br />");
document.write(isNaN(0/0)+ "<br />");
document.write(isNaN("Hello")+ "<br />");
document.write(isNaN("2005/12/12")+ "<br />");
</script>
The output of the code above will be:
false
False
false
true
true
true 47
isFinite() – Global Function
<script type="text/javascript">
document.write(isFinite(123)+ "<br />");
document.write(isFinite(-1.23)+ "<br />");
document.write(isFinite(5-2)+ "<br />");
document.write(isFinite(0) + "<br />");
document.write(isFinite(0 / 0)+ "<br />");
document.write(isFinite("Hello")+ "<br />");
document.write(isFinite("2005/12/12")+ "<br />");
</script> The output of the code above will be:
true
true
true
true
false
false
false 48
8/22/2011
25
escape() – Global Function
<script type="text/javascript">
document.write(escape("Need tips? Visit Internet!"));
</script> The output of the code above will be:
Need%20tips%3F%20Visit%20W3Schools%21
unescape() – Global Function
<script type="text/javascript">
var str="Need tips? Visit Internet!";
var str_esc=escape(str);
document.write(str_esc + "<br />")
document.write(unescape(str_esc))
</script>
The output of the code above will be:
Need%20tips%3F%20Visit%20Internets%21
Need tips? Visit Internet! 49
Recursive Functions
Recursion refers to a situation, wherein functions call themselves. In other words, there is a call
to a specific function from within the same function. Such functions are known as Recursive
functions
Example:
function factrorial(number)
{
if(number > 1)
{
return number * factorial(number – 1);
}
else
{
return number;
}
}
Note:
Recursive functions are powerful, but can lead to infinite recursions. Infinite recursions occur
when the function is designed in such a way as to call itself without being able to stop
50
8/22/2011
26
Scope Rules in Function
<html>
<head>
<script language="javascript">
var x = 1; //global variables
function start()
{
var x = 5; //variable local to function start
document.writeln("local x in start is " + x);
functionA(); //functionA has local x
functionB(); //functionB uses global variable x
functionA(); //functionA reinitializes local x
functionB(); //global variable x retains its value
document.writeln("<p>Local x in start is " + x + </p>");
}
function functionA()
{
var x = 25; //initialized each time functionA is called
document.writeln(“<p>local x in functionA is “ + x +
“after entering functionA”);
++x;
document.writeln(“<br />local x in function is “ + x +
“before exiting functionsA” + “</p>”);
} 51
function functionB()
{
document.writeln(“ <p>global variable x is “ + x +
“on entering functionsB”);
x *= 10;
document.writeln(“<br />global variable x is “ + x + “
on exiting functionB” + “</p>”);
}
</script>
</head>
<body onload="start()">
</body>
</html>
52
8/22/2011
27
Output
local x in start is 5
local x in functionA is 25 after entering functionA
local x in functionA is 26 before exiting functionA
global variable x is 1 on entering functionB
global variable x is 10 on entering functionB
local x in functionA is 25 after entering functionA
local x in functionA is 26 before exiting functiona
global variable x is 10 on entering functionB
global variable x is 100 on exiting functionB
local x in start in 553
Passing by Value and Passing by Reference – JavaScript Function
Two ways to pass arguments to functions in many programming languages are pass-by-value and
pass-by-references. When an argument is passed to a function by value, a copy of the argument’s
value is made and is passed to the called function. In JavaScript, numbers and Boolean values are
passed to functions by value.
With pass-by-reference, the caller gives the called function direct access to the caller’s data and
allows it to modify the data if it so chooses. This procedure is accomplished by passing to the
called function the actual location in memory where the data resides. Pass-by-reference can
improve performance because it can eliminate the overhead of copying large amounts of data, but
it can weaken security because the called function can access the caller’s data. In JavaScript, all
objects are passed to function by reference.
<html>
<head>
<script language = "javascript">
function MyFunction(a)
{
alert(a);
}
</script>
</head>
<body>
<h1>This program is MyFunction()</h1>
<script language="javascript">
var x = 10;
MyFunction(x);
</script>
</body>
</html>
Pass – by – Value
54
8/22/2011
28
function myobject()
{
this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6
Pass – By - References
55
JavaScript - 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.
Here we will see each dialog box one by one:
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:
56
8/22/2011
29
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:
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.
57
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.
JavaScript Array
Arrays are JavaScript objects that are capable of storing a sequence of values. These values are
stored in indexed locations within the array. The length of an array is the number of element that
an array contains. The individual elements of an array are accessed by using the name of the array
followed by the index values of the array element enclosed in square brackets.
An array must be declared before it is used. An array can be declared using any one of the
following techniques.
arrayName = new Array(Array length)
arrayName = new Array() 58
8/22/2011
30
In the first example the array size is explicitly specified. Hence this array will hold a pre-
determined set values. The second example creates an array of the size 0.
Example:
cust_orders = new Array();
cust_orders[50] = “Lion Pencils”;
cust_order[100] = “Steadler eraser”;
What is meant by Dense Array?
A Dense array is an array that has been created with each of its elements being assigned a specific
values. Dense arrays are used exactly in the same manner arrays. They are declared and
initialized at the same time.
Listing the values of the array elements in the array declaration creates dense arrays.
For example a dense array can be created as:
arrayName = new Array(value0,value1,…..valuen);
For Example:
value = new Array(10,20,30,40,50);
59
<html>
<head>
<script language="javascript">
var value = new Array(5);
for(i=0;i<value.length;i++)
{
value[i] = prompt("Enter the Array Value");
}
for(i=0;i<value.length;i++)
{
document.write("<br>The Array Value is:" + value[i] + "<br>");
}
</script>
</head>
<body>
<h1>This is the Java Scritp Array<h1>
</body>
</html>
Example
60
8/22/2011
31
The JavaScript Array and its length Property
JavaScript arrays are implemented as objects. Objects are named collections of data that have
properties and whose values may be accessed via methods. A property returns a values that
identifies some aspect of the state of an object. Methods are used to read or modify the data
contained in an object’s property.
The length of an array is property of an array. Access to any JavaScript object’s property is done
by using objectname.propertyname.
For Example, to find out the length of the multiTypeArray;
myvar = multiTypeArray.length;
Delete Operator in JavaScript Array
The delete operator is used to delete a property of an object or an element at an array
index.
Example:
delete myArray[5];
Deletes the sixth element of myArray. 61
Array of Array in JavaScriptTwo Dimensional Arrays are storing elements in a structure similar to that of a table.
Defining Array of Arrays in JavaScript:
One of the vital points to note is JavaScript does not support multi-dimensional arrays and
thereby does not support Two Dimensional Array. In order to create a Two Dimensional Array in
JavaScript, the programmer must use the concept of creating the Single Dimensional Array while
employing a small trick in the code.
Two-Dimensional Arrays in JavaScript are constructed by creating an array of arrays. JavaScript
does not directly allow creation of a Two-Dimensional Array. Two-Dimensional Arrays in
JavaScript are constructed when the inner array is created first and then, using this initial array,
the outer array is then populated.
For example defining
var Exforsys=new Array(4)
defines 4 storage area for the array named as Exforsys. That is
A two-dimensional array can be built by defining another array on each of Exforsys[0],
Exforsys[1], Exforsys[2], Exforsys[3]
This is done as follows:62
8/22/2011
32
A two-dimensional array can be built by defining another array on each of Exforsys[0],
Exforsys[1], Exforsys[2], Exforsys[3]
This is done as follows:
var Exforsys=new Array(4);
for (i=0; i <4; i++)
Exforsys[i]=new Array(4);
This gives structure as follows:
This shows a two-dimensional array constructed using the single dimensional concept of arrays in
JavaScript. The next step is adding elements to two-dimensional arrays using JavaScript.
The elements can be added to the two-dimensional array in JavaScript using double brackets. For
example, to store elements in the above two dimensional array named Exforsys we write:
63
Exforsys[0][0] = "Example1"
Exforsys[0][1] = "Example2"
Exforsys[0][2] = "Example3"
Exforsys[0][3] = "Example4"
Exforsys[1][0] = "Example5"
Exforsys[1][1] = "Example6"
Exforsys[1][2] = "Example7"
Exforsys[1][3] = "Example8"
Exforsys[2][0] = "Example9"
Exforsys[2][1] = "Example10"
Exforsys[2][2] = "Example11"
Exforsys[2][3] = "Example12"
Exforsys[3][0] = "Example13"
Exforsys[3][1] = "Example14"
Exforsys[3][2] = "Example15"
Exforsys[3][3] = "Example16"
Thus the above two dimensional array named as Exforsys has 4*4 =16 storage spaces.
<html>
<head>
<script language = "javascript">
function ArrayofArray()
{
Exforsys = new Array[4];
Example of Array of Array
64
8/22/2011
33
Exforsys[0] = new Array[4];
Exforsys[1] = new Array[4];
Exforsys[2] = new Array[4];
Exforsys[3] = new Array[4];
for(i=0; i < Exforsys.length; i++)
{
for(x=0; x < Exforsys[i].length; x++)
{
Exforsys[i][x] = parseInt(prompt("Enter the Array
Element"));
}
}
for(i=0; i < Exforsys.length; i++)
{
for(x=0; x < Exforsys[i].length; x++)
{
document.write(Exforsys[i][x]);
document.write("<br>");
}
}
}
</script></head>
<body onload="ArrayofArray()“> <h1>This is the Array of Array in JavaScript</h1>
</body></html>65
Passing Arrays to Functions
To pass an array argument to a function, specify the name of the array without brackets. For
example, if array hourlyTemperatures has been declared as
var hourlyTemperatures = new Array(18);
Then the function call
modifyArray(hourlyTemperatures);
<html>
<head>
<script language="javascript">
function start()
{
var a = new Array(1,2,3,4,5);
document.writeln("<h2>Effects of passing entire
array by reference</h2>");
outputArray("The values of the original array are
",a);
modifyArray(a); 66
8/22/2011
34
outputArray("The values of the modified array are:
",a);
document.writeln("<h2>Effects of passing array
element by value</h2> + "a[3] before
modifyElement: " + a[3]);
modifyElement(a[3]);
document.writeln("<br />a[3] after modifyElement: "
+ a[3]);
}
function outputArray(header,theArray)
{
document.writeln(header + theArray.join(" ") + "<br
/>");
}
function modifyArray(theArray)
{
for(var j in theArray)
theArray[j] *= 2;
}
67
function modifyElement(e)
{
e *= 2;
document.writeln("<br />Value in ModifyElement: " +
e);
}
</script>
</head>
<body onload = "start()">
</body>
</html>
Array Properties
Property Description
constructor Returns a reference to the array function that created the object.
length Reflects the number of elements in an array.
68
8/22/2011
35
Array Methods
Method Description
concat() Returns a new array comprised of this array joined with other array(s) and/or value(s).
join() Joins all elements of an array into a string.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the array.
reverse()Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
toSource() Represents the source code of an object
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift()Adds one or more elements to the front of an array and returns the new length of the
array.
69
70
THE END