UNIT NO:02 14 M
ARRAY,FUNCTION
AND STRING
JAVASCRIPT ARRAY
JavaScript array is an object that represents a
collection of similar type of elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new
keyword)
By using an Array constructor (using new keyword)
1) JAVASCRIPT ARRAY LITERAL
The syntax of creating array using array literal is
given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and
separated by , (comma).
Example:
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>
2) JAVASCRIPT ARRAY DIRECTLY (NEW KEYWORD)
The syntax of creating array directly is given below:
var arrayname=new Array();
or var arrayname=new Array(Number length)
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
3) JAVASCRIPT ARRAY CONSTRUCTOR (NEW
KEYWORD)
Here, you need to create instance of array by
passing arguments in constructor so that we don't
have to provide value explicitly.
The example of creating object by array constructor
is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
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.
var items=new Array(“one”,”two,”three”);
document.write(“length of the array=”+items.length);
DEFINING ARRAY ELEMENTS
Defining array elements Array contain a list of
elements, each element in the array is identified
by its index. always index start from zero.
Assignment operator(=)is used to assign values to
an array elements.
Elements are retrieved by its index.
var items=new array(3);
items[0]=“one”;
items[1]=“two”;
items[2]=“three”;
document. write(“ ”+items[0]);
LOOPING AN ARRAY
In java script ,for loop iterate over each item in an array.
• Array are zero based, which means the first item is referenced
with an index zero.
• Last element is accessed with index length-1.
<html>
<head></head>
<body>
<script>
var a=[4,5,6,8,10];
document.write("array elements are");
for(var i=0;i<a.length;i++)
{
document.write("<br>"+a[i]+"<br>")
}
</script>
</body>
</head>
<html>
Q:Write a Java script that initializes an array called flowers
with the names of 3 flowers. The script then displays array
elements.
<html>
<head>
<title> Display Array elements</title>
</head>
<body>
<script >
var flowers = new Array();
flowers[0] = 'Rose ';
flowers[1] = 'Mogra';
flowers[2] = 'Hibiscus';
for (var i = 0; i < flowers.length; i++)
{
document.write(flowers[i] + '');
}
</script>
</body>
</html>
DIFFERENT METHODS OF ARRAY
reverse() method → Returns the reverse order of items
in an array.
sort() method → Returns the sort array.
pop() method → Remove the last item of an array.
shift() method → Remove the first item of an array.
push() method → Adds an array element to array at
last.
unshift() method → Adds an array element to array at
beginning.
join() method->join the elements of array into string.
splice() method-> used to replace the items of an
existing array by removing and inserting new elements
at the required index.
ADDING AN ARRAY ELEMENT
We can add elements into array by following ways:
push() method of array
unshift() method of array
push() method appends the given element(s) in the last of the
array and returns the length of the new array.
array.push(element1, ..., elementN);
• element1, ..., elementN : elements add to the end of the
array.
unshift() method adds one or more elements at the begining
of the array.it returns updated array with change in length.
array.unshift(element1, ..., elementN);
//program to demonstrate push and unshift method of
array
<html>
<head></head>
<body>
<script>
var a=[4,5,6,8,10];
document.write("array elements are");
a.push(12);
a.unshift(14);
for(var i=0;i<a.length;i++)
{
document.write("<br>"+a[i]+"<br>")
}
</script>
</body>
</head>
<html>
SORTING AN ARRAY ELEMENTS
Index of array specifies the order in which elements appear in an array
when for loop is used to display array sometimes we want elements to
appear in sorted order.
sort() method sorts the elements of an array in ascending order.
Syntax:
arrayObj.sort();
<html>
<head>
<title>JavaScript Array sort Method</title> </head>
<body>
<script type = "text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
var sorted = arr.sort();
document.write("Returned string is : " + sorted );
</script>
</body>
</html>
Array reverse() method:
sort method sort all elements in ascending order,
we can use reverse method to display sorted element in
descending order.
Syntax: array.reverse();
NUMERIC SORT
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before
"Banana").
However, if numbers are sorted as strings, "25" is
bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce
incorrect result when sorting numbers.
You can fix this by providing a compare function:
arr.sort(function(a, b){return a - b});
<html>
<head></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]);
}
</script>
</body>
COMBINING AN ARRAY ELEMENTS
Sometime there is need to combine all elements of an
array into a single string.
Array elements can be combined in two ways:
Using the concat() method
Using the join() method
join() this function joins all elements of an array into
a string. array.join() or
array.join(separator);
Parameter Details: separator − Specifies a string to
separate each element of the array. If omitted, the
array elements are separated with a comma.
<html>
<head>
<title>JavaScript Array join Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = new Array("First","Second","Third");
var str = arr.join();
document.write("str : " + str );
var str = arr.join(“|");
document.write("<br />str : " + str );
var str = arr.join(" + ");
document.write("<br />str : " + str );
</script>
</body>
</html>
Javascript array concat() method returns a new array
comprised of this array joined with two or more arrays.
The syntax of concat() method is as follows −
array.concat(value1, value2, ..., valueN);
This method returns an array object representing the resultant
array, a concatenation of the current and given array(s).
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type = "text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
document.write("alphaNumeric : " + alphaNumeric );
</script>
</body>
</html>
CHANGING ELEMENTS OF AN ARRAY
Using Index number: We can change the elements of an array
using index number.
JavaScript array splice() method changes the content of an array,
adding new elements while removing old elements.
Syntax:
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details:
index −
: index at which to start changing the array.
howMany −An integer indicating the number of old array elements to
remove. If howMany is 0, no elements are removed.
element1, ..., elementN −The elements to add to the array. If you
don't specify any elements, splice simply removes the elements
from the array.
//program to demonstrate splice method
<html>
<head>
<title>JavaScript Array splice Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = ["orange", "mango", "banana"];
document.write(“Before Array is: " + arr );
arr.splice(1, 1, "water");
document.write("<br />After Array is: " +arr);
</body>
</html>
CHANGING ELEMENTS OF AN ARRAY
shift() method: this method used to remove first
element from an array and returns the removed
single value of an array.
Syntax:
array.shift();
pop() method : this method is used to remove
last element and returns the removed element
from an array.
Syntax:
array.pop();
OBJECT AS ASSOCIATIVE ARRAY
Associative array are dynamic objects that the user
redefines as needed .
When user assigns values to keys in a variable of type
Array, it transforms into an object and loses the
attributes and methods of previous data type.
We can create it by assigning a literal to a variable.
Syntax:
<name of the array> = {key1:’value1’, key2:’value2’,
key3:’valu3’…..};
Example:
var a={“one”:1,”two”:2,”three”:3};
//program to demonstrate associative array
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var array = { "alpha": 1, "beta": 2, "gama": 3 };
var x = array["beta"];
document.write(x);
</script>
</body>
</html>
JAVASCRIPT FUNCTIONS
A JavaScript function is a block of code designed to
perform a particular task.
A JavaScript function is executed when "something"
invokes it (calls it).
There are mainly two advantages of JavaScript
functions.
Code reusability: We can call a function several times so
it save coding.
Less coding: It makes our program compact. We don’t
need to write many lines of code each time to perform a
common task.
A JavaScript function can be defined
using function keyword.
//defining a function
<script type = "text/javascript">
<!-- function functionname (parameter-list)
{
statements
}
//-->
</script>
Example: Define and Call a Function
function ShowMessage()
{
alert("Hello World!");
}
CALLING A FUNCTION
To invoke a function somewhere later in the script, you
would simply need to write the name of that function.
//calling a function
Syntax:
function-name(); //without argument
Or
function-name(values for parameter) //with argument
ShowMessage(); //call function
ADDING AN ARGUMENT
We can add arguments in a function, which are used to hold
data to perform some task.
<html>
<head>
<title> function example</title>
</head>
<body>
<script>
function myfunction(message)
{
document.write(message);
}
myfunction(“hello this is my first function”);
</script>
</body>
</html>
FUNCTION PARAMETERS(ARGUMENTS):
A function can take multiple parameters separated by
comma.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age)
{ document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body> <p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value =
"Say Hello">
</form> <p>Use different parameters inside the function and
then try...</p>
</body>
</html>
SCOPE OF VARIABLE AND ARGUMENTS
Global scope: All the variables that you declare, is
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.
Local scope: all variables which are declared using
var keyword within function are called local variables
and they are accessible within function only.
EXAMPLE OF LOCAL AND GLOBAL VARIABLE
// program to print a text
<html>
<body>
<script language=“javascript”>
var a = "hello"; //Global Variable
function greet ()
{
var i=“hi”; //Local Variable
document.write(i);
document.write(a);
}
greet();
</script>
</body>
</html>
Output:
hi hello
WRITE JAVASCRIPT TO CALL FUNCTION FROM HTML
In JavaScript functions can be called from HTML code in response of any
particular event like page load,page unload,button click etc.
Code:
<html>
<head>
<title> calling function from html</tittle>
<script>
function welcome()
{
alert("Welcome students");
}
function goodbye()
{
alert("Bye");
}
</script>
</head>
<body onload="welcome()" onunload="goodbye()“>
</body>
</html>
FUNCTION CALLING ANOTHER FUNCTION:
In JavaScript we can call one function inside another
function.
<html>
<body>
<script>
function accept(s)
{
document.write(“your city:”+s);
}
function display()
{
accept(“mumbai”);
}
display();
</script>
</body>
</html>
THE RETURN STATEMENT
There are some situations when we want to return
some values from a function after performing some
operations. In such cases, we can make use of the
return statement in JavaScript.
A JavaScript function can have an
optional return statement.
function calcAddition(number1, number2)
{
return number1 + number2;
}
STRING
The JavaScript string is an object that represents a
sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The
syntax of creating string using string literal is given
below:
var stringname="string value";
Example:
<script>
var str="This is string literal";
document.write(str);
</script>
o/p:This is string literal
2) By string object (using new keyword)
The syntax of creating string object using new
keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of
string.
Let's see the example of creating string in JavaScript
by new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
o/p:hello javascript string
MANIPULATE STRING: JAVASCRIPT STRING
METHODS
JOINING A STRING
String concat(str) Method: The JavaScript
String concat(str) method concatenates or joins
two strings.
Syntax: s1.concat(s2);
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
o/p:javascript concat example
RETRIEVING A CHARACTER FROM GIVEN POSITION
JavaScript String charAt(index)
Method:each character in a string is an array
element that can be identified by its index.
The JavaScript String charAt() method returns
the character at the given index.
Syntax: string.charAt(index);
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
o/p:v
RETRIEVING A POSITION OF CHARACTER IN A STRING
JavaScript String indexOf(str) Method:The JavaScript String
indexOf(str) method returns the index position of the given string.
Syntax: string.indexOf(‘character’);
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
o/p:11
JavaScript String lastIndexOf(str) Method: The JavaScript
String lastIndexOf(str) method returns the last index position of the
given string
<script>
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
o/p: 16
DIVIDING STRING
JavaScript String split() Method:
Splits a String object into an array of strings by
separating the string into substrings.
string.split([separator], [limit]);
separator − Specifies the character to use for
separating the string. If separator is omitted, the
array returned contains one element consisting of the
entire string.
limit − Integer specifying a limit on the number of
splits to be found
EXAMPLE:
<html>
<head>
<script>
var str = 'Welcome to the javaTpoint.com'
var arr = str.split(" ", 3);
document.write(arr);
</script>
</head>
<body>
</body>
</html>
o/p: Welcome,to,the
COPYING A SUBSTRING
JavaScript String substring() Method
The JavaScript string substring() method fetch the
string on the basis of provided index and returns the
new sub string.
It works similar to the slice() method with a
difference that it doesn't accepts negative indexes.
This method doesn't make any change in the original
string.
Syntax:
string.substring(start,end)
Parameter:
start - It represents the position of the string from
where the fetching starts.
end - It is optional. It represents the position up to
which the string fetches.
EXAMPLE:
<script>
var str="Javatpoint";
document.writeln(str.substring(0,4));
</script>
Output:Java
STRING SUBSTR() METHOD
The JavaScript string substr() method fetch the part
of the given string and return the new string. The
number of characters to be fetched depends upon the
length provided with the method. This method doesn't
make any change in the original string.
Syntax:
string.substr(start,length)
Parameter:
start - It represents the position of the string from
where the fetching starts.
length - It is optional. It represents the number of
characters to fetch.
EXAMPLE:
<script>
var str="Javatpoint";
document.writeln(str.substr(0,4));
</script>
Output:
Java
slice() method is used to fetch the part of the string and returns
the new string.
It required to specify the index number as the start and end
parameters to fetch the part of the string. The index starts from
0.
Syntax: string.slice(start,end)
Parameter:
start - It represents the position of the string from where the
fetching starts.
end - It is optional. It represents the position up to which the
string fetches. In other words, the end parameter is not included.
<script>
var str = "Javatpoint";
document.writeln(str.slice(2,5));
</script>
o/p:
vat
CHANGING THE CASE OF STRING
JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns
the given string in lowercase letters.
Syntax: string. toLowerCase() ;
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
o/p:javascript tolowercase example
JavaScript String toUpperCase() Method
The JavaScript String toUpperCase() method
returns the given string in uppercase letters.
Syntax: string.toUppercase();
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
o/p:JAVASCRIPT TOUPPERCASE EXAMPLE
CONVERTING STRING TO NUMBER
JavaScript Number parseInt() method:
The JavaScript number parseInt() method parses a string
argument and converts it into an integer value. With string
argument, we can also provide radix argument to specify the
type of numeral system to be used.
Syntax:
Number.parseInt(string, radix)
Parameter:
string - It represents the string to be parsed.
<script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseInt(a)+"<br>");
document.writeln(Number.parseInt(b)+"<br>");
document.writeln(Number.parseInt(c)+"<br>");
document.writeln(Number.parseInt(d)+"<br>");
document.writeln(Number.parseInt(e));
</script>
o/p: 50 50 NaN 50 50
JavaScript Number parseFloat() method:
The JavaScript number parseFloat() method parses
a string argument and converts it into a floating point
number. It returns NaN, if the first character of given value
cannot be converted to a number.
Syntax:
Number.parseInt(string)
Parameter
string - It represents the string to be parsed.
EXAMPLE:
<script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseFloat(a)+"<br>");
document.writeln(Number.parseFloat(b)+"<br>");
document.writeln(Number.parseFloat(c)+"<br>");
document.writeln(Number.parseFloat(d)+"<br>");
document.writeln(Number.parseFloat(e));
</script>
o/p: 50 50.25 NaN 50 50.25
CONVERTING NUMBER TO STRING
This method returns a string representing the specified object.
The toString() method parses its first argument, and attempts to
return a string representation in the specified radix (base).
Syntax:
number.toString( [radix] )
Parameter Details:
radix −An integer between 2 and 36 specifying the base to
use for representing numeric values.
Return Value
Returns a string representing the specified Number object.
EXAMPLE:
<script>
var a=50;
var b=-50;
var c=50.25;
document.writeln(a.toString()+"<br>");
document.writeln(b.toString()+"<br>");
document.writeln(c.toString());
</script>
o/p:50 -50 50.25
FINDING A UNICODE OF CHARACTER-
CHARCODEAT()
The JavaScript string charCodeAt() method is used to
find out the Unicode value of a character at the specific
index in a string.
The index number starts from 0 and goes to n-1, where
n is the length of the string.
It returns NaN if the given index number is either a
negative number or it is greater than or equal to the
length of the string
Syntax:
string.charCodeAt(index)
Parameter:
index - It represent the position of a character.
EXAMPLE:
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
</script>
o/p:97
FROMCHARCODE()
JavaScript fromCharCode() method is used to
convert the Unicode values into characters.
It is a static method of the String object so the syntax
will remain always same.
Syntax: String.fromCharCode(n1, n2, ..., nX)
// use of fromCharCode() let string1 =
String.fromCharCode(72, 69, 76, 76, 79);
// printing the equivalent characters console.log(string1);
Output: // HELLO
QUESTIONS:
1. Differentiate between concat() and join()
methods of array object.
2. Write the use of chatAt() and indexof() with
syntax and example.
3. Write a JavaScript that will replace following
specified value with another value in string.
String = “I will fail” Replace “fail” by “pass”.