Javascript
Javascript
JavaScript1
Mamatha
BMSCE, ISE 1
Why Study JavaScript?
BMSCE, ISE 2
What can JavaScript do ?
BMSCE, ISE 3
Three parts of Javascript
• Core JavaScript
Includes operators, expressions, statements and
subprograms (heart of language)
• Client-side JavaScript
A collection of objects that support control of browser
and interactions with user. Eg: with javascript, an HTML
document can be made to respond to user inputs such
as mouse clicks and keyboard use.
• Server-side JavaScript
A collection of objects that make the language useful on
a web server. For eg: to support communication with a
DBMS, file operations and networking.
BMSCE, ISE 4
JavaScript Reserved words
BMSCE, ISE 5
First JavaScript Program
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
document.write("First JavaScript Program in
Web Technologies");
//-->
</script>
</body>
</html>
Sample I/O:
BMSCE, ISE 6
JavaScript: Where To Place?
Two different ways to embed JavaScript in an HTML Document:
1. Explicit Embedding
2. Implicit Embedding : External file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"> program1.js
document.write("JavaScript inside document.write
Head tag","<br />"); ("JavaScript inside
</script> </head> External file","<br />");
<body>
<script type="text/javascript">
document.write("JavaScript inside
Body tag","<br />");
</script>
<script src = program1.js"> Sample I/O:
</script>
</body>
</html>
BMSCE, ISE 8
JavaScript Data Types
JavaScript variables can hold many primitive data types:
Numbers,
Strings,
Boolean,
Undefined : If a variable is explicitly declared, but not assigned a
value, it has value undefined.
BMSCE, ISE 9
JavaScript functions for string manipulation
1. length: a value which holds the number of characters
2. charAt(index): function returns the character which is at position
index in the string
3. concat(“string” [, “string” [, . . . “string”]]):
4. indexOf(“search” [,offset]): returns the position in string object of
the parameter
5. lastIndexOf(“search” [,offset]): searches backwards of indexOf
6. Split(separator [,limit]): function breaks the string apart whenever
it encounters the character passed in as the first parameter. Limit
is an integer value indicating how many of pieces are to be stored
in array
7. Substr(index [,length])
8. toLowerCase()
9. toUpperCase()
10. Substring(index [,index2]): similar to substr but not includes the
char at index2.
BMSCE, ISE 10
String Methods : Example
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
b m s c o l l e g e
BMSCE, ISE 11
Example to find length of string:
<!DOCTYPE html>
<html>
<head>
<title> Exercise to find length of string</title>
</head>
<body> Sample I/O:
<script type="text/javascript">
<!--
var str="Bangalore";
var len=str.length;
document.write("Length of string
\"Bangalore\" is :" ,len,"<br />");
//-->
</script>
</body></html>
BMSCE, ISE 12
Example for charAt() function:
<!DOCTYPE html> Sample I/O:
<html>
<head>
<title> Exercise for charAt function of
string</title>
</head>
<body>
<script type="text/javascript">
<!--
var you=prompt("Enter your name:", " ");
document.write("The character at position in your
name is :" , you.charAt(4));
//-->
</script>
BMSCE, ISE 13
</body></html>
Example for substr and substring functions:
<!DOCTYPE html>
<html>
<head>
<title> Exercise for substr and substring functions of string</title>
</head>
<body>
<script type="text/javascript">
<!--
var str="Bangalore";
document.write("substr function on string Bangalore (1,4) is: "+str.substr(1,4)+"<br />");
document.write("substring function on string Bangalore (1,4) is: "+str.substring(1,4));
//-->
</script>
</body></html>
Sample I/O:
BMSCE, ISE 14
Example for split function:
<!DOCTYPE html>
<html>
<head>
<title> Exercise for split function of string</title>
</head>
<body>
<script type="text/javascript">
<!--
var str="Bangalore one today";
document.write("split function on string Bangalore one today with Blank as separator is:
"+str.split(" ") +"<br />");
document.write("split function on string Bangalore one today is: "+str.split(""));
//--></script>
</body></html>
Sample I/O:
BMSCE, ISE 15
Screen Output and Keyboard Input:
• The alert() method displays an alert box with a specified message and
an OK/Close button.
• An alert box is often used if you want to make sure information
comes through to the user.
BMSCE, ISE 16
Example Program : alert
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
alert("Welcome to BMSCE");
</script> Sample I/O:
</body>
</html>
BMSCE, ISE 17
Screen Output method2:confirm()
method
BMSCE, ISE 18
Example Program : confirm
<!DOCTYPE html>
<html>
<body>
<script>
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
alert(txt);
} else {
txt = "You pressed Cancel!";
alert(txt);
}
</script>
</body>
</html>
BMSCE, ISE 19
Example program output1
BMSCE, ISE 20
Example program output2
BMSCE, ISE 21
Screen Output method3:
prompt() method
BMSCE, ISE 22
Example program: Prompt
<!DOCTYPE html>
<html>
<body> Sample I/O:
<script>
var txt;
var r = prompt("Enter your name:");
if (r == true) {
txt = "You pressed OK!";
alert(txt);
} else {
txt = "You pressed Cancel!";
alert(txt);
}
</script>
</body>
</html>
BMSCE, ISE 23
Dialog Windows
Confirm registration=confirm(
Window "Do You want to register for 8th
Sem ?");
BMSCE, ISE 24
Keyboard Input
BMSCE, ISE 25
<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The write() Method</h2>
<p>Write some text directly to the HTML
output:</p>
<script>
document.write("Hello World!");
</script>
<h2>The Lorem Ipsum Passage</h2>
<p>This is Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do Sample I/O:
eiusmod tempor incididunt ut labore et
dolore magna aliqua.</p>
</body>
</html>
BMSCE, ISE 26
<!DOCTYPE html>
<html> <body>
<h1>The Document Object</h1>
<h2>The write() Method</h2>
<p>Write some HTML elements directly to
the HTML output:</p>
<script>
document.write("<h2>Hello
World!</h2><p>Have a nice day!</p>");
</script>
<h2>The Lorem Ipsum Passage</h2>
<p>
This is Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do eiusmod Sample I/O:
tempor incididunt ut labore et dolore magna
aliqua.
</body>
</html>
BMSCE, ISE 27
Selection Statements:
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is
true
} else {
block of code to be executed if the condition1 is false and condition2 is
false
}
BMSCE, ISE 28
JavaScript script To find Largest of
three numbers
<!DOCTYPE html>
<html> <body>
<script type="text/javascript">
{
var n1=Number(prompt("Enter number 1: "));
var n2=Number(prompt("Enter number 2: "));
var n3=Number(prompt("Enter number 3: "));
if (n1>n2 && n1>n3)
alert(n1+" is largest");
else if(n2>n3)
alert(n2+" is largest");
else
alert(n3+" is largest");
}
</script>
</body></html>
BMSCE, ISE 29
Sample I/O:
BMSCE, ISE 30
Javascript Switch Statement
• Use the switch statement to select one of many blocks of code to be
executed.
• General Syntax:
switch(expression) {
case n1:
code block
break;
case n2:
code block
break;
default:
default code block
}
This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
BMSCE, ISE 31
Example1 for Switch Statement
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
Sample I/O:
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</body> BMSCE, ISE 32
</html>
Example2 for Switch Statement to get the day of the week
<!DOCTYPE html> based on a day number
<html>
<body>
<script>
var day=4;
var dayName;
switch(day) Sample I/O:
{
case 1:dayName='Sunday'; break;
case 2:dayName='Monday'; break;
case 3:dayName='Tuesday'; break;
case 4:dayName='Wednesday'; break;
case 5:dayName='Thursday'; break;
case 6:dayName='Friday'; break;
case 7:dayName='Saturday'; break;
default:
dayName='Invalid day';
}
document.write(dayName);
</script>
</body>
</html>
BMSCE, ISE 33
JavaScript Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
BMSCE, ISE 34
Example1 program: // remainder
Arithmetic operators document.write('x % y = ', x % y, '<br />'); // 2
BMSCE, ISE 36
Example2 for Arithmetic Operators
<!DOCTYPE html>
<html> <body><script> Sample I/O:
var a1=40; var b1=25;
//addition
document.writeln('a1+b1 = ', a1+b1,"<br />");
//subtraction
document.writeln('a1-b1 = ', a1-b1,"<br />");
//multiplication
document.writeln('a1*b1 = ', a1*b1,"<br />");
//division
document.writeln('a1/b1 = ', a1/b1,"<br />");
//remainder
document.writeln('a1%b1 = ', a1%b1,"<br />");
//increment
document.writeln('++a1 = ', ++a1,"<br />");// a1 is now 41
document.writeln('a1++ = ',a1++,"<br />");//prints 41 and then increased to 42
document.writeln('a1 = ',a1,"<br />");// 42
//decrement
document.writeln('--a1 = ', --a1,"<br />");// a1 is now 41
document.writeln('a1-- = ',a1--,"<br />");//prints 41 and then decreased to 40
document.writeln('a1 = ',a1,"<br />");// 40
</script> </body></html> BMSCE, ISE 37
JavaScript Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
BMSCE, ISE 38
Example program for Assignment operators
<!DOCTYPE html> Sample I/O:
<html>
<head>
<title> Javascript Assignment Operators</title>
</head>
<body>
<h1> Assignment Operations </h1>
<script>
var a = 10, Total = 24;
BMSCE, ISE 39
JavaScript Comparison and Logical Operators
Operator Description
== equal to (“4” == 4 returns true)
=== equal value and equal type (“4” === 4
returns false)
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
BMSCE, ISE 40
Example program1 for Comparison and Logical
operators
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Comparison and Logical Operators </title>
</head>
<body>
<h1>Performing Comparison and logical Operations </h1>
<script>
var a = 32, b = 54;
document.write("Result of " + a +" Greater than " + b +" is = " + (a > b) + "<br />");
document.write("Result of " + a +' Greater than or Equal to ' + b +" is = " + (a >= b) + "<br />");
document.write("Result of " + a +' Less than or Equal to ' + b +" is = " + (a <= b) + "<br />");
document.write("Result of " + a +' Less than ' + b +" is = " + (a < b) + "<br />");
document.write("Result of " + a +' Equal to ' + b +" is = " + (a ==b ) + "<br />");
document.write("Result of " + a +' Not Equal to ' + b +" is = " + (a !=b ) + "<br />");
var i = 0, j=2, k=3, l=8;
document.write(Boolean(i&&j&&k)+ "<br />");
document.write(Boolean(j&&k&&l));
</script>
</body>
</html>
BMSCE, ISE 41
Sample I/O:
BMSCE, ISE 42
Example2 for Comparison and Logical Operators
<!DOCTYPE html>
<html> <body> <script> Sample I/O:
//equal operator
document.write(3 == '3');document.write("<br />");//true
document.write(3 == 3);document.write("<br />");//true
// not equal operator
document.write(3 != 2);document.write("<br />");//true
document.write('wt' != 'WT');document.write("<br />");//true
//strict equal operator
document.write(3 === 3);document.write("<br />");//true
document.write(3 === '3');document.write("<br />");//false
//strict not equal operator
document.write( 3 !== '3');document.write("<br />");//true
document.write( 3 !== 3);document.write("<br />");//false
var x = 5, y = 3;
res = (x < 6) && (y < 5); // true
document.write(res);document.write("<br />");
res = (x < 3) && (y < 5); // false
document.write(res);
</script>
</body>
</html> BMSCE, ISE 43
Loop statements
BMSCE, ISE 44
The For Loop
Syntax
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Example:
for (i = 0; i < 3; i++) {
document.write("The number is " + i + "<br>”);
}
Output: The number is 0
The number is 1
The number is 2
BMSCE, ISE 45
To display table of numbers from 4 to 16 their squares and cubes
Sample I/O:
<!DOCTYPE html>
<html> <head></head><body>
<script type="text/javascript">
document.write(" <table border=2>
<tr><th>Number</th><th>Squares<
/th> <th>Cubes </th></tr>");
for(i=4;i<17;i++){
document.write("<tr><td>"+ i +
"</td><td>"+(i*i)+"</td><td>"+(i*i
*i)+"</td></tr>");
}
document.write("</table>");
</script>
</body></html>
BMSCE, ISE 46
Javascript to print first 20 Fibonacci numbers:
<!DOCTYPE html>
<html> <head></head><body>
<script type="text/javascript">
var k=0, j=1;
document.write("Javascript script to print first 20 fibonacci numbers <br />");
//document.write(k+" " + j+" ");
for (i=1;i<21;i++)
{
r=k+j;
document.write(r+ " ");
k=j; Sample I/O:
j=r;
}
</script>
</body></html>
BMSCE, ISE 47
The For/In Loop
JavaScript for/in statement loops through the properties of an object.
Example:
<!DOCTYPE html>
<html> <body>
<script type="text/javascript">
var person = {fName:“Vara", LName:“Prasad", age:55};
var x;
for (x in person) {
document.write(person[x]);
}
</script>
</body></html>
Output: VaraPrasad55
BMSCE, ISE 48
The While Loop
• Syntax
while (condition) {
code block to be executed
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript While Loop </title>
</head>
<body>
<h1>Example for While Loop </h1> Sample I/O:
<script type="text/javascript">
var i = 0;
while (i < 5) {
document.write("The number is " + i +"<br/>");
i++;
} BMSCE, ISE 49
</script>
The Do/While Loop Output:
• Syntax
do {
code block to be executed
} while (condition);
Example:
<script type="text/javascript">
var i =10;
do {
document.write("The number is " + i+"<br/>");
i++;
} while (i < 20);
</script>
BMSCE, ISE 50
Web Technologies
JavaScript2
(Arrays, Functions)
Mamatha
BMSCE, ISE 51
JavaScript: Arrays
BMSCE, ISE 52
JavaScript Arrays : Array object creation
Can create an array using either
1.An array initializer (array literal) or
2.Array constructor
An array initializer
// an array with 5 elements
var myArray1 = [1,3,5,7,9,”eight”, 6];
Array constructor
// an array with 5 elements
var myArray2 = new Array(1,3,5,7,9, “eight”, 6);
// an empty array of length 100
var myArray3 = new Array(100);
// an empty array of length 0
var myArray4 = new Array();
BMSCE, ISE 53
JavaScript: Arrays
var mobile = [“Samsung”, “Motorola”, ”Nokia”];
OR
var mobile = new Array(“Samsung”, “Motorola”, ”Nokia”);
OR
var mobile = new Array(3);
mobile[0]=“Samsung”; mobile[1]=“Motorola”; mobile[2]=“Nokia”;
L1=mobile.length; //L1 is 3
mobile[3]=“HTC”;
L2=mobile.length; //L2 is 4
//Two dimensional array
var a=[[2,4,6],[1,3,5],[10,20,30]];
BMSCE, ISE 54
Example for JavaScript length property:
<!DOCTYPE html>
<html>
<body> Sample I/O:
<h1>JavaScript Arrays</h1>
<h2>The length Property</h2>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Mango"];
let size = fruits.length;
document.getElementById("demo").innerHTML = size;
</script>
</body>
</html>
BMSCE, ISE 55
Example for Array Methods
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd
for (var col = 0; col <=2; col++)
"> document.write(nested_array[row][col],
<!-- nested_arrays.html
" ");
An example illustrate an array of arrays
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
document.write("<br />");
<head> <title> Array of arrays </title> }
</head> // -->
<body> </script>
<script type = "text/javascript"> </body>
<!-- </html>
// Create an array object with three arrays as its
elements
var nested_array = [[2, 4, 6],
[1, 3, 5],
[10, 20, 30]
Sample I/O:
];
// Display the elements of nested_list
for (var row = 0; row <= 2; row++) {
document.write("Row ", row, ": ");
BMSCE, ISE 56
Program:To find the number of negative values, zeros and values
greater than Zeros in the given array
<body> <script type="text/javascript">
var list = [2, 10, -4, 0, 8,-6,0, 21]; Sample I/O:
var i,pos=0,neg=0,zeros=0;
document.write("Elements of Array","<br />");
for(i=0;i<list.length;i++)
document.write(list[i]+" ");
document.write("<br /><br />");
for(i=0;i<list.length;i++) {
if(Number(list[i])>0)
pos++;
else if(Number(list[i])<0)
neg++;
else
zeros++;
}
document.write("Number of Positive Numbers:",pos,"<br / >");
document.write("Number of Negative Numbers: ",neg,"<br / >");
document.write("Number of Zeros: ",zeros,"<br / >");
</script></body>
BMSCE, ISE 57
Program: insertion of an element
Sample I/O:
<script type="text/javascript">
var a = [2, 4, 6,10];
var i, last_index;
document.write("Elements of Array","<br />");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<br /><br />");
var n1=Number(prompt("Enter the number to be inserted: "));
last_index=a.length-1;
while(last_index>=0 && a[last_index] > n1){
a[last_index+1]=a[last_index];
last_index--;
}
a[last_index+1]=n1;
document.write("Elements of the Array after inserting ",n1,"<br />");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
BMSCE, ISE 58
Array Methods
var names = new Array[“Mary”,”Murray”,”Murphy”,”Max”]
...
var name_string = names.join(“:”)
join method,
reverse method,
sort method,
slice method,
push method,
pop method,
shift method,
unshift method. . .
BMSCE, ISE 59
JavaScript: Array Methods
INPUT list = [“WP” , ”DS” , “CO” ]
Method Calling the Method OUTPUT
BMSCE, ISE 61
Demo program1 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,3);
document.writeln(result);
</script>
Sample I/O:
</body>
</html>
BMSCE, ISE 62
Demo program2 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [23,56,87,32,75,13];
// Extracted array
var new_arr = arr.slice(2,4);
document.write(arr);
Sample I/O:
document.write("<br>");
document.write(new_arr);
</script>
</body>
</html>
BMSCE, ISE 63
Demo program3 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
// Extracted array
var arr = [23,56,87,32,75,13];
var new_arr = arr.slice();
document.write(arr,"<br />"); Sample I/O:
document.write(new_arr);
</script>
</body>
</html>
BMSCE, ISE 64
Demo program4 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
// Extracted array
var arr = [23,56,87,32,75,13];
var new_arr = arr.slice(-3);
document.write(arr,"<br />"); Sample I/O:
document.write(new_arr);
</script>
</body>
</html>
BMSCE, ISE 65
Demo program5 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
// Extracted array
var arr = [23,56,87,32,75,13];
var new_arr = arr.slice(2);
document.write(arr,"<br />"); Sample I/O:
document.write(new_arr);
</script>
</body>
</html>
BMSCE, ISE 66
JavaScript Slice method example:
<!DOCTYPE html>
<html><body>
<h1>JavaScript Arrays</h1>
<h2>The Slice method</h2>
<p>The slice() method returns a new array containing a portion of the original array, based
on the start and end index provided as arguments:</p>
<p id="demo"></p>
<script>
// Original Array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Case 1: Extract the first 3 elements of the array
const case1 = arr.slice(0, 3);
document.write("Case 1: First 3 Array Elements: ", case1 ,"<br />");
// Case 2: Extract the last 3 array elements
const case2 = arr.slice(-3);
document.write("Case 2: Last 3 Array Elements: ", case2,"<br />");
// Case 3: Extract elements from middle of array
const case3 = arr.slice(3, 7);
document.write("Case 3: Extract elements from middle: ", case3,"<br />");
BMSCE, ISE 67
// Case 4: Start index is greater than end index
const case4 = arr.slice(5, 2);
document.write("Case 4: Start index is greater than end index: ",
case4,"<br />");
// Case 9: Start and end index are
negative
// Case 5: Negative start index // and out of range
const case5 = arr.slice(-4, 9); const case9 = arr.slice(-15, -10);
document.write("Case 5: Negative start index: ", case5,"<br />"); document.write("Case 9: Start and
end index are negative"
// Case 6: Negative end index
+ " and out of range: ", case9);
const case6 = arr.slice(3, -2);
document.write("Case 6: Negative end index: ", case6,"<br />");
</script>
// Case 7: Only start index is provided </body>
const case7 = arr.slice(5); </html>
document.write("Case 7: Only start index is provided: ", case7,"<br />");
BMSCE, ISE 68
Sample I/O:
BMSCE, ISE 69
JavaScript: Array Methods
Method Calling the Method OUTPUT
push list = [“WP” , ”DS” , “CO” ] res=4
res=list.push(“C++”); list=[“WP”,”DS”,”CO”,”C++”]
pop list = [“WP” , ”DS” , “CO” ] res=“CO”
res=list.pop(); list=[“WP”, “DS”]
Unshift list = [“WP” , ”DS” , “CO” ] res =4
(add) res=list.unshift(“C++”); list=[“C++”, “WP”,”DS”,”CO”]
BMSCE, ISE 70
Push method example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The Push method</h2>
<p>The Push method is used to add one or more elements to the end of an array:</p>
<p id="demo"></p>
<script>
var languages = ["JavaScript", "Python", "Java", "Lua"];
BMSCE, ISE 71
JavaScript Functions
General Syntax
function Name(parameter1, parameter2)
{
//function code
}
BMSCE, ISE 72
JavaScript Functions
<html> <head></head>
<body>
<script type="text/javascript">
var a,b,c;
a=10; b=20;
<!-- parameters.html
The params function and a test driver for it.
This example illustrates function parameters
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title> Parameters </title>
<script type = "text/javascript">
<!--
// Function params
// Parameters: two named parameters and one unnamed
// parameter, all numbers
// Returns: nothing
BMSCE, ISE 74
function params(a, b) {
document.write("Function params was passed ",
arguments.length, " parameter(s) <br />");
document.write("Parameter values are: <br />");
document.write("<br />");
}
// -->
</script>
</head>
BMSCE, ISE 75
<body>
<script type = "text/javascript">
// A text driver for params
params("Mozart");
params("Mozart", "Beethoven");
params("Mozart", "Beethoven", "Tchaikowsky");
</script>
</body>
</html>
BMSCE, ISE 76
Sample I/O:
BMSCE, ISE 77
Example:
<!DOCTYPE html>
<!-- medians.html
A function and a function tester
Illustrates array operations
-->
<html>
<head> <title> Median Computation </title>
<script type = "text/javascript">
<!--
/* Function median
Parameter: An array of numbers
Result: The median of the array
Return value: none
*/
BMSCE, ISE 78
function median(list) {
list.sort(function (a, b) {return a - b;});
if ((list_len % 2) == 1)
return list[Math.floor(list_len / 2)];
else
return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2);
} // end of function median
// -->
</script>
</head>
BMSCE, ISE 79
<body>
<script type = "text/javascript">
<!--
var my_list_1 = [8, 3, 9, 1, 4, 7];
var my_list_2 = [10, -2, 0, 5, 3, 1, 7];
var med = median(my_list_1);
document.write("Median of [", my_list_1, "] is: ", med,"<br />");
med = median(my_list_2);
document.write("Median of [", my_list_2, "] is: ", med, "<br />");
// -->
</script>
</body>
Sample I/O:
</html>
BMSCE, ISE 80
Test Your Knowledge
BMSCE, ISE 81
Test Your Knowledge: Answer
• Add FOR LOOP to the following program that output the numbers 1 3 5 7
9 with line breaks between each number.
<!DOCTYPE html>
<html> <head></head><body>
<script>
var i;
for(i=1;i<10;i=i+2)
document.write(i,"<br/>");
</script>
</body>
</html>
BMSCE, ISE 82
Test Your Knowledge
• Try to fix the following code to output 0 1 2 3 4
<!DOCTYPE html>
<html> <head></head> <body>
<script>
var i = 0;
do {
document.write( );
i= ;
}while ( );
</script>
</body></html>
BMSCE, ISE 83
Test Your Knowledge:Answer
BMSCE, ISE 84
Find the output of the following program:
<!DOCTYPE html>
<html> <head></head>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango”,
"Chikko"];
var citrus = fruits.slice(1, 3);
document.write(citrus+"</br>");
citrus = fruits.slice(1);
document.write(citrus+"</br>");
citrus = fruits.slice(-2);
document.write(citrus+"</br>");
</script>
</body>
</html>
BMSCE, ISE 85
Answer
<!DOCTYPE html>
<html> <head></head>
<body>
<script type= "text/javascript">
var fruits =
["Banana","Orange","Lemon","Apple","Mango","Chikko"];
Output: 2
BMSCE, ISE 87
Solution
<html> <head></head ><body> <script type="text/javascript">
function find(names) {
var count = 0, tmp, pattern1, pattern2;
while(names.length)
{
tmp = names.shift();
Sample I/O:
pattern1 = tmp.toLowerCase().slice(-2);
pattern2 = tmp.toLowerCase().slice(-1);
if( pattern1 =="ie" || pattern2 =="y" )
count++;
}
return count;
}
var list = ["Harish Gowda","Mary Gracie","Sandeep Varma","Archana Reddy"];
var count; count=find(list);
document.write("<br />",count, " names end with either 'ie' or 'y'");
document.write("<br />", list);
</script> </body></html> BMSCE, ISE 88
Test Your Knowledge
Write JavaScript function which accepts input from user a string and
prints the position of the leftmost vowel.
BMSCE, ISE 89
Solution
<html> <head></head ><body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
var find = 0,pos,i; var str=prompt("Enter the string: ");
str=str.toLowerCase();
for(i=0;i<str.length;i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
{
find=1; pos=i; break;
}
}
if(find)
document.write("Position of first vowel in the string ", str, " was ",(pos+1));
else
document.write("Vowel Not found");
return;
}
document.write("Function to find first vowel in a String","<br />");
firstvowel(); </script> </body> </html>
BMSCE, ISE 90
Sample I/O:
BMSCE, ISE 91
Question: Find the output generated by this program
<!DOCTYPE html> <html> <head></head>
<body>
<script type="text/javascript">
document.write("BMS College of Engineering, Bangalore");
alert("Welcome to BMSCE");
var registration=confirm("Do You want to register for 4th Sem ?");
if(registration){
name=prompt("Enter your name:");
if(name==“Manjunatha")
alert("Hello Manjunatha");
else
alert("You are not Manjunatha");
}
else
alert("Please Register later");
</script>
</body>
</html>
BMSCE, ISE 92
Sample I/O:
BMSCE, ISE 93
Characteristics of Array objects:
• Length of an array is both read and write accessible through the ‘length’
property, which is created for every array object by the Array constructor.
• Lowest index of every array is zero.
Example program:
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
BMSCE, ISE 95
Sample I/O:
BMSCE, ISE 96
Exercises:
BMSCE, ISE 97
Web Technologies
JavaScript2
(Pattern Matching Using Regular Expressions)
Mamatha
• What is Pattern ?
• Some specific substring in a given string
• Example: Strings having atleast one occurrence of two consecutive letter a: baacd,
dcbaaba, aabdc, cbdaa
• What is Regular Expression ?
• Expressing the general PATTERN format in short hand notation
• A regular expression is a sequence of characters that forms a search pattern.
• Example: Regular expression /aa/ identifies the pattern for occurrence of two
consecutive letter a
Code Output
<script type="text/javascript">
var str = "The rain in Bangalore stays mainly in the plain";
var result = str.match(/ain/);
document.write(result);
</script>
<!DOCTYPE html>
<html>
<body>
<script>
var str= "The rain in Bangalore stays mainly in the plain";
document.writeln(str.match(/ain/g));
</script>
</body> g Perform a global match (find all matches rather than stopping after the first match)
</html>
Note: ^ is circumflex
Example
Name Equivalent Pattern Matches
\d [0-9] A digit
\D [^0-9] Not a digit
<script type="text/javascript"> b
var str = "1b253M67s894";
var patt1 = /[^1-4]/;
var result = str.match(patt1);
document.write(result);
</script>
Quantifier Description
Pattern Description
/x*y+z?/ Matches the strings that begin with any number of x’s (including
zero), followed by one or more y’s, possibly followed by z
/\d+\.\d*/ Matches one or more digits followed by decimal point and
possibly more digits
<script type="text/javascript"> l
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /lo*/;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> l,looo,l,l,lo,l
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /lo*/g;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> 1
var str = "1, 100 or 1000?";
var patt1 = /10?/;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> 1,10,10
var str = "1, 100 or 1000?";
var patt1 = /10?/g;
var result = str.match(patt1);
document.write(result);
</script>
Pattern Description
Output:
BMS college of Engineering
BMS Institute of Engineering
Example:
var str="BMS:RV:PES";
var colleges=str.split(":");
document.write("<br />", str,"<br />",colleges);
Output:
BMS:RV:PES
BMS,RV,PES
Example:
var str = "BMS college of Engineering";
var matches=str.match(/college/);
document.write("<br />", str,"<br />",matches);
Output:
BMS college of Engineering
college
20 April 2025 ISE, BMSCE 42
Write a program check validity of the USN of the format 1BM19IS followed by three digits.
Example:
Valid: 1BM19IS065, 1bm19is999
Not Valid: 1BM18IS6 , 1BM17IS038, 1is16BM065
Note: Accept the USN from the user through textbox.
• Write a program using JavaScript to accept a value in the variable with name time. If time value is
less than 10, display "Good morning" message, if time value is less than 18 display "Good day"
message, otherwise a "Good evening".
• Show the implementation using both If-else statement and also using switch statement
BMSCE, ISE 47
Exercise2:
Write Javascript program to insert the numbers into the existing
array which maintains sorting order.
Example: If the input array a=[2,4,6,10] then after inserting 1 and 8
the same array should be modified to contain a=[1,2,4,6,8,10].
Note: Should not use any temporary array.
BMSCE, ISE 48
Exercise3:
JavaScript program to remove all Zeros in the given array
Example INPUT list = [2, 0, 0, 4]
OUTPUT list = [2,4]
BMSCE, ISE 49
Exercise4:Which of the following solution is Better ?
Solution 1 last=a.pop();
a.pop(); a.pop();a.push(last);
Solution 2 for(i=0; i < a.length ; i++)
Write JS program to remove {
all Zeros in the given array. tmp = a[i];
Example: if( tmp !== 0 )
INPUT a = [2, 0, 0, 4] {
OUTPUT a = [2,4] new_list.push(tmp);
}
}
a=new_list;
Solution 3 j=0;
for(i=0; i<a.length; i++ )
{
if (a[i] != 0)
a[j++] = a[i];
}
a.length=j;
BMSCE, ISE 50
Exercise5:
1. Write javaScript code to reverse a given number.
2. Write javaScript code to find median of the given array of
elements
3. Write javaScript code to find the average of each row in a given
matrix.
4. Write HTML files and JavaScript scripts for input of
line of text using prompt. Generate the output as the
words of the input text in alphabetical order.
5. Write a java script code to print the number with its
digits in reverse order.
BMSCE, ISE 51
Exercises:
1. JavaScript to find reverse of a number
<!DOCTYPE html> while (n>0)
<html> {
<head> rem = n % 10;
<title>JavaScript to Reverse a number rev = rev * 10 + rem ;
</title> n = Math.floor(n/10);
</head> }
document.write("The given number is : "
<body> +num+ " <br/> The reversed number is : "
<h1>Reverse a number </h1> +rev+ "\n");
<script type ="text/javascript"> </script>
var num = prompt("Enter the number to </body>
be reveresed :", " "); </html>
var n= num;
var rev = 0, rem;
BMSCE, ISE 52
Sample I/O:
BMSCE, ISE 53
Exercises:2. Words of input text are printed in
alphabetical orders
<!DOCTYPE html>
<html>
<head>
document.write("Given input is :
<title>JavaScript to print words of the input text, in "+words+"<br />");
alphabetical order </title>
// Sorting the input array using array.sort
</head>
<body>
const sortedWords = words.sort();
<h1>Print words of the input text, in alphabetical order
</h1>
//Getting the sorter array output
<script type ="text/javascript">
document.write("Sorted words are :
const words = [
"JavaScript",
"+sortedWords);
"Program", </script>
"to", </body>
"Sort", </html>
"Words",
"in",
"Alphabetical",
"Order",
];
BMSCE, ISE 54
Sample I/O:
BMSCE, ISE 55
Output: A table of numbers from 5 to 15 and their squares and cubes.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.1 modified </title>
<meta charset = "utf-8" />
</head> <body>
<script type = "text/javascript">
<!--
var number, square, cube;
document.write("Number, Square, Cube <br /><br />");
for (number = 5; number < 16; number++) {
square = number * number;
cube = number * square;
document.write(number + ", " + square + ", " +
cube + "<br />");
}
// -->
</script></body>
</html>
BMSCE, ISE 56
Sample I/O:
BMSCE, ISE 57
Exercise 4.1:Output: A table of numbers from 5 to 15 and
their squares and cubes, using alert.
<html> <head>
<script type = "text/javascript">
<!--
function alertTable() {
var result = "";
for (var i = 5; i <= 15; i++) {
result += i + " " + i*i + " " + i*i*i + "\n";
}
alert(result);
}
</script>
</head ><body> <script type="text/javascript">
alertTable()
</script> </body></html>
BMSCE, ISE 58
Sample I/O:
BMSCE, ISE 59
Exercise 4.2: Output: The first 20 Fibonacci numbers, which are defined as in
the sequence 1,1,2,3,. . .
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.2 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
document.write("First 20 Fibonacci Numbers <br/><br/>");
document.write("1 - 1 <br/> 2 - 1 <br/>");
for (count = 3; count <= 20; count++) {
next = first + second;
document.write(count + " - " + next + "<br/>");
first = second;
second = next;
}
// -->
</script></body></html>
BMSCE, ISE 60
Sample I/O:
BMSCE, ISE 61
Exercise 4.4: Modify exercise 4.2 to use prompt to input a number n that is
the number of the Fibonacci number required as output.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.4 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
var first = 1, second = 1, next, count;
number = prompt("How many Fibonacci numbers do you want? (3-50)", "");
if (number >= 3 && number <= 50) {
document.write("First " + number + " Fibonacci Numbers <br /><br />");
document.write("1 - 1 <br/> 2 - 1 <br />");
for (count = 3; count <= number; count++) {
next = first + second;
document.write(count + " - " + next + "<br />");
first = second; second = next;
}
}
else
document.write("Error - number not in the range 3-50");
</script></body></html>
BMSCE, ISE 62
Sample I/O:
BMSCE, ISE 63
Exercise 4.6:
Input: A line of text, using prompt
Output: The words of the input text, in alphabetical order
<!DOCTYPE html>
<!-- e4_6.html - A solution to Exercise 4.6
-->
<html lang = "en">
<head>
<title> Exercise 4.6 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
str = prompt("Please input your sentence", "");
var words = str.split(" ");
words = words.sort();
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
// -->
</script>
</body>
</html>
BMSCE, ISE 64
Sample I/O:
BMSCE, ISE 65
Exercise 4.7:
Modify exercise4.6 to get a second input from the user, which is either
“ascending” or “descending”. Use this input to determine how to sort the
input words.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.7 </title> <meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// A function to compare strings for reverse alphabetic order
function dec_order(a, b) {
if (a > b)
return -1;
else if (a < b)
return 1;
else return 0;
}
// -->
</script> </head> <body>
<script type = "text/javascript">
<!--
var order, str, words, word_len, count; BMSCE, ISE 66
Exercise 4.7 Continued…
// Get the input
str = prompt("Please input your sentence", "");
order = prompt("What order? (ascending or descending)", "");
// If the order is recognized, issue an error message
if (order != "descending" && order != "ascending")
document.write("Error - order is incorrectly specified <br/>");
// Otherwise, do the sort, depending on the requested order
else {
var words = str.split(" ");
if (order == "ascending")
words = words.sort();
else
words = words.sort(dec_order);
// Write out the results
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
}
// -->
</script>
</body>
</html> BMSCE, ISE 67
Sample I/O:
BMSCE, ISE 68
ascending descending
BMSCE, ISE 69
Exercise 4.9 : Function:e_names
Parameter: An array of names, represented as strings.
Returns: The number of names in the given array that end in either “ie” or “y”.
<!DOCTYPE html>
<!-- e4_9.html - A solution to Exercise 4.9
-->
<html lang = "en">
<head>
<title> Exercise 4.9 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// Function e_names
// Parameter: an array of strings
// Returns: the number of given strings that end
// in either "ie" or "y"
function e_names(names) {
var len, index, count = 0;
len = names.length;
// Loop to use pattern matching to produce the count
BMSCE, ISE 70
Exercise 4.9 Continued . . .
for (index = 0; index < len; index++) {
position1 = names[index].search(/ie$/);
position2 = names[index].search(/y$/);
if (position1 + position2 > -2)
count++;
}
return count;
}
// -->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
// Function e_names tester
var new_names = new Array ("mourya", "babu", "manju", "priya", "vinay");
result = e_names(new_names);
document.write("The number of special names that end in either \"ie\" or \"y\" is: " + result
+ "<br/>");// -->
</script></body></html>
BMSCE, ISE 71
Sample I/O:
BMSCE, ISE 72
Exercise 4.14:Function: reverser
Parameter: A number
Returns: The number with its digits in reverse order
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
// Function reverser
// Parameter: a number
// Returns: the number with its digits in reverse order
// Note: Math.floor must be used to get the integer part
// of the division operations
BMSCE, ISE 73
function reverser(num) {
var digit, position = 0;
do {
digit = num % 10;
result = 10 * result + digit;
num = Math.floor(num / 10);
} while (num >= 1);
return result;
}
// --> BMSCE, ISE 74
</script>
</head>
<body>
<script type = "text/javascript">
<!--
// Function reverser tester
Document Object
Paragraph Object
<html>
<head>
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i>
document.
</body>
</html>
<!DOCTYPE html>
<html> Sample I/O:
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML =
'Hello JavaScript!'">
Click Me!</button>
</body>
</html>
• Reference to several nodes in the model of the page that the browser
constructed
• document
• The root of the tree is an object of type HTMLDocument
• Using the global variable document, we can access all the nodes in the tree, as well as useful
functions and other global information
• title, body, images, links, forms, ...
• open, write, close, getElementById, ...
• getElementById(“demo”)
• This is a predefined function that makes use of the id that can be defined for
any element in the page
• An id must be unique in the page, so only one element is ever returned by
this function
• The argument to getElementById specifies which element is being
requested
onmousedown The event occurs when the user presses a mouse button over an element
onmouseover The event occurs when the pointer is moved onto an element
onmouseout The event occurs when a user moves the mouse pointer out of an element
onmouseup The event occurs when a user releases a mouse button over an element
Form Events
Event Description
<!DOCTYPE html>
<html>
<body>
<h1 onmouseover="style.color='blue'" onmouseout="style.color='black'">
Mouse over this text
</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Click Anywhere!</title>
</head>
<body>
<script> document.addEventListener("click", changeColor, false);
function changeColor() {
document.body.style.backgroundColor = "#FFC926";
}
</script>
</body>
</html>
onclick
REGISTERING ??
EventHandler
document.getElementById(“b1").onclick = myFun;
<html><head>
<script type = "text/javascript">
function myFunction() {
var dom = document.forms[0].elements[1];
dom.value="Text Box Changed";
Sample I/O:
} </script>
</head> <body>
<h1>My Web Page</h1>
<form name="myForm">
<input type="text" name="par"/>
</br>
<input type = "button" onclick="myFunction();" name="turnItOn" value="CLICK" />
</form>
</body> </html>
var numchecked = 0;
var dom = document.get ElementById("vehicleGroup");
for (index = 0;index <dom.vehicles.length;index++)
if(dom.vehicles[index].checked)
numChecked++;
<!DOCTYPE html>
<html>
<body>
<p someevent="this.innerHTML='GOOD JOB!'">Click me.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p onclick="this.innerHTML='GOOD JOB!'">Click me.</p>
</body>
</html>
• The <span> element should do something when someone moves the mouse over
it. Try to fix it!
<!DOCTYPE html>
<html>
<body>
<span someevent="this.style.color='red'">Mouse over me!</span>
</body>
</html>
• The <span> element should do something when someone moves the mouse over
it. Try to fix it!
<!DOCTYPE html>
<html>
<body>
<span onmouseover="this.style.color='red'">
Mouse over me!
</span>
</body>
</html>
<html> <head>
<script type = "text/javascript" >
</script> </head>
<body>
<form name = "myForm" action="" onsubmit="return(chkpasswords());">
<p>
</label> User Name:
<input type = "text" id="username"> </label>
<br /> <br />
</label> Password:
<input type = "password" id = "firstpwd" /> </label>
<br /> <br />
<label> Retype Password:
<input type = "password" id = "secondpwd" /> </label>
<br /><br />
<input type = "submit" name = "submit" />
</p> </form>
</body></html>
Screen Y
Client Y
Screen X
Client X