Professional Documents
Culture Documents
CHP 2
CHP 2
2.1 Array- declaring an array, initializing an array, defining an array element, looping an array, adding
an array element, sorting an array ,combining an array element, objects as associative arrays.
Array:
It is a collection of more than one element value of similar data type. Array is used store multiple values
required for processing data. An array has user defined name long with index value to identify each element
stores in an array. A combination of array name and an index value is same as having a single variable.
Individual element can be stored using index position along with array name as shown below:
products[0]=’book’;
Looping an array:
An array element can be accessed using an index variable. By using loop, we can traverse through all the
elements of an array by incrementing index variable by one, after every visit to an element.
In looping, a index variable/counter variable is initially assigned with 0 position. By using for loop or while
loop, each element from an array can be visited with index variable. Initially index variable will point to first
element stored at 0th position. Then index variable is incremented by one to point to next position and so on.
The loop will execute till all elements are visited and index variable points to length value.
1. An array element can be added at the time of array declaration with following syntax:
var array_name=new Array(‘value1’,’value2’, … ,’value n’);
example: var products=new Array(‘book’,’pen’,’pencil’,’eraser’);
2. An array element can be added after the declaration of an array by using index variable to indicate position
inside array. An index variable is initially 0. First element is stored at 0th position and last element is stored at
size-1 position
To access any particular position following syntax is used:
array_name[index position]=’value’;
Example: var products=new Array( );
products[0]=’book’;
products[1]=’pen’;
products[2]=’pencil’;
products[3]=’eraser’;
3. push( ) method: It is used to add a new element at the end of an array. It allocates memory to new element
in an array by incrementing index position by one.
Syntax: array_name.push(“value”);
Example: products.push(“notebook”);
Program: Output:
<html>
<head></head>
<body>
<h3>Adding element to an array</h3>
<script type="text/javascript">
var products=new Array("book","pen","pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i]+"<br>");
}
document.write("<h4>push method</h4>");
products.push("Notebbok");
document.write("After push() method execution Array
elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>
Sorting An array:
Arranging all array elements in alphabetical order for strings and ascending order for numbers.
sort( ) function is used to perform sorting on array elements.
Syntax: array_name.sort( );
Example: products.sort( );
Program: Output:
<html> Sort an array and display elements
<head></head>
pen
<body> scale
<h3>Sort an array and display elements</h3> pencil
<script type="text/javascript">
eraser
var products=new book
Array("pen","scale","pencil","eraser","book");
var i; Sorted array :
for(i=0;i<products.length;i++) book
{
eraser
document.write(products[i] + "<br>"); pen
}
pencil
products.sort(); scale
document.write("<br>Sorted array : <br>");
for(i=0;i<products.length;i++)
{
document.write(products[i] + "<br>");
}
</script>
</body>
</html>
Program: Output:
<html> Array elements
<head></head> book
<body> pen
<h3>Array elements</h3> pencil
<script type="text/javascript"> eraser
var products=new Array ("book","pen","pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i] + "<br>");
}
document.write("<br> Combining array elements with
concat() :<br>");
var str=products.concat(); Combining array elements with concat():
document.write(str); book,pen,pencil,eraser
</script>
</body>
</html>
Program: Output:
<html> Array elements
<head></head> book
<body> pen
<h3>Array elements</h3> pencil
<script type="text/javascript"> eraser
var products=new Array("book","pen","pencil", "eraser");
var i; Combining array elements with join():
for(i=0;i<products.length;i++) book*pen*pencil*eraser
{
document.write(products[i] + "<br>");
}
document.write("<br> Combining array elements with
join() :<br>");
var str=products.join('*');
document.write(str);
</script>
</body>
</html>
Program: Output:
<html>
<head></head>
<body>
<h3>Reverse elements of an array</h3>
<script type="text/javascript">
var products=new Array("book", "pen", "pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i]+ "<br>");
}
document.write("<hr>");
document.write("<h4>Reverse method</h4>");
products.reverse();
document.write("Array elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>
shift( ) : It is used to remove first element from an array and return it. It also moves second element at the top
of an array.
Syntax: var variable_name=array_name.shift( );
Example: var str=products.shift( );
Program: Output:
<html>
<head></head>
<body>
<h3>Removing first element from an array</h3>
<script type="text/javascript">
var products=new Array("book", "pen", "pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i]+ "<br>");
}
document.write("<hr>");
document.write("<h4>shift method</h4>");
var str=products.shift();
document.write("Shifted element is : " +str);
document.write("<br> Array elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>
Program: Output:
<html>
<head></head>
<body>
<h3>Removing last element from an array</h3>
<script type="text/javascript">
var products=new Array("book","pen","pencil","eraser")
var i
for(i=0;i<products.length;i++)
{
document.write(products[i]+"<br>");
}
document.write("<hr>");
document.write("<h4>pop method</h4>");
var str=products.pop();
document.write("<br> poped element is : " +str);
document.write("<br> Array elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>
2.2 Function
Defining a function, writing a function, adding arguments, scope of variable and arguments
Defining a function: A function must be defined before it can be called in a JavaScript. A function
in a JavaScript is defined at the beginning of a JavaScript i.e. inside <head> tag or inside <body> tag. If a
function is defined inside <head> tag then all JavaScript code on the web page will know the definition of
that function. Web browser always loads everything from <head> tag before it starts execution of any part
from JavaScript.
Syntax to define a function:
function function_name([Arguments])
{
Statement block;
[return statement;]
}
- Function name is a user defined name. Function name must contain letters, digits or underscore
character. Only one function with same name must exist on a web page. A name cannot begin with a
digit, cannot be a keyword or reserved word. A name should represent action to be performed by the
function.
- Parenthesis are used to pass value if any, to the function. Values are referred as arguments. If the
function does not accept any value then bracket is empty.
- Statement block contains set of statements to be executed when a function is called. All statements of
function are written within a pair of curly brackets.
- Return is optional. It is a keyword that tells the browser to return a value from the function definition
to the statement that called the function. All functions don’t return value, so it is an optional
statement.
Example:
function display ( )
{
alert (“WELCOME TO JAVASCRIPT”);
}
When the above function is executed(called), it displays alert dialog box with the message
as ’WELCOME TO JAVASCRIPT’
Adding an argument:
A function need data to perform its task. Data required for processing task is either declared and accepted
inside function definition or it can be accepted in the form argument pass in function call.
Argument can be one or more variables(values) that are declared inside round brackets followed by function
name in function definition.
Example: function add (no1, no2) // No need to specify data type of any argument
{
var no3;
no3=no1+no2;
document. write (“addition = “+ no3);
}
In the above example, function add accepts two arguments as no1 and no2. These two arguments are used
inside function to process addition.
Program: Output:
<html>
<head>
<script type="text/javascript">
function add(no1,no2)
{
var no3;
no3=no1+no2;
document. write ("Addition = " + no3);
}
</script>
</head>
<body>
<script type="text/javascript">
add (10,20);
</script>
</body>
</html>
Program: Output:
<html>
<head>
<script type="text/javascript">
var a=10;
function display( )
{
document.write("Inside Function display<br>");
document.write("Global variable a= " + a);
var b=20;
document.write("<br>Local variable b= " +b);
}
function show()
{
document.write("<br>Inside Function show <br>");
document.write("Global variable a= " + a);
var c=30;
document.write("<br>Local variable c= " + c);
}
</script>
</head>
<body>
<h3>Scope of variable</h3>
<script type="text/javascript">
display( );
document.write("<hr>")
show( );
</script>
</body>
</html>
Calling a function: A function can be called with function name followed by brackets and arguments
(values) if any.
Syntax : function_name([Argument 1,Argument 2, . . . ,Argument n]);
Example: display( );
Note: A function definition can be placed inside <head> tag or <body> tag.
1. Calling a function without an argument: A function definition is placed within the <head> tag and the
function call is placed within the <body> tag. When a function is called, empty bracket followed by function
name is a function call that does not contain any argument. When function is called, browser passes control
to the function definition and executes statements from the code block.
Example:
Function definition:
function display( )
{
alert(“Welcome to JavaScript”);
}
Function call:
display( );
In the above example,when function call display( ) will execute, browser will pass the control to function
definition. Execution of function will display alert dialog box with the message “Welcome to javascript”.
Program: Output:
<html>
<head>
<script type="text/javascript">
function welcome()
{
alert("Welcome to javascript");
}
</script>
</head>
<body>
<script type="text/javascript">
welcome();
</script>
</body>
</html>
2. Calling a function with argument: Calling a function with arguments requires a function call with
argument values. When a function is called, its function call contains function name followed by argument
values inside round brackets. Argument values inside the bracket tells the browser to assign these values to
the corresponding arguments in the function.
Function call:
add(2,3);
In the above example,when function call add (2,3) will execute, browser will pass values 2 and 3 as function
arguments to function definition. Execution of function will display alert dialog box with the addition of no1
and no2.
Program: Output:
<html>
<head>
<script type="text/javascript">
function add(no1,no2)
{
document.write("<br> number 1 = " + no1);
document.write("<br> number 2 = " + no2);
document.write("<br> Addition = " + (parseInt(no1) +
parseInt(no2)));
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Program on function with argument");
add(2,3);
</script>
</body>
</html>
Program: Output:
<html> //onload event calls welcome function at the time of
<head> loading browser contents(web page)
<script type="text/javascript">
function welcome()
{
alert("Welcome to JavaScript");
}
function goodbye()
{
alert("Thank you for visiting");
}
</script> //onclick event of submit button calls goodbye
</head> function when user click on submit button.
<body onload="welcome()">
<form>
<input type="submit" onclick="goodbye()">
</form>
</body>
</html>
Example:
function add(no1,no2)
{
var no3;
no3=parseInt(no1)+parseInt(no2);
return no3;
}
In calling function, add function is called with : var result=add(2,3);
Program: Output:
<html>
<head>
<script type="text/javascript">
function add(no1,no2)
{
var no3;
no3=parseInt(no1)+parseInt(no2);
return no3;
}
</script>
</head>
<body>
<script type="text/javascript">
var result;
result=add(2,3);
document.write("Addition = " + result);
</script>
</body>
</html>
Creating pop-up window:
A pop-up window is a small user interface element that will be displayed on a web page when an event
triggers. A pop-up window can be used to open another link on a web page in same window or in a new tab.
For creating a pop-up window, window object along with open method is used with arguments.
Syntax: window.open(URL,name,features,replace);
URL=” address of web page” : It specify URL of a web page to be opened in a pop-up window. If
URL is not specified, then a new window with about:blank will open on a web page.
Features=”height/width/top/left/menubar/toolbar/status/resizable/scrollbars”: It specify
list of features that specify parameters to be set for pop-up window. All parameters are separated with a
comma. The list of parameters:
- height=pixels: Specify height of pop-up window
- width=pixels: Specify width of pop-up window
- top=pixels: Specify position of pop-up window from top
- left=pixels: Specify position of pop-up window from left
- menubar=”yes/no” : Shows or hides the browser menu
- toolbar=”yes/no”: Shows or hides the navigation bar
- status=”yes/no”: Shows or hides the status bar
- resizable=”yes/no”: Whether or not the window is resizable
- scrollbars=”yes/no”: Whether or not to display scroll bars
Replace=”true/false” : Specifies whether the URL creates a new entry or replace the current entry in the
browser history. Works only if the URL is loaded into the same window.
- true: URL replaces the current document in the history list
- false: URL created a new entry in the browser history list
Example:
<html>
<head>
</head>
<body>
<input type="button" value="open popup" onclick="window.open( 'example/page1.html', '_blank ',
'height=400 , width=400, top=200, left=200, resizable=yes')">
</body>
</html>
Output:
Chapter 2.4 Strings
Manipulate a string, joining a string, retrieving a character from given position,
retrieving a position of character in a string ,dividing text, copying a sub string,
converting string to number and numbers to string, changing the case of string, finding
a Unicode of a character-charCodeAt(),fromCharCode().
String: It is a collection of characters. String is used for storing and manipulating text. A string can be
declared in a single quote or double quote.
Example: var a=’hello’; OR var a=”hello”;
String manipulation is the process of working with string. It includes performing various operations
on string such as join, search, copy, split, etc.
Joining a string:
Concatenating / merging two strings : in joining operation a new string is formed from two strings, by
placing contents of second string at the end of first string. New string contains all characters from both the
strings. ‘+’ operator is used to join / concatenate two strings.
Program: Output:
<html>
<head></head>
<body>
<script type="text/javascript">
var str1="hello";
var str2=" Welcome to CSS";
var str3=str1+str2;
document.write("String1 = " + str1);
document.write("<br> String2 = " + str2);
document.write("<br>Concatenated string = " + str3);
</script>
</body>
</html>
To retrieve a position of character from a string, indexOf( ) method of string object is used. indexOf( )
method returns the index position of a character passed as an argument in charAt( ) method. If the character
is not in the string then the method returns -1 value.
Syntax: var index=stringobject.indexof(‘char’);
Program: Output:
<html> If specified character is in the list:
<head></head>
<body>
<script type="text/javascript">
var str1;
var str2;
str1=prompt("Enter string"," ");
str2=prompt("Enter character"," ");
var index=str1.indexOf(str2);
if(index != -1) If specified character is not in the list:
{
document.write("Character "+str2+ " is at index
position= "+index);
}
else
{
document.write("Character is not in the list");
}
</script>
</body>
</html>
Dividing text:
A comma separated/delimited string contains multiple data elements separated with comma. Comma is used
to specify the beginning and end of each data element. split( ) method of string object is used to separate
each data element into its own string. split( ) method creates a new array and then copies portions of the
string,called a sub string into its array elements.
Program: Output:
<html> datastring=
<head></head> JavaScript,VBScript,Python,Android
<body>
<script type="text/javascript">
var datastring="JavaScript,VBScript,Python,Android"; String after split in array elements
var newarray=datastring.split(','); JavaScript
document.write("datastring= " + datastring); VBScript
document.write("<hr><br>String after split in array elements"); Python
for(var i=0;i<newarray.length;i++) Android
{
document.write("<br>" + newarray[i]);
}
</script>
</body>
</html>
1. substring( ) : This method copies a substring from a string based on a beginning and an end position,
passed as an argument to the substring( ).
Syntax: stringvar=string.substring(start,end);
- start : specify position of first character to be copied from string.
- end : specify position of character whose previous character will be last character to be copied from string.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
W e l c o m e t o J a v a S c r i p t
Program: Output:
<html> datastring= Welcome to JavaScript
<head></head>
<body> new substring= ome to J
<script type="text/javascript">
var datastring="Welcome to JavaScript";
var newstr=datastring.substring(4,12);
document.write("datastring= " + datastring);
document.write("<hr>new substring= " +newstr);
</script>
</body>
</html>
2. substr( ) : This method is used to copy sub string from a string based on starting position and number of
characters pass as an argument to the method.
Syntax: stringvar=string.substr(startposition,noofchar);
- start position specify position of first character from string
- noofchar specify number of characters to be copied from first character from the string.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
W e l c o m e t o J a v a S c r i p t
Program: Output:
<html>
<head></head> datastring= Welcome to JavaScript
<body>
<script type="text/javascript"> new substring= ome to Jav
var datastring="Welcome to JavaScript";
var newstr=datastring.substr(4,10);
document.write("datastring= " + datastring);
document.write("<hr>new substring= " +newstr);
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var data1=10;
var data2=20;
var str1=data1.toString();
var str2=data2.toString();
document.write(str1+str2);
//document.write(data1+data2);
</script>
</body>
</html>
<html> a= 4
b= 5
<head></head> Addition without conversion= 45
<body> Addition with conversion= 9
<script type="text/javascript">
var a=prompt("Enter first number","");
var b=prompt("Enter second number","");
document.write("a= "+a);
document.write("<br>b= "+b);
var c=a+b;
document.write("<br> Addition without conversion= " +c);
var d=parseInt(a);
var e=parseInt(b);
var f=d+e;
document.write("<br> Addition with conversion=" +f);
</script>
</body>
</html>
2. parseFloat( ) : This method converts a floating number stored in string into a float / decimal value.
Syntax: var number=parseFloat(string_name);
Example: var no=parseFloat(str1);
<html> a= 2.47
<head></head> b= 3.50
<body> Addition without conversion= 2.473.50
<script type="text/javascript"> Addition with conversion=
var a=prompt("Enter first number",""); 5.970000000000001
var b=prompt("Enter second number","");
document.write("a= "+a);
document.write("<br>b= "+b);
var c=a+b;
document.write("<br> Addition without conversion= " +c);
var d=parseFloat(a)+parseFloat(b);
document.write("<br> Addition with conversion= " +d);
</script>
</body>
</html>
Changing case of string:
In some application, for string validation and comparison , JavaScript developers need to convert string into
either lowercase or uppercase. For changing case of string two methods of string object are used such as
toLowerCase( ) and toUpperCase( ).
1. toLowerCase( ) : This method is used to convert a given string characters into lowercase letters. After
conversion it returns converted string.
Syntax: str=stringobj.toLowerCase( );
Example: var str=”WELCOME to CSS”;
document.write(“ Lowercase characters= “ +str.toLowerCase( ));
<html>
<head></head>
<body>
<script type="text/javascript">
var str1="WELCOME to CSS";
document.write("Original String : = " + str1);
document.write("<br>Converted into Lowercase : = " +
str1.toLowerCase( ));
</script>
</body>
</html>
2. toUpperCase( ) : This method is used to convert a given string characters into uppercase letters. After
conversion it returns converted string.
Syntax: str=stringobj.toUpperCase( );
Example: var str=”welcome TO CSS”;
document.write(“Uppercase characters= “ +str.toUpperCase( ));
<html>
<head></head>
<body>
<script type="text/javascript">
var str1="welcome TO css";
document.write("Original String : = " + str1);
document.write("<br>Converted into Uppercase : = " +
str1.toUpperCase( ));
</script>
</body>
</html>