You are on page 1of 31

ARRAY

An array is an object that can store a collection of items. Arrays is useful when you need to store large amounts
of data of the same type like storing of details of 100 students. If you are using variables, you will have to create
100 different variables but you can do the same with a single array. You can access the items in an array by
referring to its index number and the index of the first element of an array is zero. An array in JavaScript can hold
different elements – We can store Numbers, Strings and Boolean in a single array.
 Declaring an Array :
There are basically two ways to create an array :

1. By array literal :
Syntax:
var arrayname= [value1,value2,……..,valuneN];
values are contained inside [] and separated by ,(comma).
Example:
<html>
<head>
<title>Array demo</title>
</head><body><script>
var a=[1,2,3,4,5];
document.write(“Length of an array=”+a.length);
</script> </body> </html>
Output:
Length of Array=5

2. By creating instance of Array:


Syntax:
var arrayname=new Array();
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
//array constructor with a single parameter
var a= new Array(3);
or
//array constructor with a multiple parameters
var a= new Array(“apple”,”banana”,”orange”);
document.write(“Length of array=”+a.length);
</script></body></html>
Output: Length of array=3
 Initializing an Array:
Initialization is the process of assigning values to an array. While initializing an array, all the elements
should be placed in parenthesis and separated by commas.
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array(“C”,” C++”,”Java”,”VB”);
document.write(“Length of array=”+a.length);
</script> </body> </html>
Output: Length of array=4
 Defining an array elements:
Array contains a list of elements; each elements in the array is identified by its index. The firs
element in the array stores at 0th position, second element at 1st position, third element at 2nd position and
so on. Assignment (=) operator used to assign values to an array elements. Elements can be retrieving by
its index position.
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array(4);
a[0]=”C”;
a[1]=”C++”;
a[2]=”Java”;
a[3]=”VB”;
document.write(“<br>Elements at 0th place=”+a[0]);
document.write(“<br>Elements at 1th place=”+a[1]);
document.write(“<br>Elements at 2th place=”+a[2]);
document.write(“<br>Elements at 3th place=”+a[3]);
</script></body></html>
Output:
Elements at 0th place=C
Elements at 1th place=C++
Elements at 2th place=Java
Elements at 3th place=VB
 Looping an Array:
In JavaScript, for loop iterate over each item in an array. Arrays are zero based, which means the
first item is referenced with an index of 0. Elements in an Array are access by a numeric index, starting
at zero and ending with an array length minus 1.
Example :
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array(“one”,Two”,”three”);
a[0]=”C”;
a[1]=”C++”;
a[2]=”Java”;
a[3]=”VB”;
for(var i=0;i<a.length;i++)
{
document.write(“<br> Element=”+a[i]);
}
</script></body></html>
Output:
Element=C
Element=C++
Element=Java
Element=VB
 Adding an Array Element:
Sometimes, it is important to increase the size of an array by adding elements. Following are
two ways to add elements in array-
1. Using push() method:
It adds one or more elements at the end of an array. This method changes the original
length of an array.
Syntax:
array.push(element1,element2,……,elementN);
Example :
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=”C”;
a[1]=”C++”;
document.write(“Original Length=”+a.length+”<br>”);
a.push(“Java”);
a.push(“VB”,”PHP”);
document.write(“New length after push method=”+a.length+”<br>”);
for(var i=0;i<a.length;i++)
{
document.write(a[i]);
}
</script></body></html>
Output:
Original Length=2
New length after push method=5
CC++JavaVBPHP
2. Using unshift() method:
Is adds one or more elements in the beginning of an array. It returns the updated array with
change in length.
Syntax: array.unshift(element1,element2,……,elementN);
Example :
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=”Java”;
document.write(“Original Length=”+a.length+”<br>”);
a.unshift(“C”.”C++”,”VB”);
document.write(“New length after unshift method=”+a.length+”<br>”);
for(var i=0;i<a.length;i++)
{
document.write(a[i]);
}
</script></body></html>
Output:
Original Length=1
New length after unshift method=4
CC++VBJava
 Sorting an array element:
