1 of 95

JAVA SCRIPT��Prepared by�C.Jamunadevi�Assistant Professor(Sr.G)�Department of Computer Technology-PG�Kongu Engineering College

2 of 95

Java Script

  • JavaScript is a programming language commonly used in web development.
  • It was originally developed by Netscape as a means to add dynamic and interactive elements to websites.
  • JavaScript is a client-side scripting language, which means the source code is processed by the client's web browser rather than on the web server.
  • JavaScript can calculate, manipulate and validate data.
  • JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.

3 of 95

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>

4 of 95

5 of 95

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>

6 of 95

7 of 95

Variables and Datatype

  • Primitive types used in javascript

Number(x=10)

String(s=“hello”)

Boolean

Undefined(explicitly declared but not assigning value)

Null(no value)

  • Unlike its predecessor languages C, C++ and Java, JavaScript does not require variables to have a declared type before they can be used in a script.
  • A variable in JavaScript can contain a value of any data type, and in many situations JavaScript automatically converts between values of different types for you.
  • For this reason, JavaScript is referred to as a loosely typed language.

8 of 95

Operators

•Arithmetic Operators(+,-,*,/,%)

•Relational Operators(<,>,<=,>=,==,!=)

•Logical Operators(&&,||)

•Assignment Operators(=)

•Increment Operators

•Decrement Operators

9 of 95

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>

10 of 95

11 of 95

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>

12 of 95

13 of 95

popup boxes

  • JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
  • When an alert box pops up, the user will have to click "OK" to proceed.
  • When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false
  • When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

14 of 95

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>

15 of 95

16 of 95

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>

17 of 95

18 of 95

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>

19 of 95

20 of 95

Confirm Box�

  • A confirm box is often used if you want the user to verify or accept something.
  • When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
  • If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax

window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

21 of 95

<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>

22 of 95

23 of 95

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" );

24 of 95

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>

25 of 95

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”

26 of 95

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>

27 of 95

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�}

28 of 95

<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>

29 of 95

JavaScript Ternary Operator

  • JavaScript Ternary Operator (Conditional Operator) is a concise way to write a conditional (if-else) statement.
  • Ternary Operator takes three operands i.e. condition, true value and false value.
  • Syntax

condition ? trueExpression : falseExpression

  • EXAMPLE:

Input: let result = (10 > 0) ? true : false;�Output: true��Input: let message = (20 > 15) ? "Yes" : "No";�Output: Yes

30 of 95

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>

31 of 95

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>

32 of 95

while loop

  • The while loop loops through a block of code as long as a specified condition is true.
  • A repetition structure (also known as a loop) allows you to specify that a script is to repeat an action while some condition remains true
  • Syntax:

