You are on page 1of 99

CLIENT SIDE SCRIPTING

LANGUAGE
(22519)

By
Mrs. Jyotsna Joshi
• Aim: Develop Dynamic Web pages
using JavaScript.
• Course Outcome: Implements Arrays
and Functions in JavaScript.
• Unit Outcomes:
1. Create array to solve given problem
2. Perform String Manipulations operations
3. Develop JavaScript to convert given Unicode
to Character form.
Chapter 2
Array, Functions and Strings
TOPICS
• Arrays
• Declaring and Allocating
Array
• Types of Array
• Array Methods
• Array Attributes
Arrays
• Array is a Object used to store
collection of items.
• We can access array by referring to its
index value.
• The index value of 1st element is
zero.
• Array in javascript can hold different
elements such as Numbers, Strings
and Booleans in single array.
Declaring an Array
• Three ways to create an array:
1. By array literal
2. By creating instance of Array directly (using
new keyword)
3. By using an Array constructor (using new
keyword)
Declaring and Allocating Arrays

• JavaScript arrays are Array objects.


• Creating new objects using the new operator is
known as creating an instance or instantiating an
object
• Operator newis known as the dynamic memory
allocation operator.
1. Array Literal

var array_name=[“a”,”b”,”c”] ;
2. Creating instance of Array using new
keyword

//declaration
•let car = new Array(3);
•//initialization
•car[0]=”Swift”;
•car[1]=”WagonR”;
•car[2]=”i10”;
3. Uisng an Array Constructor

let car = new Array(“swift”,”wagonR”,”i10”);


Types of Array
• Associative Array
• Index Array
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 loses the attributes and
methods of Array. The length attribute has no effect because the
variable is not longer of Array type
An associative array is declared or dynamically created

We can create it by assigning a literal to a variable


Object.keys() function –
The Object.keys() is an inbuilt function in javascript
which can be used to get all the keys of array.
Syntax - Object.keys(obj)
<script>
var marks={"OSY":"65","STE":"77","CSS":"50"};

var keys = Object.keys(marks);

document.write("Keys are listed below <br>");

document.write(keys);
</script>
<script>
var marks={"OSY":"65","STE":"77","CSS":"50"};

var keys = Object.keys(marks);

document.write("Keys are listed below <br>");


document.write(keys);

document.write("<br>");
for (var i in marks)
{
document.write(marks[i]);
}
</script>
Index Array

Array elements are accessed using their index


number:
var ary = [“ A” , “ B” , “ C” , “ D” , “ E” , “
F” ];
document.write(ary[4]);
//output:

//output:
Using Loop
For Loop
For in Loop
Array Methods
• Concat
• Join
• Push
• Pop
• UnShift
• Shift
• Sort
• Slice
• Splice
Array Methods
Adding an Array Element

By push() By unshift()
• it adds one or more • it adds one or more
elements at the end elements in the
of an array beginning of an array

Syntax – Syntax –

array.push(e1,e2....en) array.unshift(e1,e2,....,en)
Push method
<script>
var fruits=new Array("Apple","Plums","Mango");

document.write(fruits);
document.write("<br>");

fruits.push("Orange");
fruits.push("Pineapple");

document.write(fruits);
</script>
Unshift method
<script>
var colors=new Array("Red","Yellow","Blue");

document.write(colors);
document.write("<br>");

colors.unshift("Green");
colors.unshift("White");

document.write(colors);
</script>
Sorting an Array Elements
• It returns the element of the given array in a
sorted order.
• Syntax –
array.sort(compareFunction)
• compareFunction - It is optional. It represents a
function that provides an alternative sort order.
Sorting of Numeric values
<script>
var num=new Array(3,9,5,4);

document.write(num + "<br>");

num.sort();

document.write(num);

</script>
Sorting of String values

<script>
var colors=new Array("Red","Yellow","Blue");

document.write(colors + "<br>");