1. sort():
sorts the elements of an array in place and returns the sorted array. When sort() without argument is
called, it will sort elements in alphabetical order.
Syntax: array.sort(compareFunction);
The sort() function is used to the array in place in a given order according to the compare()
function. The only argument to this function is a compare function that is used to sort the elements
according to different attributes and in the different order.
- compareFunction(a,b)<0=Then a comes before b in the answer.
- compareFunction(a,b)>0=Then b comes before a in the answer.
- compareFunction(a,b)=0=Then the order of a and b remains unchanged.
1. Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=4;
a[1]=3;
a[2]=1;
a[3]=2;
a.sort();
for(var i=0;i<a.length;i++)
{
document.write(a[i]);
}
</script></body></html>
Output: 1234

2. Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=20;
a[1]=13;
a[2]=5;
a[3]=2;
a.sort(function(a,b)
{
return a-b
}
);
for(var i=0;i<a.length;i++)
{
document.write(a[i]+”<br>”);
}
</script></body></html>
i. reverse():
sort method will sort all elements from array in ascending order, we can use reverse method to
display sorted list in reverse manner i.e. in descending order.
Syntax:
array.reverse();
It will return the reversed single value of the array.
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=4;
a[1]=3;
a[2]=5;
a[3]=12;
a[4]=223;
var r=a.sort();
r.reverse();
for(var i=0;i<a.length;i++)
{
document.write(a[i]);
}
</script></body></html>
 Combining an Array Elements into Strings
In JavaScript, an array can be combined into string using following two functions:
1. Join():
This function joins all elements of an array into a string.
Syntax:
array.join(separator);
Here, separator is like/,-,* etc. to separate each element of the array. If separator is not mentioned, it will
display list with comma as separator. This function returns a string after joining all elements together.
Example 2:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=”C”;
a[1]=”C++”;
a[2]=”Java”;
var r=a.join();
document.write(“After joining=”+r);
</script>
</body>
</html>
Output:
After joining=C,C++,Java
Example 1:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=”C”;
a[1]=”C++”;
a[2]=”Java”;
var r=a.join(/);
document.write(“After joining=”+r);
</script></body></html>
Output:
After joining=C/C++/Java

2. Concat():
This function is used to join two or more array together in JavaScript. This function returns a
new string which is combination of different strings passed to it as argument.
Syntax:
string1.conact(string1,string2,……,stringN);
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Array();
a[0]=”C”;
a[1]=”C++”;
a[2]=”Java”;
var r=a.concat(VB);
document.write(“After joining=”+r);
var r1=a.concat(“NET”,”PHP”);
document.write(“<br> After joining=”+r);
</script></body></html>
Output:
After joining=C,C++,Java,VB
After joining=C,C++,Java,VB,NET,PHP
 Changing elements of an array:
1. shift():
This method is used to remove first element from an array and returns the removed single value
of an array.
Syntax: array.shift();
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
Var a=new Array();
a[0]=5;
a[1]=3;
a[2]=4;
a[3]=2;
a[4]=1;
document.wite(“Elements before shift…..<br>”);
for(var i=0;i<a.length;i++)
{
Document.write(a[i]+“<br>”);
}
a.shift();
document.write(“Elements after shift…..<br>”);
for(var i=0;i<a.length;i++)
{
document.write(a[i]+“<br>”);
}
</script></body></html>
Output:
Elements before shift….
5
3
4
2
1
Elements after shift….
3
4
2
1

2. Pop():
This method is used to remove last element and returns the removed elements from an array.
Syntax: array.pop();
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
Var a=new Array();
a[0]=5;
a[1]=3;
a[2]=4;
a[3]=2;
a[4]=1;
document.wite(“Elements before pop…..<br>”);
for(var i=0;i<a.length;i++)
{
Document.write(a[i]+“<br>”);
}
a.pop();
document.write(“Elements after pop…..<br>”);
for(var i=0;i<a.length;i++)
{
Document.write(a[i]+“<br>”);
}
</script></body></html>
Output:
Elements before pop….
5
3
4
2
1
Elements after pop….
5
3
4
2
3.splice():
It is add or remove the elements to or from the existing array. It returns the removed elements
from an array. The splice() method also modifies the original array.
Syntax: array.splice(start,delete,element1,element2,……,elementN);

