Professional Documents
Culture Documents
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
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
document.write(keys);
</script>
<script>
var marks={"OSY":"65","STE":"77","CSS":"50"};
document.write("<br>");
for (var i in marks)
{
document.write(marks[i]);
}
</script>
Index Array
//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
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.
var s = myarray.concat("PHP");
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>
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)
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)
array.splice(number, 1)
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
Eg.1
let myFunction = (a, b) => a * b;
Eg.2 without Arrow function
hello = function() {
return "Hello World!";
}
<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);
<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
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.
</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.
<script>
var str = "Hello! Welcome all";
document.write("Result ="+str.split('!'));
</script>
<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.
</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.
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
<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)