colors.sort();

document.write(colors);
</script>
Sorting of Numbers + Alphabets + String

<script>
var myarray=new Array(2,"hello","b","B",1);

document.write(myarray + "<br>");

myarray.sort();

document.write(myarray);
</script>
Compare Function

 Compare Function(a,b) < 0 = a then b

 Compare Function(a,b) > 0 = b then a

 Compare Function(a,b) = 0 = order of a and b


remains unchanged.
Ascending Array
<script>
var myarray=new Array(11,2,1,30,5);

document.write(myarray + "<br>");

function compare(a,b)
{
return a-b;
}

myarray.sort(compare);
document.write(myarray);
</script>
Descending Order

<script>
var myarray=new Array(11,2,1,30,5);
document.write(myarray + "<br>");

function compare(a,b)
{
return b-a;
}

myarray.sort(compare);
document.write(myarray);
</script>
Combining Array into String
join() - it joins all elements of an array into String.
This method doesn't make any change in the
original array
Syntax –
array.join(separator)
separator - It is optional. It represent the separator
used between array elements - /,-,* etc.

Return - a new string contains the array values with


specified separator.
<script>
var myarray=new Array("FY","SY","TY");
var s = myarray.join();

document.write("After join () ="+s);


</script>
<script>
var myarray=new Array("FY","SY","TY");
var s=myarray.join('-');
document.write(s);
</script>
concat() - method combines two or more arrays and
returns a new string. This method doesn't
make any change in the original array.
Syntax –
array.concat(arr1,arr2,....,arrn)
separator - It is optional. It represent the separator
used between array elements - /,-,* etc.

Return - A new array object that represents a joined


array..
<script>
var myarray=new Array("C","C++","JAVA");

document.write("Before concat () ="+myarray);

var s = myarray.concat("PHP");

document.write("<br> After concat () ="+s);


</script>
Changing elements of an Array

1) shift() 2) pop()
• it removes first • it removes last
element of an array elements of an array

Syntax – Syntax –

array.shift() array.pop()
<script>
var myarray=new Array("C","C++","JAVA");

document.write(myarray);

myarray.shift();

document.write("<br>After ="+myarray);

</script>
<script>

var myarray=new Array("C","C++","JAVA");

document.write(myarray);

myarray.pop();

document.write("<br>After ="+myarray);

</script>
Tip: The push() and pop() methods runs faster than unshift() and shift().
Because push() and pop() methods simply add and remove elements at
the end of an array therefore the elements do not move, whereas unshift()
and shift() add and remove elements at the beginning of the array that
require re-indexing of whole array.
3) splice() - It add/remove elements to/from the
given array.
• It returns the removed elements from an
array.
• It modifies the original array
Syntax –
array.splice(start_index,delete_count,e1,e2,…,en)

It represents the It is optional. It It is optional. It


index from represents the represent the
where the number of elements to be
method start to elements to be inserted.
extract the removed.
elements.
Adding element
<script>

var myarray=new Array("C","C++","JAVA");

document.write(myarray);

myarray.splice(1,0,"PHP","Python");

document.write("<br>After ="+myarray);

</script>
Deleting element
<script>
var myarray=new Array("C","C++","JAVA");

document.write(myarray);

var result=myarray.splice(2);

document.write("<br>After ="+myarray);

document.write("<br>Result ="+result);
</script>
<script>
var myarray=new Array("C","C++","JAVA","VB");
No of elements
document.write(myarray); index need to remove

Element need to
var result=myarray.splice(2,1,"PHP"); add

document.write("<br>After ="+myarray);

document.write("<br>Result ="+result);

</script>
Extracting a Portion of an Array
• If you want to extract out a portion of an array
(i.e. subarray) but keep the original array intact
you can use the slice() method.
arr.slice(startIndex, endIndex)