start: it represent the index from where the method start to extract the elements.
Delete: it is optional. It represent the number of elements to be inserted.
Example 1:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
Var a=new array();
a[0]=”C”;
a[1]=”C++”;
document.write(“Original Length=”+a.length+<br/>);
a.splice(2,0,”Java”,”PHP”);
document.write(“New length=”+a.length);
for(var i=0;i<.length;i++)
{
document.write(a[i]);
}
</script></body></html>
Output:
Original Length=2
New Length=4
CC++JavaPHP
Example 2:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
Var a=new array();
a[0]=”C”;
a[1]=”C++”;
a[2]=”Java”;
a[3]=”VB”;
document.write(“Original Length=”+a.length+<br/>);
a.splice(2);
document.write(“New length=”+a.length);
for(var i=0;i<.length;i++)
{
document.write(a[i]);
}
</script></body></html>
Output:
Original Length=4
New Length=2
CC++
Object as Associative Array:
Associative arrays are dynamic objects that the user redefines as needed. When you assign values to
keys in a variable of type array, the array is transformed into an object, and it looses the attributes and
methods of array. We can create it by assigning a literal to a variable.
Syntax:
array={key1:’value1’, key2:’value2’};
Example:
var a={“one”:1,”two”:2,”three”:3};
 the value is stored in associated with key and the value is ace ssed by keys.
var r=a[“one”];
Example 1:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a={“Name”:”Jhon”,”Age”:23,”Language”:”English”};
document.write(“Name=”+a[“Name”]);
document.write(“<br>Age=”+a[“Age”]); document.write(“<br>Language=”+a[“Language”]);
</script></body></html>
Output:
Name=Jhon
Age=23
Language=English
Example 2:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Object();
a[“Name”]=”Jhon”;
a[“Age”]=23;
a[“Language”]=”English”;

for(var i in a)
{
document.write(i+”=”+a[i]+”<br>”);
}
</script></body></html>
Output:
Name=Jhon
Age=23
Language=English

There is an alternative way to access a value that makes the key look like a property. That is possible
using “property syntax”:
Syntax: array.key=value;
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
var a=new Object();
a.Name=”Jhon”;
a.Age=23;
a.Language=”English”;

for(var i in a)
{
document.write(i+”=”+a[i]+”<br>”);
}
</script></body></html>
Output:
Name=Jhon
Age=23
Language=English

FUNCTION
A function is a subprogram designed to perform a particular task.
Functions are executed when they are called. This is as invoking a function.
Values can be passed into functions and used within the functions.
Functions always return a value. In JavaScript, if no return value is specified, the function will return
undefined.
Functions are objects.
 Defining a function:
The function definition consist of following parts:
1. The function keyword with Name of function.
2. A list of parameters names encloses in parenthesis.
3. The statement enclose in braces.
4. The return keyword(optional).
Syntax:
function name(parameters)
{
Statements;
}
 Writing a function:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
Function display()
{
document.write(“In display function”);
}
</script></body></html>
 Adding an argument:
When one or more variables that are declared within the parentheses of a function definition is
known as arguments. These arguments are used to hold data to perform some task.
Example:
<html>
<head>
<title>Array demo</title>
</head>
<body>
<script>
function display(name,age)
{
document.write(“details=”+name+age);
}
</script></body></html>
 Scope of variables and Argument
1. Global scope: All the variables that you declare, is by default defined in global scope. When a variable
is declared outside a function with a var keyword then that variable is a global variable because it is
available through all parts of script
2. Local script: All variables which are declared using var keyword within function then those variable are
known as local variable and they are accessible within function only.
Example
<html>
<head>
<title>Function demo</title>
</head>
<body>
<script>
var g=”Welcome”;
function display()
{
Var l=”Thanks”;
Document.write(“Global value=”+g);
Document.write(“Local value=”+l);
}
</script></body></html>

Output:
Global value=Welcome
Local value=Thanks
 Calling a function:
1. Calling a function with or without argument:
In JavaScript function calling is by using name of function followed by parenthesis.
Syntax: function_name();
Example:
<html>
<head>
<title>Function demo</title>
<body>
</script>
function area()
{
Var l=5;
Var b=3;
document.write(“Area of rectangle=”+(l*b));
}
area();
</script></body></html>

Output:
Area of rectangle=15
If function has arguments(parameters) then values for each argument in placed within parentheses
separated by commas.
Syntax: function_name(values_for_parameters);
Example:
<html>
<head>
<title>Function demo</title>
</head>
<body>
<script>
function area(l, b)
{
Document.write(“Area of rectangle=”+(l*b));
}
area(10,2);
</script></body></html>
Output:
Area of rectangle=20