while (condition) {�  // code block to be executed�}

33 of 95

  • The pseudocode statement:

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;

34 of 95

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>

35 of 95

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>

36 of 95

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>

37 of 95

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>

38 of 95

For statement

39 of 95

40 of 95

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>

41 of 95

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>

42 of 95

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>

43 of 95

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>

44 of 95

What is the difference between break and continue statement?

  • Break statement stops the entire process of the loop. Continue statement only stops the current iteration of the loop. Break also terminates the remaining iterations. Continue doesn't terminate the next iterations; it resumes with the successive iterations.

45 of 95

46 of 95

47 of 95

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

48 of 95

Logical OR:

Logical Negation:

49 of 95

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>

50 of 95

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>

51 of 95

Java script Functions

  • A JavaScript function is a block of code designed to perform a particular task.
  • A JavaScript function is executed when "something" invokes it (calls it).
  • Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or modules.
  • This technique is called divide and conquer.
  • A function is invoked (that is, made to perform its designated task) by a function call.
  • The function call specifies the function name and provides information (as arguments) that the called function needs to perform its task.

52 of 95

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>

53 of 95

<!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>

54 of 95

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>

55 of 95

56 of 95

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>

57 of 95

58 of 95

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>

59 of 95

Scope Rules

  • Each identifier in a program also has a scope.
  • An identifier is nothing but a name assigned to an element in a program. Example, name of a variable, function, etc
  • The scope of an identifier for a variable or function is the portion of the program in which the identifier can be referenced. Global variables or script-level variables that are declared in the head element are accessible in any part of a script and are said to have global scope
  • Identifiers declared inside a function have function (or local) scope and can be used only in that function. Function scope begins with the opening left brace ({) of the function in which the identifier is declared and ends at the function’s terminating right brace (}).
  • If a local variable in a function has the same name as a global variable, the global variable is “hidden” from the body of the function.

60 of 95

<!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>

61 of 95

JavaScript Global Functions

62 of 95

Recursion

  • A recursive function is a function that calls itself, either directly, or indirectly through another function.
  • As an example of these concepts at work, let’s write a recursive program to perform a popular mathematical calculation. The factorial of a nonnegative integer n, written n! (and pronounced “n factorial”), is the product n · (n – 1) · (n – 2) · … · 1
  • A recursive definition of the factorial function is arrived at by observing the following relationship:
  • n! = n · (n – 1)!

63 of 95

<!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>

64 of 95

65 of 95

Java Script Arrays

  • Arrays are data structures consisting of related data items
  • An array is a group of memory locations that all have the same name and normally are of the same type
  • To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array.
  • JavaScript arrays are used to store multiple values in a single variable.
  • An array is a special variable, which can hold more than one value at a time and you can access the values by referring to an index number.

66 of 95

67 of 95

Declaring and Allocating Arrays

  • Arrays occupy space in memory.
  • Actually, an array in JavaScript is an Array object.
  • You use the new operator to create an array and to specify the number of elements in an array.
  • The new operator creates an object as the script executes by obtaining enough memory to store an object of the type specified to the right of new.
  • To allocate 12 elements for integer array c, use a new expression like:

var c = new Array( 12 );

  • The preceding statement can also be performed in two steps, as follows:

var c; // declares a variable that will hold the array

c = new Array( 12 ); // allocates the array

  • When arrays are created, the elements are not initialized—they have the value undefined.

68 of 95

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>

69 of 95

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>

70 of 95

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>

71 of 95

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

72 of 95

73 of 95

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" ) );

}

74 of 95

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>

75 of 95

76 of 95

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" ) );

}

77 of 95

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>

78 of 95

79 of 95

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>

80 of 95

81 of 95

References and Reference Parameters

  • Two ways to pass arguments to functions (or methods) in many programming languages are pass-by-value and pass-by-reference.
  • When an argument is passed to a function by value, a copy of the argument’s value is made and is passed to the called function.
  • With pass-by-reference,This procedure is accomplished by passing to the called function the address in memory where the data resides.
  • Pass-by-reference can improve performance because it can eliminate the overhead of copying large amounts of data, but it can weaken security because the called function can access the caller’s data.
  • In JavaScript, all objects (and thus all arrays) are passed to functions

by reference.

82 of 95

  • The name of an array actually is a reference to an object that contains the array elements and the length variable.
  • To pass a reference to an object into a function, simply specify the reference name in the function call.
  • The reference name is the identifier that the program uses to manipulate the object.

83 of 95

Passing Arrays to Functions

  • To pass an array argument to a function, specify the array’s name (a reference to the array)without brackets.
  • For example, if array hourlyTemperatures has been declared as

var hourlyTemperatures = new Array( 24 );

  • then the function call

modifyArray( hourlyTemperatures );

  • passes array hourlyTemperatures to function modifyArray

84 of 95

<!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

}

85 of 95

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>

86 of 95

87 of 95

Sorting Arrays with Array Method sort

  • The sort() method sorts an array alphabetically
  • The sort() method allows you to sort elements of an array in place.
  • By default, Array method sort (with no arguments) uses string comparisons to determine the sorting order of the array elements.
  • The strings are compared by the ASCII values of their characters.
  • By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

88 of 95

<!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>

89 of 95

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

90 of 95

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

91 of 95

<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

92 of 95

Searching Arrays with Array Method indexOf

  • The indexOf() method returns the position of the first occurrence of a value in a string.
  • The indexOf() method returns -1 if the value is not found.
  • The indexOf() method is case sensitive.

<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>

93 of 95

94 of 95

Multidimensional arrays

95 of 95

REFERENCE

Paul Deitel, Harvey Deitel and Abbey Deitel, "Internet and World Wide Web – How To Program", 5th Edition, Pearson Education, New Delhi, 2018.