var fruits = ["Apple", "Banana", "Mango", "Orange",


"Papaya"];
var subarr = fruits.slice(1, 3);
document.write(subarr); // Prints: Banana,Mango
If endIndex parameter is omitted, all elements to the end
of the array are extracted.
filter()
• The filter() method creates a new array
filled with elements that pass a test
provided by a function.
• Does not change the original array.

const age = [22, 4, 9, 16, 25,6];


const above10 = age.filter(myFunction);
function myFunction(value) {
return value > 10;
}
map()
• map() creates a new array from calling a
function for evey array element.
• does not change the original array.

const num1 = [55, 4, 9, 12, 25];


const num2 = num1.map(myFunction);
function myFunction(value) {
return value * 2;
}
some()
• The some() method check if some array
values pass a test.
• This example check if some array values
are larger than 18:
const numbers = [45, 4, 9, 16, 25];
let someOver18 =
numbers.some(myFunction);
function myFunction(value) {
return value > 18;
}
Array Attributes
• length
• indexOf
• typeOf
• Changing Elements
• Deleting Elements
LENGTH…..
• The length property provides an easy way
to append new elements to an array
without using the push() method.
INDEXOF
Typeof
TYPE OF
A common question is: How do I know if a variable
is an array? The problem is that the JavaScript
operator typeof returns "object":
Changing Elements
Deleting Elements
delete array[number]

• Removes the element, but leaves a hole in the


numbering.

array.splice(number, 1)

• Removes the element and renumbers