2. Calling a function from HTML


In JavaScript function can be called from HTML code in response of any particular event like page
load, page unload, button click etc.
Example:
<html>
<head>
<title>Function demo</title>
<body>
<script>
function open()
{
alert(“Welcome”);
}
function close()
{
alert(“Thank You”);
}
</script> </body> </html>
3. Function calling another function:
In JavaScript we can call one function inside another function.
Example:
<html>
<head>
<title>Function demo</title>
<body>
<script>
function accept(s)
{
document.write(“Enter your city=”+s);
}
function display()
{
accept(“Mumbai”);
}
display();
</script></body></html>
Output: Enter your city=Mumbai
4. Returning value from function
The ‘return’ keyword stops the execution of function and the value is return from the function to the
function caller.
Syntax: return value;
example:
<html>
<head>
<title>Function demo</title>
</head>
<body>
<script>
function accept()
{
Var s=prompt(“Enter your city”);
Return(s);
}
Var r=accept();
document.write(r);
</script></body></html>

String
In JavaScript, strings are used for storing and manipulating text. String is zero or more characters written inside
quotes.
var c=”India”;
JavaScript strings are primitive values, created from literals.
var fName =”Bob”;
But string can also be defined as objects with new keyword.
var fName=new String(“Bob”);
Example:
<html>
<head>
<title>Function demo</title>
</head>
<body>
<script>
var c=”India”;
document.write(“String value=”+c);
var s=new String(“INDIA”);
document.write(“<br>String as object=”+s);
</script></body></html>
Output:
String value=India
String as object=INDIA
 Manipulating a string :
String manipulation means operations on string like- concatenation, extraction of sub string, finding length,
finding position of characters, changing case of string characters, etc.
Following are methods of String class:
Method name Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the
specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides a position of a char value present in the given
string.
lastIndexOf() It provides the position of a char value present in the given
string by searching a character from the last position.
search() It searches a specified regular expression in a given string and
returns position if match occurs.
match() It searches a specifies regular expression in a given string and
returns that regular expression if match occurs.
replace() It replace a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of
the specified staring position and length.
subString() It is used to fetch the part of the given string on the basis of
the specified index.
slice() It is used to fetch the part of given string. It allows us to
assign positive as well as negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis
of hosts current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis
of hosts current locale.
toString() It provides a string representing the particular object
valueOf() It provides a primitive value for string object.

 Joining a string:
String concatenation means joining two strings to create a new string by placing the copy of second
string behind a copy of string.
METHODS:
1. Using concatenation(+) operator:
Syntax:
String1+string2;
In this method, concatenation(+) operator is used to joining two separate things.
var name=fName+sName;
Example:
<html>
<head>
<title>Function demo</title>
<body>
<script>
var year=”TY”;
var branch=”IT”;
document.write(“String value=”+(year+branch));
</script></body></html>
Output:
String value=TYIT

2. Using concat():
This methods combines one or more strings into the existing one and returns the combined string.
Original string is not modified.
Syntax:
Concat(v1,v2,….);
var message=”India”;
var final=message.conat(“is my country”);
Example:
<html>
<head>
<title>Function demo</title>
</head>
<body>
<script>
Var message=”India” ;
Var result=message+”is my country”;
document.write(“String value= ”+result);
</script></body></html>
Output: String value=India is my country
 Retrieving a character from given position:
1. charAt(): returns the character at the “x” position within the string.
Syntax:
String.charAt(x);

Example:
<html>
<head>
<title>Function demo</title>
</head><body><script>
Var message=”Hello world” ;
document.write(message.charAt(7));
</script></body></html>
Output:
0
 Retrieving a Position of Character in a string
1. indexOf():
This function searches and returns the index number of the character or substring within the string.
Syntax: indexOf(substr,[start]);
substr is a string/character that we want to search and start is an optional argument specifying the
position within string to begin the search. Default value for the start is 0.
Syntax: string.insteadOf(char/substring);
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var string=”Hello World”;
document.write(“Position=”+string.indexOf(“d”));
</script></body></html>
Output:
Position=10

