JAVA SCRIPT��Prepared by�C.Jamunadevi�Assistant Professor(Sr.G)�Department of Computer Technology-PG�Kongu Engineering College
Java Script
Simple Javascript program
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>A First Program in JavaScript</title>
<script type = "text/javascript">
document.writeln("<h1>Welcome to JavaScript Programming!</h1>");
</script>
</head>
<body></body>
</html>
Example 2(javascript and CSS)
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>A First Program in JavaScript</title>
<script type = "text/javascript">
document.writeln("<h1 style='font-size:56px;color:red'>Welcome to JavaScript Programming!</h1>");
</script>
</head>
<body></body>
</html>
Variables and Datatype
Number(x=10)
String(s=“hello”)
Boolean
Undefined(explicitly declared but not assigning value)
Null(no value)
Operators
•Arithmetic Operators(+,-,*,/,%)
•Relational Operators(<,>,<=,>=,==,!=)
•Logical Operators(&&,||)
•Assignment Operators(=)
•Increment Operators
•Decrement Operators
String Concatenation Operator(+)
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>string concatenation</title>
<script type = "text/javascript">
var str="programming"
document.write("<h1>Web"+str+"concepts</h1>");
</script>
</head><body></body></html>
Addition of two numbers
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>addition</title>
<script type = "text/javascript">
var a=10;
var b=20;
var c=a+b;
document.write("the sum of a and b is"+c);
</script>
</head>
<body></body>
</html>
popup boxes
Displaying Text in an Alert Dialog
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>alert box</title>
<script type = "text/javascript">
window.alert( "Welcome to JavaScript Programming!");
</script>
</head>
<body></body>
</html>
Obtaining User Input with prompt Dialogs
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>dynamic page</title>
<script type = "text/javascript">
var name;
name=window.prompt("enter your name");
document.write("welcome"+name);
</script>
</head>
<body></body>
</html>
Adding Integers using Prompt box
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>adding integers</title>
<script type = "text/javascript">
var firstnumber;
var secondnumber;
firstnumber=window.prompt("enter your first number");
secondnumber=window.prompt("enter your second number");
a=parseInt(firstnumber);
b=parseInt(secondnumber);
var c=a+b;
document.write("the result is"+c);
</script>
</head><body></body>
</html>
Confirm Box�
Syntax
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Control Statements I : if Selection Statement
if Selection Statement
if (condition) {� // block of code to be executed if the condition is true�}
Example:
if ( studentGrade >= 60 ) document.writeln( "Passed" );
Control Statements I : if Selection Statement
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>If statement</title>
<script type = "text/javascript">
grade=70;
if ( grade >= 60 )
document.writeln( "<h3>Passed</h3>" );
</script>
<body>
</body>
</html>
if…else Selection Statement
Syntax:
if (condition) {� // block of code to be executed if the condition is true�} else { � // block of code to be executed if the condition is false�}
Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
Else Print “Failed”
if…else Selection Statement
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>If statement</title>
<script type = "text/javascript">
grade=50;
if ( grade >= 60 )
document.writeln( "<h3>Passed</h3>" );
else
document.writeln( "<h3>failed</h3>" );
</script>
<body>
</body>
</html>
Nested if...else Statements
Syntax:
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�}
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
JavaScript Ternary Operator
condition ? trueExpression : falseExpression
Input: let result = (10 > 0) ? true : false;�Output: true��Input: let message = (20 > 15) ? "Yes" : "No";�Output: Yes
Conditional Operator (?:)-�
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>conditional operator</title>
<script type = "text/javascript">
grade=50;
document.writeln(grade>=60?"Passed":"Failed");
</script>
<body>
</body>
</html>
Nested if...else Statements
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>nested if</title>
<script type = "text/javascript">
grade=65;
if (grade >= 90 )
document.writeln( "A" );
else
if (grade >= 80 )
document.writeln( "B" );
else
if (grade >= 70 )
document.writeln( "C" );
else
if (grade >= 60 )
document.writeln( "D" );
else
document.writeln( "F" );
</script>
<body>
</body>
</html>
while loop
while (condition) {� // code block to be executed�}
While there are more items on my shopping list Purchase next item and cross it off my list.
Example:
var product = 2;
while ( product <= 1000 )
product = 2 * product;
while Repetition Statement
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>while</title>
</head>
<body>
<table border="1">
<script>
var i=0;
while(i<=10)
{
document.write("<tr>"+"<td>"+i+"</td>"+"<td>"+(i*i)+"</td>"+"</tr>");
i++;
}
</script>
</table>
</body>
</html>
Calculate average of given numbers
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>while</title>
</head>
<body>
<script>
var marks;
var total=0;
var avg;
var i=1;
while(i<=10)
{
marks=window.prompt("enter your marks");
m=parseInt(marks);
total=total+m;
i++;
}
avg=total/10;
document.writeln(" the average value is"+avg);
</script>
</body>
</html>
Formulating Algorithms: Nested Control Statements
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>nested control</title>
</head>
<body>
<script>
var passes = 0;
var failures = 0;
var student = 1;
var result;
while(student<=10)
{
result=window.prompt("enter your result (1=pass,2=fail)");
r=parseInt(result);
if(r==1)
passes=passes+1;
else
failures=failures+1;
student=student+1;
}
document.writeln(" Examination results"+"passsed"+passes+"<br>"+"failed"+failures);
</script>
</body>
</html>
Control Statements II :do…while Repetition Statement
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>while</title>
</head>
<table border="1">
<script>
var i=0;
do
{
document.write("<tr>"+"<td>"+i+"</td>"+"<td>"+(i*i)+"</td>"+"</tr>");
i++;
}while(i<=10);
</script>
</table>
</body>
</html>
For statement
for Repetition Statement-The for repetition statement conveniently handles all the details of counter-controlled repetition.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>for</title>
<script>
var sum=0;
for(var i=2;i<100;i=i+2)
{
sum=sum+i;
}
document.write("the sum of even integers"+sum);
</script>
<body>
</body>
</html>
switch Multiple-Selection Statement
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>switch case</title>
<script type="text/javascript">
var d=new Date();
var c=d.getDay();
switch(c)
{
case 0:
document.write("Monday");
break;
case 1:
document.write("Tuesday");
break;
case 2:
document.write("wednesday");
break;
case 3:
document.write("thursday");
break;
case 4:
document.write("friday");
break;
case 5:
document.write("saturday");
break;
case 6:
document.write("sunday");
break;
}
</script>
</head>
<body>
</body>
</html>
Break Statements
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>break</title>
<script>
for(var i=0;i<=10;i++)
{
if(i==5)
break;
document.write(i);
}
</script>
<body>
</body>
</html>
Continue Statements
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>continue</title>
<script>
for(var i=0;i<=10;i++)
{
if(i==5)
continue;
document.write(i);
}
</script>
<body>
</body>
</html>
What is the difference between break and continue statement?
Logical Operators
JavaScript provides logical operators that can be used to form more complex conditions by combining simple conditions. The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, also called logical negation).
logical AND
Logical OR:
Logical Negation:
Logical AND
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>logical AND</title>
<script type="text/javascript">
var a=6,b=5,c=10;
if(a>b && b>c)
document.write("a is greater");
if(b>c)
document.write("b is greater");
else
document.write("c is greater");
</script>
</head>
<body></body>
</html>
Logical OR
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>logical OR</title>
<script type="text/javascript">
var semavg=90,finalexam=85;
if(semavg>=90 || finalexam>=90)
document.write("Grade is A");
else
document.write("Grade is B");
</script>
</head>
<body></body>
</html>
Java script Functions
Function Definitions
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var a=10,b=5;
function add(a,b)
{
c=a+b;
document.write("the result is "+c);
}
add(a,b);
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var a=10,b=20;
function add(a,b)
{
c=a+b;
return c;
}
document.write("the result is"+add(a,b));
</script>
</head>
<body>
</body>
</html>
Programmer-Defined Function square
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>A Programmer-Defined square Function</title>
<script>
function square( y )
{
return y * y;
}
document.writeln( "<h1>Square the numbers from 1 to 10</h1>" );
for ( var i = 0; i <= 10; i++ )
document.writeln( "<p>The square of " + i + " is " +square( i )+ "</p>" );
</script>
</head><body></body></html>
Programmer-Defined Function maximum
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Maximum of Three Values</title>
<script>
var input1 = window.prompt( "Enter first number");
var input2 = window.prompt( "Enter second number");
var input3 = window.prompt( "Enter third number");
var value1 = parseInt( input1 );
var value2 = parseInt( input2 );
var value3 = parseInt( input3 );
var maxValue = maximum( value1, value2, value3 );
document.writeln( "Maximum is: "+maxValue);
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
}
</script>
</head><body></body>
</html>
Random Number Generation-Scaling and Shifting Random Numbers
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Shifted and Scaled Random Integers</title>
<script type="text/javascript">
var value;
document.writeln("Random Numbers");
for(var i = 1; i <= 30;i++ )
{
value = Math.floor( 1 + Math.random() * 6 );
document.writeln(value);
}
</script>
</head><body></body></html>
Scope Rules
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>scope</title>
<script>
var x = 1;// global scope
function start()
{
functionA();
functionB();
functionA();
functionB();
}
function functionA()
{
var x = 25;//local scope
document.writeln("the value of x is"+x+"<br>");
x++;
document.writeln("the value of x is"+x+"<br>");
}
function functionB()
{
document.writeln("the value of x is"+x+"<br>");
x = x*10;
document.writeln("the value of x is"+x+"<br>");
}
start();
</script>
</head><body>
</body>
</html>
JavaScript Global Functions
Recursion
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>recursive</title>
<script>
function calculateFactorials()
{
for ( var i = 0; i <= 10; i++)
document.write("<br>"+factorial( i ));
}
function factorial( number )
{
if ( number <= 1 ) // base case
return 1;
else
return number * factorial( number - 1 );
}
calculateFactorials();
</script>
<body>
</body>
</html>
Java Script Arrays
Declaring and Allocating Arrays
var c = new Array( 12 );
var c; // declares a variable that will hold the array
c = new Array( 12 ); // allocates the array
Examples Using Arrays
One dimensional array
<!DOCTYPE html>
<html>
<body>
<script>
var a=new Array(5);
a=[100,200,300,400,500];
for(i=0;i<5;i++)
{
document.write(a[i]);
document.write("<br>");
}
</script>
</body>
</html>
•
Examples Using Arrays
<!DOCTYPE html>
<html>
<head>
<title> arrays</title>
<meta charset="UTF-8">
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for(i=0;i<3;i++)
{
document.write("<br>"+cars[i]);
}
</script>
<body>
</body>
</html>
Two dimensional array
<!DOCTYPE html>
<html>
<body>
<script>
var a=new Array();
a=[[1,2,3],[4,5,6],[7,8,9]];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
document.write(a[i][j]);
}
document.write("<br>");
}
</script>
</body>
</html>
Indirectly embedding of javascript
<!DOCTYPE html>
<html>
<head>
<title> arrays</title>
<meta charset="UTF-8">
<script type="text/javascript" src="a.js">
</script>
<body>
</body>
</html>
a.js
function myfun()//function definition
{
var cars = ["Saab", "Volvo", "BMW"];
for(i=0;i<3;i++)
{
document.write("<br>"+cars[i]);
}
}
myfun();//function call
Creating, Initializing and Growing Arrays
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Initializing an Array</title>
<script>
function start()
{
var n1 = new Array( 5 );
var length =n1.length;
for ( var i = 0; i < length; ++i )
{
n1[ i ] = i;
}
outputArray( "Array n1:", n1, document.getElementById( "output1" ) );
}
function outputArray( heading, theArray, output )
{
var content = "<h2>" + heading + "</h2><table>" +"<thead><th>Index</th><th>Value</th></thead><tbody>";
var length = theArray.length;
for ( var i = 0; i < length; ++i )
{
content=content+"<tr><td>" + i + "</td><td>" + theArray[ i ] +"</td></tr>";
}
content =content+ "</tbody></table>";
output.innerHTML = content//place the table in the output element;
}
window.addEventListener( "load", start, false );
/*attaches an event handler to the document syntax : document.addEventListener(event, function, Capture) */
</script>
</head>
<body>
<div id = "output1"></div></body></html>
Initializing Arrays with Initializer Lists
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Initializing an Array</title>
<script type="text/javascript">
function start()
{
var colors = new Array( "cyan", "magenta","yellow", "black" );
var integers1 = [ 2, 4, 6, 8 ];
var integers2 = [ 2, , , 8 ];
outputArray( "Array colors contains", colors,document.getElementById( "output1" ) );
outputArray( "Array integers1 contains", integers1,document.getElementById( "output2" ) );
outputArray( "Array integers2 contains", integers2,document.getElementById( "output3" ) );
}
function outputArray( heading, theArray, output )
{
var content = "<h2>" + heading + "</h2><table>" +"<thead><th>Index</th><th>Value</th></thead><tbody>";
var length = theArray.length; // get array's length once before loop
for ( var i = 0; i < length; ++i )
{
content=content+"<tr><td>" + i + "</td><td>" + theArray[ i ] +"</td></tr>";
}
content =content+"</tbody></table>";
output.innerHTML = content;
}
window.addEventListener( "load", start, false );
</script>
</head>
<body>
<div id = "output1"></div>
<div id = "output2"></div>
<div id = "output3"></div>
</body>
</html>
Summing the Elements of an Array with for and for…in
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Sum Array Elements</title>
<script type="text/javascript">
function start()
{
var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var total1 = 0, total2 = 0;
var length = theArray.length;
for ( var i = 0; i < length; ++i )
{
total1=total1+theArray[ i ];
}
var results = "Total using indices: " + total1;
document.write(results);
for( var element in theArray )
{
total2=total2+ theArray[ element ];
}
results= "Total using for...in: " + total2 ;
document.write("<br>"+results);
}
window.addEventListener( "load", start, false );
</script>
</head>
<body>
</body>
</html>
References and Reference Parameters
by reference.
Passing Arrays to Functions
var hourlyTemperatures = new Array( 24 );
modifyArray( hourlyTemperatures );
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>passing array to function</title>
<script>
function start()
{
var a = [ 1, 2, 3, 4, 5 ];
document.write("the original array");
for(var i=0;i<a.length;i++)
{
document.write(a[i]);
}
modifyArray(a);//function call
modifyElement( a[ 3 ] );//function call
}
function modifyArray( a )// passing entire array by reference
{
document.write("<br><h4>Effects of passing entire array by reference</h4>");
document.write("the modified array");
for (var i=0; i<a.length;i++ )
{
a[i] =a[i]*2;
document.write(a[i]);
}
}
function modifyElement( e )//passing array element by value
{
document.write("<br><h4>Effects of passing array element by value</h4>");
e *= 2;
document.write("after modifying element"+e);
}
start();// function call
</script>
</head>
<body></body>
</html>
Sorting Arrays with Array Method sort
<!DOCTYPE html>
<html>
<head>
<title> Sort</title>
<meta charset="UTF-8">
<script type="text/javascript">
function start()
{
var a = ["Banana", "Orange", "Apple", "Mango"];
document.writeln("<h4>Original array is</h4>");
for(var i=0;i<a.length;i++)
{
document.writeln(a[i]);
}
a.sort( );
document.writeln("<h4>sorted array</h4>");
for(var i=0;i<a.length;i++)
{
document.writeln(a[i]);
}
}
window.addEventListener( "load", start, false );
</script>
<body></body>
</html>
Numeric Sort
a negative value if the first argument is less than the second argument(first argument will be Place before second argument)
zero if the arguments are equal (no change)
a positive value if the first argument is greater than the second argument(first argument will be Place after second argument
Numeric Sort
● The sort function sorts the elements in string format.
● It will work good for string array but not for numbers
● Using comparator Function: We can create a comparator function that return negative, zero,
or positive values.
a negative value if the first argument is less than the second argument(first argument will be
Place before second argument)
zero if the arguments are equal (no change)
a positive value if the first argument is greater than the second argument(first argument will
be Place after second argument
<html>
<head>
<title> Sort</title>
<meta charset="UTF-8">
<script type="text/javascript">
function start()
{
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5, 11,13,0 ];
a.sort(function compare(a,b){return a-b});
document.writeln("<h5>sorted array</h5>");
for(var i=0;i<a.length;i++)
{
document.writeln(a[i]);
}
}
window.addEventListener( "load", start, false );
</script><body></body></html>
note
● Negative Value => a comes first
● zero value => No Change
● Positive Value => b comes first
Searching Arrays with Array Method indexOf
<html>
<head>
<meta charset = "utf-8">
<title>Search an Array</title>
<script src = "search.js"></script>
</head>
<body>
<form action = "#">
<p><label>Enter integer search key:
<input id = "inputVal" type = "number"></label>
<input id = "searchButton" type = "button" value = "Search">
</p>
<p id = "result"></p>
</form>
</html>
Multidimensional arrays
REFERENCE
Paul Deitel, Harvey Deitel and Abbey Deitel, "Internet and World Wide Web – How To Program", 5th Edition, Pearson Education, New Delhi, 2018.