all the following elements.
Deleting Elements
Ary = ['a', 'b', 'c', 'd‘ ,‘e’];
delete Ary[1];
['a',undefined, 'c', 'd‘ ,’e’]
Functions
Function
• Defining a function
• Writing a function
• Adding an argument
• Scope of variable and arguments
• Calling Function – with argument / without
argument
• Function Expression
• JS Arrow Function
Function
• It is a sub-program designed to perform particular
task
• Functions are executed when they are called
(invoking function)
• Values can be passed to function (argument
passing)
• Function can return value
• Built in functions –
– Write()
– Prompt()
– Alert()
– Confirm()
Defining a Function
Syntax –

Keyword arguments

function function_name(parameter-list)
{
Statements
}
In Javascript function calling is by using function
name with parenthesis
Writing a Function

<script>
function disp()
{
document.write("Display Function");

}
</script>
Calling a Function
• In <head> tag
<html>
<head> <script>
function disp()
{ document.write("Good Morning");
}
disp();
</script> </head>
<body>
<h3> Welcome </h3>
</body></html>
• In <body> tag
<html> <head> <script>
function disp()
{
document.write("Good Morning");
}
</script> </head>
<body>
<h3> Welcome </h3>
<script> disp(); </script>
</body></html>
<script>
function print()
{
var s=prompt("Enter your name");

document.write("Welcome "+s);
}

print();
</script>
• The function confirm shows a modal window
with a question and two buttons: OK and Cancel.
• It returns true for OK and false for Cancel/Esc
• Syntax - result = confirm(question);
<script>
var txt;
var r = confirm("Do you want to continue");
if (r == true)
{
document.write("You pressed OK!");
}
else
{
document.write("You pressed Cancel!");
}
</script>
Returning from Function
• Keyword – return()
• This statement should be the last statement in a
function.
<script>
function calculate()
{
var i=10;
var j=20;
return(i*j);
}
var r = calculate();
document.write(r);
</script>
Adding an argument
• Arguments are variables declared within parentheses
• A function can take multiple parameters separated by
comma.
parameter
<script>
function print(s)
{
document.write("Welcome "+s);
value
}
print("Jhon");
</script>
<script>
addition(90,5);
function addition(i,j)
subtract(55,2);
{
</script>
var r=i+j;
document.write(r + "<br>");

function subtract(i,j)
{
var r=i-j;
document.write(r);
}
Scope of variable
Local Scope – <script>
– Variables declared within var g="Global";
function
– They are accessible within function display()
function only. {
var i="Local";
document.write(i + "<br>");
Global Scope – document.write(g);
– Variables declared outside
function }
– Available through all parts
of script display();

</script>
Function calling another function
<script>
function accept()
{
var s=prompt("Enter Your Name");

return(s);
}
function show()
{
var r=accept();
document.write("Welcome "+r);
}
show();
Function Expressions
• In Javascript, functions can also be defined as
expressions. For example,
• // program to find the square of a number
• // function is declared inside the variable
let x = function (num) { return num * num };
console.log(x(4));
// can be used as variable value for other variables
let y = x(3);
console.log(y);
The function above is called an anonymous
function.
• Note: In ES2015, JavaScript expressions
are written as arrow functions.
JavaScript Arrow Function

• Arrow functions were introduced in ES6.


• Arrow functions allow us to write shorter
function syntax:

Eg.1
let myFunction = (a, b) => a * b;
Eg.2 without Arrow function
hello = function() {
return "Hello World!";
}

• With Arrow Function:


hello = () => {
return "Hello World!";
}
Compare Alert(), Prompt() and Confirm()
STRING
String Functions
• charAt()
• concat()
• indexOf()
• lastIndexOf()
• replace()
• search()
• substr()
• substring()
• toLowerCase()
• toUpperCase()
String
Literals – Object –
– var s = “SVCP”; – var s=new
String(“SVCP”);

<script>
var s="SVCP";
document.write("By Literal ="+s);

var o="Computer";
document.write("<br>By Object ="+o);

</script>
Joining a String
Using Concatenation (+) Operator –

Syntax – string1+string2

<script>
var s1="TY";

var s2="CM";

document.write(s1+s2);
</script>
Using concat() Method –

Syntax – string.concat(v1,v2,..,vn);

<script>
var s1="Welcome to";

document.write(s1.concat("India"));
</script>
Retrieving a Character from given
Position
chatAt() – Returns the character from the specified
index.
Syntax – string.charAt(index);

An integer between 0 and 1 less than the length of the string.

<script>
var str="Good Day";

document.writeln(str.charAt(5));
</script>
Retrieving a Position of Character in a
String
indexOf() – it is used to find the location of a substring
in a string

Syntax – string.indexOf(substring, [start_position]);

Substring -It is the substring that you want to find within string.

start_position -Optional - It is the position in string where the search will start.
The first position in string is 0. If this parameter is not provided, the search
will start at the beginning of string and the full string will be searched.
<script>
var str="Hello World";
document.writeln(str.indexOf(‘o’));
</script> It will return the first occurrence of ‘o’

H e l l o W o r l d

0 1 2 3 4 5 6 7 8 9 10

<script>
var str="Hello World";
document.writeln(str.indexOf('o',5));
</script> It will return the first occurrence of ‘o’
after specified index position
lastIndexOf() - returns the last occurrence of a
substring in a string.

Syntax – string.lastIndexOf(substr, [start])

The value of start can be between 0 to the length -1


of string.
<script>
var str="Hello World";

document.write("First Position ="+str.indexOf("o"));

document.write("Last Position ="+str.lastIndexOf("o"));

</script>
H e l l o W o r l d

0 1 2 3 4 5 6 7 8 9 10

First Position =4
Last Position =7
search() – it searches the string for a specified
value and returns the position of the if match
found
Syntax – string.search(word)

<script>
var str="Hello World";

document.write("<br>Position ="+str.search("World"));

</script>
Diving Text
split() – split the string into array of strings by
separating it into substrings using a specified
separator.

Syntax - string.split(separator, limit)

If the separator is an empty string (‘ ’) then every


character of the string is separated by commas.

The limit specifies the upper limit on the number of


splits to be found in the given string.
<script>
var str = "Hello! Welcome all";
document.write("Result ="+str.split(''));
</script>

Result =H,e,l,l,o,!, ,W,e,l,c,o,m,e, ,a,l,l

<script>
var str = "Hello! Welcome all";
document.write("Result ="+str.split('!'));
</script>

Result =Hello, Welcome all


<script>
var str = "Hello! Welcome all";
document.write("Result ="+str.split('',2));
</script>
Result =H,e

<script>
var str = "Hello! Welcome all";
document.write("Result ="+str.split('!',1));
</script>

Result =Hello
Replace Text
replace() -method replaces a specified value with
another value in a string:
<script>
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft",
"Google");
</script>

The replace() method does not change the string it is called on.
The replace() method returns a new string.
The replace() method replaces only the first match
By default, the replace() method is case sensitive
Copying a sub-string
substring() – method returns the part of the string
between the start and end indexes, or to the end of
the string.

Syntax – string.substring(start, end)

start: The position where to start the extraction, index starting


from 0.
end: The position (up to, but not including) where to end the
extraction (optional).
<script>
var str="Javascript";
document.write("<br>Result ="+str.substring(0));
document.write("<br>Rresult ="+str.substring(0,7));

</script>
Result =Javascript
Result =Javascr

J A V A S C R I P T

0 1 2 3 4 5 6 7 8 9
substr() - extracts parts of a string, beginning at
the character at the specified position, and returns
the specified number of characters.

Syntax - string.substr(start, length)

start: The position where to start the extraction, index


starting from 0.

length: The number of characters to extract (optional).


<script>
var str="Javascript";
document.write("<br>Result ="+str.substr(1,7));
</script>
Rresult =avascri
J A V A S C R I P T
0 1 2 3 4 5 6 7 8 9

Difference –
• 2nd argument to substring is the index to stop at (but not
include),
• 2nd argument to substr is the maximum length to return.
• Moreover, substr() accepts a negative starting position as
an offset from the end of the string. substring() does not.
Convert String -> Number
• parseInt()- it parses a string and returns a whole
number.
• parseFloat()- it parses a string and returns a
number.
• Number () – it converts the string to a number. If
the string value is number then it will convert
otherwise will return NaN as output.
<script>
var i="15 years";
document.write("<br>Parse Int="+parseInt(i));
var j="3.14f";
document.write("<br>Parse Float="+parseFloat(j));
var k="25.5";
document.write("<br>Number Result 1="+Number(k));
var l="3.14f";
document.write("<br>Number Result 2="+Number(l));
</script>
Parse Int=15
Parse Float=3.14
Number Result 1=25.5
Number Result 2=NaN
Convert Number -> String

• toString()- this function is used to convert


number (Interger and Decimal numbers) to
string.
<script>
var i=67;
var r=i.toString();
document.write("<br>String="+r);
document.write("<br>String="+r.concat("Value"));
</script>
String=67
String=67Value
Changing the Case
• toUpperCase() - returns the string with all of its
characters converted to uppercase.
Syntax – string.toUpperCase();
• toLowerCase()- returns the string with all of its
characters converted to lowercase.
Syntax – string.toLowerCase();

<script>
var str1="Hello World";
document.write("<br>Upper Case ="+str1.toUpperCase());
document.write("<br>Lower Case ="+str1.toLowerCase());
</script>
Upper Case =HELLO WORLD
Lower Case =hello world
Unicode of a Character
• charCodeAt() –returns the Unicode value of the
character at specified position.
Syntax – string.charCodeAt(x)

• fromCharCode() –convert a given Unicode number


into a character.
Syntax - String.fromCharCode(n1, n2, ..., nX)
<script>
var str1="Apple";
document.write("<br>Unicode ="+str1.charCodeAt(0));
</script>
Unicode =65
<script>
document.write("<br>Char ="+String.fromCharCode(97));
document.write("<br>Char
="+String.fromCharCode(65,71,72,115));
</script>
Char =a
Char =AGHs

You might also like