2. lastIndexOf():
This method searches and returns the index number of last occurrence of the character within the string.
Searches the string from end to beginning.
Syntax: String.lastIndexOf(substr,[start]);
The value of start can be between 0 to the length of the string.
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var string=”Hello World”;
document.write(“ First Position=”+string.indexOf(“l”));
document.write(“last Position=”+string.lastIndexOf(“l”));
</script></body></html>
Output:
First Position=2
Last Position=9
3. search():
This method searches a string for a specified value and returns the position of the if match found.
Syntax: String.search(word);

Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var string=”Hello World”;
document.write(“ First Position=”+string.search(“World”));
</script></body></html>
Output:
Position=6

 Dividing a text:
1. Split():
This function is used to split the given string into array of strings by separating it into
substrings using a specified separator.
Syntax :String.split(separator,limit);

The separator specified a points where the spit has to take place. If the separator is not specified
then the entire string becomes one single array element. If the separator is an empty string(‘ ’) the
every character of the string is separated by commas.
The limit specifies the upper limit on the number of the splits to be found in the given string.
This functions returns an array of strings that is formed after splitting the given string with the help
of separator.
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var string=”Welcome to World of JavaScript”;
document.write(“Result=”+string.split());
</script></body></html>
Output:
Result=Welcome,to,World,of,JavaScript
 Copying a substring:
1. substring():
returns the character in a string between “from” and “to” indexes. “To” is optional, and if it is
omitted then it will search up to the end of the string.
Syntax: string.substring(from,[to]);
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var string=”Welcome to World of JavaScript”;
document.write(“Result=”+string.substring(5));
document.write(“Result=”+string.substring(5,10));
</script></body></html>
Output:
Result=me to JavaScript
Result=me to
2. substr():
returns the character in a string beginning at “start” and through the specified number of characters,
“length”. “Length” is optional, and if omitted, end of the string is assumed.
Syntax: string.substr(start,[length]);
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var string=”Welcome to World of JavaScript”;
document.write(“Result=”+string.substring(2));
document.write(“Result=”+string.substring(2,5));
</script></body></html>
Output:
Result=lcome to JavaScript
Result=lcome
 converting string to numbers and numbers to string:
1. parseInt(): the parseInt() parses a string and returns a number.
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”25”;
Var j=”15 years”;
document.write(“Integer result1=”+parseInt(i));
document.write(“Integer result2=”+parseInt(j));
</script></body></html>
Output:
Integer Result1=25
Integer Result2=15

2. parseFloat():
is parses a string and returns a number.
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”25.5”;
Var j=”3.14f”;
document.write(“Float result1=”+parseFloat(i));
document.write(“Float result2=”+parseFloat(j));
</script></body></html>
Output:
Float Result1=25.5
Float Result2=3.14f
3. number():

this function converts a string to a number. If the string value is number then it will convert otherwise
will return NaN as output.
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”25.5”;
Var j=”3.14f”;
document.write(“Number result1=”+parseFloat(i));
document.write(“Number result2=”+parseFloat(j));
</script></body></html>

Output:
Number Result1=25.5
Number Result2=NaN
4. string():
this function is used to convert number to string.
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”67”;
document.write(“String=”+i.toString());
</script></body></html>
Output: String=67

 Changing the case of string:


1. toUpperCase():
this function will returns the string with all of its characters converted to uppercase.
Syntax: string.toUpperCase();

Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”Welcome to JavaScript”;
document.write(“Result=”+i.toUpperCase());
</script></body></html>
Output:
Result=WELCOME TO JAVASCRIPT

1. toLowerCase():
this function will returns the string with all of its characters converted to lowercase.
Syntax:
string.toLowerCase();
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”Welcome to JavaScript”;
document.write(“Result=”+i.toLowerCase());
</script></body></html>
Output: Result=welcome to javascript
 Finding a Unicode of a character:
1. charCodeAt():
this function returns the Unicode value of the character at a specified position.
Syntax:
String.charCodeAt(x);
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
Var i=”Welcome to JavaScript”;
document.write(“Result=”+i.charCodeAt(4));
</script></body></html>
Output:
Result=111
2. fromCharCode():
this method convert a given Unicode number into a character.
Syntax: String.fromCharCode(n1,n2,….,nX);
Example:
<html>
<head>
<title>string demo</title>
</head>
<script>
document.write(“Unicode=”+String.fromCharCode(115));
document.write(“Unicode=”+String.fromCharCode(70,71,72,115));
</script></body></html>
Output:
Unicode=s
Unicode=FGHs

You might also like