0% found this document useful (0 votes)
2K views

Module2 JS

javascript

Uploaded by

gkfgvk13412
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Module2 JS

javascript

Uploaded by

gkfgvk13412
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Overview of JavaScript

Origins
➢ Originally developed by Netscape
➢ Joint Development with Sun Microsystems in 1995
➢ Standard 262 (ECMA-262) of the European Computer Manufacturers Association
➢ ECMA-262 edition 3 is the current standard
• Edition 4 is under development
➢ Supported by Netscape, Mozilla, Internet Explorer
Java and JavaScript
➢Differences
JavaScript has a different object model from Java
JavaScript is not strongly typed
➢Java 1.6 has support for scripting
http://java.sun.com/javase/6/docs/technotes/guides/scripting/index.html
➢Mozilla Rhino is an implementation of JavaScript in Java
http://www.mozilla.org/rhino/
JavaScript Components
➢ Core
The heart of the language
➢ Client-side
Library of objects supporting browser control and user interaction
➢ Server-side
Library of objects that support use in web servers
➢ Text focuses on Client-side
Uses of JavaScript
➢ Provide alternative to server-side programming
• Servers are often overloaded
• Client processing has quicker reaction time
➢ JavaScript can work with forms
➢ JavaScript can interact with the internal model of the web page (Document Object Model)
Event-Driven Computation

➢ Users actions, such as mouse clicks and key presses, are referred to as events
➢ The main task of most JavaScript programs is to respond to events
➢ For example, a JavaScript program could validate data in a form before it is submitted to a
server
XHTML/JavaScript Documents

➢ When JavaScript is embedded in an XHTML document, the browser interpret ‘s it with


Java Interpretor to run or execute.
➢ Two locations for JavaScript server different purposes
• JavaScript in the head element will react to user input and be called from other
locations
• JavaScript in the body element will be executed once as the page is loaded
➢ Various strategies must be used to ‘protect’ the JavaScript from the browser
• For example, comparisons present a problem since < and > are used to mark tags in
XHTML
• JavaScript code can be enclosed in XHTML comments
• JavaScript code can be enclosed in a CDATA section
JavaScript in XHTML: CDATA
➢ The <![CDATA[ … ]]> block is intended to hold data that should not be interpreted as XHTML
➢ Using this should allow any data (including special symbols and --) to be included in the script
➢ This, however does not work, at least in Firefox:
<script type=“text/javascript”>
<![CDATA[
…JavaScript here…
]]>
</script>
➢ The problem seems to be that the CDATA tag causes an internal JavaScript error
JavaScript in XHTML
➢ This does work in Firefox
<script type=“text/javascript”>
/*<![CDATA[ */
…JavaScript here…
/*]]> */
</script>
➢ The comment symbols do not bother the XML parser (only /* and */ are ‘visible’ to it)
➢ The comment symbols protect the CDATA markers from the JavaScript parser
Object Orientation and JavaScript
➢ JavaScript is object-based
• JavaScript defines objects that encapsulate both data and processing
• However, JavaScript does not have true inheritance nor subtyping
➢ JavaScript provides prototype-based inheritance

JavaScript Objects
➢ Objects are collections of properties
➢ Properties are either data properties or method properties
➢ Data properties are either primitive values or references to other objects
➢ Primitive values are often implemented directly in hardware
➢ The Object is the ancestor of all objects in a JavaScript program
➢ Object has no data properties, but several method properties
JavaScript in XHTML

➢ Directly embedded
<script type=“text/javascript”>
<!--
…Javascript here…
-->
</script>

➢ However, note that a-- will not be allowed here!

➢ Indirect reference
<script type=“text/javascript” src=“tst_number.js”/>
This is the preferred approach
General Syntactic Characteristics
➢ Identifiers
• Case sensitive
➢ Reserved words: alert, etc
➢ Keywords: break, case, fuction, typeof… etc
➢ Comments
• //
• /* … */

➢ Statements can be terminated with a semicolon


➢ However, the interpreter will insert the semicolon if missing at the end of a line and
the statement seems to be complete
➢ Can be a problem:
➢ return
➢ x;
➢ If a statement must be continued to a new line, make sure that the first line does
not make a complete statement by itself
<html>
<head>
<title> Hello.html </title>

</head>
<body>
<script type="text/javascript">
document.write("Hello World Program");
</script>
</body>
</html>
Primitive Types

➢ Five primitive types


• Number
• String
• Boolean
• Undefined
• Null
➢ There are five classes corresponding to the five primitive types
• Wrapper objects for primitive values
• Place for methods and properties relevant to the primitive types
• Primitive values are coerced to the wrapper class as necessary, and vice-versa
Primitive and Object Storage
Numeric and String Literals
➢ Number values are represented internally as double-precision floating-point values
• Number literals can be either integer or float
• Float values may have a decimal and/or and exponent
➢ A String literal is delimited by either single or double quotes
• There is no difference between single and double quotes
• Certain characters may be escaped in strings
• \’ or \” to use a quote in a string delimited by the same quotes
• \\ to use a literal backspace
• The empty string ‘’ or “” has no characters
>> Other Primitive Types
➢ Null
• A single value, null
• null is a reserved word
• A variable that is used but has not been declared nor been assigned a value has a null value
• Using a null value usually causes an error
➢ Undefined
• A single value, undefined
• However, undefined is not, itself, a reserved word
• The value of a variable that is declared but not assigned a value
➢ Boolean
• Two values: true and false
Declaring Variables
➢ JavaScript is dynamically typed, that is, variables do not have declared types
• A variable can hold different types of values at different times during program execution
➢ A variable is declared using the keyword var
var counter,
index,
pi = 3.14159265,
quarterback = "Elway",
stop_flag = true;
Numeric Operators
➢ Standard arithmetic
• + * - / %
➢ Increment and decrement
• -- ++
• Increment and decrement differ in effect when used before and after a variable
• Assume that a has the value 3, initially
• (++a) * 3 has the value 12
• (a++) * 3 has the value 9
• a has the final value 4 in either case
Precedence of Operators
Operators Associativity
++, --, unary - Right
*, /, % Left
+, - Left
>, <, >= ,<= Left
==, != Left
===,!== Left
&& Left
|| Left
=, +=, -=, *=, /=, &&=, ||=, %= Right

Special: = = = : 1 = = “1” returns true, but its not, so 1 === “1” returns false
Example of Precedence: var a = 2,b = 4,c,d;
c = 3 + a * b;
// * is first, so c is now 11 (not 24)
d = b / a / 2;
// / associates left, so d is now 1 (not 4)
The Math Object
➢ Provides a collection of properties and methods useful for Number values
➢ This includes the trigonometric functions such as sin and cos
➢ When used, the methods must be qualified, as in Math.sin(x)

The Number Object


➢ Properties
• MAX_VALUE: largest Representable Number
• MIN_VALUE: Smallest Representable Number
• NaN: Not a Number
• POSITIVE_INFINITY: Special value to represent Infinity
• NEGATIVE_INFINITY: Special value to represent Negative Infinity
• PI: the value of ∏
➢ Operations resulting in errors return NaN
• Use isNaN(a) to test if a is NaN
➢ toString method converts a number to string
String Catenation
➢ The operation + is the string catenation operation
➢ In many cases, other types are automatically converted to string

Implicit Type Conversion

➢ JavaScript attempts to convert values in order to be able to perform operations


➢ “August “ + 1977 causes the number to be converted to string and a concatenation to
be performed
➢ 7 * “3” causes the string to be converted to a number and a multiplication to be
performed
➢ null is converted to 0 in a numeric context, undefined to NaN
➢ 0 is interpreted as a Boolean false, all other numbers are interpreted a true
➢ The empty string is interpreted as a Boolean false, all other strings (including “0”!) as
Boolean true
➢ undefined, Nan and null are all interpreted as Boolean false
Explicit Type Conversion
➢ Explicit conversion of string to number
• Number(aString)
• aString – 0
• Number must begin the string and be followed by space or end of string
➢ parseInt and parseFloat convert the beginning of a string but do not cause an error if a
non-space follows the numeric part

String Properties and Methods


➢ One property: length
➢ Character positions in strings begin at index 0
String Methods

Method Parameters Result

charAt A number Returns the character in the String object that


is at the specified position

indexOf One-character string Returns the position in the String object of the
parameter

Substring Two numbers Returns the substring of the String object from
the first parameter position to the second

toLowerCase None Converts any uppercase letters in the string to


lowercase

toUpperCase None Converts any lowercase letters in the string to


uppercase
Example:

Var str=“George”

var len = str.length; //6

Str.charAt(2) //o
str.indexof ( ‘ r ’ ) //3
Str.substring(2,4) //or
Str.toLowerCase() /george
The typeof Operator
➢ Returns type of single operand
➢ Returns “number” or “string” or “boolean” for primitive types
➢ Returns “object” for an object or null
➢ Two syntactic forms
• typeof x or typeof(x)
Assignment Statements
➢ Plain assignment indicated by =
➢ Compound assignment with
+= -= /= *= %= …
a += 7 means the same as a = a + 7
The Date Object
➢ A Date object represents a time stamp, that is, a point in time
➢ A Date object is created with the new operator
• var now= new Date();
• This creates a Date object for the time at which it was created
The Date Object: Methods

toLocaleString A string of the Date information

getDate The day of the month

getMonth The month of the year, as a number in the range of 0 to 11

getDay The day of the week, as a number in the range of 0 to 6

getFullYear The year

getTime The number of milliseconds since January 1, 1970

getHours The number of the hour, as a number in the range of 0 to 23

getMinutes The number of the minute, as a number in the range of 0 to 59

getSeconds The number of the second, as a number in the range of 0 to 59

getMilliseconds The number of the millisecond, as a number in the range of 0 to 999


Screen Output and Keyboard Input
➢ Standard output for JavaScript embedded in a browser is the window displaying the
page in which the JavaScript is embedded
➢ The write method of the Document object write its parameters to the browser window
➢ The output is interpreted as HTML by the browser
➢ If a line break is needed in the output, interpolate <br/> into the output
The alert Method
➢ The alert method opens a dialog box with a message
➢ The output of the alert is not XHTML, so use new lines rather than <br/>
alert("The sum is:" + sum + "\n");
The confirm Method

➢ The confirm methods displays a message provided as a parameter


➢ The confirm dialog has two buttons: OK and Cancel
➢ If the user presses OK, true is returned by the method
➢ If the user presses Cancel, false is returned
var question =
confirm("Do you want to continue this download?");
The prompt Method
➢ This method displays its string argument in a dialog box
• A second argument provides a default content for the user entry area
➢ The dialog box has an area for the user to enter text
➢ The method returns a String with the text entered by the user
name = prompt("What is your name?", "");
Root.html Root.js
<?xml version="1.0"?> var a = prompt("enter value of 'A' ? \n", "");
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" var b = prompt("enter value of 'B' ? \n", "");
"http://www.w3.org/TR/xhtml11/DTD/shtml11.dtd"> var c = prompt("enter value of 'c' ? \n", "");
<html xmlns="http://www.w3.org/1999/xhtml">
<head> var root1 = Math.sqrt(b * b - 4.0 * a * c);
<title> root.html </title> var denom = 2.0 * a;
</head>
<body> var r1 = (-b + root1) / denom;
<script type="text/javascript" src="roots.js"> var r2 = (-b - root1) / denom;
</script>
</body> document.write("root1 is:", r1, "<br/>");
</html> document.write("root2 is:", r2, "<br/>");
Control Statements
➢ A compound statement in JavaScript is a sequence of 0 or more statements enclosed in curly
braces.
Compound statements can be used as components of control statements allowing multiple
statements to be used where, syntactically, a single statement is specified.
➢ A control construct is a control statement including the statements or compound statements
that it contains

Control Expressions
➢ A control expression has a Boolean value
An expression with a non-Boolean value used in a control statement will have its value
converted to Boolean automatically
➢ Comparison operators
== , != , < , <= , > , >=, !==
=== compares identity of values or objects
3 == ‘3’ is true due to automatic conversion
3 === ‘3’ is false
➢ Boolean operators
&& || !
➢ Warning! A Boolean object evaluates as true
Unless the object is null or undefined
Selection Statements
➢ The if-then and if-then-else are similar to that in other programming languages,
especially C/C++/Java
If ( a > b)
switch Statement Syntax document.write(“largest”);
switch (expression) { else
case value_1: document.write(“smallest”);
// statement(s)
case value_2:
// statement(s)
...
[default:
// statement(s)]
}
switch Statement Semantics
➢ The expression is evaluated
➢ The value of the expressions is compared to the value in each case in turn
➢ If no case matches, execution begins at the default case
➢ Otherwise, execution continues with the statement following the case
➢ Execution continues until either the end of the switch is encountered or a break
statement is executed

Results:
Example.html Roots.js

<html xmlns="http://www.w3.org/1999/xhtml"> var bordersize;


<head> bordersize = prompt("select size \n" +
<title> root.html </title> "0/1/4/8\n");
</head> switch(bordersize) {
<body> case "0": document.write("<table>");
<script type="text/javascript" src="roots.js"> break;
</script> case "1": document.write("<table
</body> border = '1'>");
</html> break;
case "4": document.write("<table
border = '4'>");
break;
case "8": document.write("<table
border = '8'>");
break;

}
document.write("<tr> <th> College </th></tr>",
“<tr><td> DSCE </td></tr>",
"</table>");
Loop Statements
Loop statements in JavaScript are similar to those in C/C++/Java
While
while (control expression)
statement or compound statement
For
for (initial expression; control expression; increment expression)
statement or compound statement
do/while
do statement or compound statement
while (control expression)

while Statement Semantics


➢ The control expression is evaluated
➢ If the control expression is true, then the statement is executed
➢ These two steps are repeated until the control expression becomes false
➢ At that point the while statement is finished.
for Statement Semantics
➢ The initial expression is evaluated
➢ The control expression is evaluated
➢ If the control expression is true, the statement is executed
➢ Then the increment expression is evaluated
➢ The previous three steps are repeated as long as the control expression remains true
➢ When the control expression becomes false, the statement is finished executing
var today= new Date();
<?xml version="1.0"?>
var date = today.toLocaleString();
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"
var day = today.getDay();
"http://www.w3.org/TR/xhtml11/DTD/shtml11.dtd">
var month = today.getMonth();
<html xmlns="http://www.w3.org/1999/xhtml">
var year = today.getFullYear();
<head>
var timemillisec = today.getTime();
<title> root.html </title>
var hour = today.getHours();
</head>
var sec = today.getSeconds();
<body>
var millisec = today.getMilliseconds();
<script type="text/javascript" src="roots.js">
</script>
document.write(
</body>
"Date: " + date + "<br/>",
</html>
"Day: " + day + "<br/>",
"month: " + month + "<br/>");
do/while Statement Semantics
➢ The statement is executed
➢ The control expression is evaluated
➢ If the control expression is true, the previous steps are repeated
➢ This continues until the control expression becomes false
➢ At that point, the statement execution is finished
Object Creation and Modification
The new expression is used to create an object
▪ This includes a call to a constructor
▪ The new operator creates a blank object, the constructor creates and initializes all
properties of the object
• Properties of an object are accessed using a dot notation
Syntax : object.property
• Properties are not variables, so they are not declared
• An object may be thought of as a Map/Dictionary/Associative-Storage
• The number of properties of an object may vary dynamically in JavaScript.
Dynamic Properties
Create my_car and add some properties
// Create an Object object
var my_car = new Object();
// Create and initialize the make property
my_car.make = "Ford";
// Create and initialize model
my_car.model = "Contour SVT";
OR var my_car={ make:”ford”, model:”svt”};

Nesting : my_car.engine= new Object();


my_car.engine.ho=99;
The delete operator can be used to delete a property from an object
delete my_car.model
The for-in Loop
Syntax
for (identifier in object)
statement or compound statement
The loop lets the identifier take on each property in turn in the object
Printing the properties in my_car:
* Perfect to list prop of object
for (var prop in my_car)
document.write("Name: ", prop, "; Value: ",
my_car[prop], "<br />");

Result:
Name: make; Value: Ford
Name: model; Value: Contour SVT
Arrays
➢ Arrays are lists of elements indexed by a numerical value
➢ Array indexes in JavaScript begin at 0
➢ Arrays can be modified in size even after they have been created

Array Object Creation


Arrays can be created using the new Array method
new Array with one parameter creates an empty array of the specified number of elements
new Array(10) → blank array
new Array with two or more parameters creates an array with the specified parameters as
elements
new Array(10, 20,60) →10,20,60
Literal arrays can be specified using square brackets to include a list of elements
var alist = [1, “ii”, “gamma”, “4”]; → 1, ii, gamma, 4
Elements of an array do not have to be of the same type
Characteristics of Array Objects

➢ Array elements are accessed using numeric subscript expression


➢ The length of an array is one more than the highest index to which a value has been
assigned or the initial size. Ex: list[47] ➔ new length is 48 (index from 0)
➢ Assignment to an index greater than or equal to the current length simply increases
the length of the array
➢ Only assigned elements of an array occupy space
• Suppose an array were created using new Array(200)
• Suppose only elements 150 to 174 were to be assigned values
• Only the 25 assigned elements would be allocated storage, the other 175 would
not be allocated storage
Access particular element
Accessing all array elements
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h2>JavaScript Arrays</h2>
<h2>JavaScript Arrays</h2>
<script>
var cars = ["Saab", "Volvo", <script>
"BMW"]; var person = ["John", "Doe", 46];
document.write(cars); document.write(person[1]);
</script> </script>
</body>
</html> </body>
</html>
<html>
//insert to location in array
<head>
name_list[last+1]= new_name;
<title> arrays </title>
<script type="text/javascript">
document.write("<p><b> Name list is:
var name_list = new Array("Amar",
</b>", "<br/>");
"Rahul", "Rajesh");
var new_name,i,last;
for (i=0; i < name_list.length ; i++)
//to get new name and insert
document.write(name_list[i],"<br/>");
while(new_name = prompt("enter New
name:", ""))
document.write("</p>");
{
}
last = name_list.length - 1;
</script>
<body>
//to find place
</body>
while(last >= 0 && name_list[last] >
</html>
new_name)
{
name_list[last+1] = name_list[last]
last--;
}
Array Methods Two-dimensional Arrays
• join ex. name.join(“:”);
• Reverse, sort,concat ➢ A two-dimensional array in JavaScript is an array
• Slice of arrays
Ex: var list=[2,4,6,8,10]; ➢ This need not even be rectangular shaped:
var l2=list.slice(1,3); different rows could have different length
// 4 6 ** if list.slice(3)➔8 10 ➢ Example nested_arrays.js illustrates two-
dimensional arrays
Dynamic List Operations ➢ var nest_arry= [ [2,4,6], [1,3,5], [10,20,30]];

• push
Add to the end
• pop
Remove from the end
• shift
Remove from the front
• unshift
Add to the front Example: arraymethods.html
<html>
<head>
<title> arrays </title>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var num = new Array(4,2,3,1,0,8);
document.write("<p> Array list is", "<br/>");
document.write("Join Operation:- &nbsp;&nbsp;" + fruits.join(" : "), "<br/>");
document.write("Rev Operation:- &nbsp;&nbsp;" + fruits.reverse(), "<br/>");
document.write("Sort Operation:- &nbsp;&nbsp;" + num.sort(), "<br/>");
document.write("Slice Operation:- &nbsp;&nbsp;" + num.slice(0,3), "<br/>");
document.write("</p>");

document.write("<p> other","<br/>");
document.write("<b>push operation:</b><br/>" +fruits.push("kiwi"), "<br/>");
for(var i=0; i< fruits.length;i++)
document.write(fruits[i], "<br/>");

document.write("<b>poped:</b> " +fruits.pop(), "<br/>");


for(var i=0; i< fruits.length;i++)
document.write(fruits[i], "<br/>");
// shift & unshift
document.write("<b>Shift:</b> " +fruits.shift(), "<br/>");
document.write("<b>List </b> ", "<br/>");
for(var i=0; i< fruits.length;i++)
document.write(fruits[i], "<br/>");

document.write("<b>Shift:</b> " +fruits.unshift("Dragon Fruit"), "<br/>");


for(var i=0; i< fruits.length;i++)
document.write(fruits[i], "<br/>");

</script>
<body>
</body>
</html>
Functions
➢ Function definition syntax
A function definition consist of a header followed by a compound statement
A function header:
function function-name(optional-formal-parameters)
➢ return statements
A return statement causes a function to cease execution and control to pass to the caller
A return statement may include a value which is sent back to the caller
This value may be used in an expression by the caller
A return statement without a value implicitly returns undefined
➢ Function call syntax
Function name followed by parentheses and any actual parameters
Function call may be used as an expression or part of an expression
➢ Functions must defined before use in the page header
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation,


and returns the result:</p>

<p id="demo"></p>

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
var c=myFunction(4,4);

document.write(c);
</script>

</body>
</html>
Functions are Objects
Functions are objects in JavaScript & variables that reference them is treated as other
reference.
Object properties that have function values are methods of the object
Example
function fun()
{
document.write("This surely is fun! <br/>");
}
ref_fun = fun; // Now, ref_fun refers to the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun
Local Variables
➢ The scope of a variable is the range of statements over which it is visible
➢ A variable not declared using var has global scope, visible throughout the page, even if used
inside a function definition
➢ A variable declared with var outside a function definition has global scope
➢ A variable declared with var inside a function definition has local scope, visible only inside
the function definition
➢ If a global variable has the same name, it is hidden inside the function definition
Parameters
➢ Parameters named in a function header are called formal parameters
➢ Parameters used in a function call are called actual parameters
➢ In JS Parameters are passed by value
• For an object parameter, the reference is passed, so the function body can actually
change the object
• However, an assignment to the formal parameter will not change the actual parameter
<html>
<head> If Parameter is passed and my_list is updated
<title> arrays </title> function fun(my_list)
<script type="text/javascript"> { my_list=12;
function fun(my_list) document.write(my_list); }
{
document.write(my_list); Output: 12
}
var list= new Array(1,2,3,4,5); Modification
fun(list); function fun(my_list)
</script> { var list1=new Array(2,4,5,6) ; // or var list1=[2,4,5,6];
<body> my_list=12;
</body> my_list=list1;
</html> document.write(my_list);
}
Output: 1,2,3,4,5 Output: 2,4,5,6

Note: if ➔ var list1=(2,4,5,6); o/p: 6


Parameter Passing Example
function fun1(my_list) {
var list2 = new Array(1, 3, 5);
my_list[3] = 14;
...
my_list = list2;
...
}
...
var list = new Array(2, 4, 6, 8)
fun1(list);

➢ The first assignment changes list in the caller


➢ The second assignment has no effect on the list object in the caller
➢ Pass by reference can be simulated by passing an array containing the value
Program to find Max value in array
<html>
<body>
<script>
function findMax() { • JavaScript functions have a built-in object called the
var i; arguments object.
var max = 0;
for(i = 0; i < arguments.length; i++) {
if (arguments[i] > max) { • The argument object contains an array of the arguments
max = arguments[i]; used when the function was called (invoked).
}
}
return max; • This way you can simply use a function to find (for instance)
} the highest value in a list of numbers:
document.write( findMax(4, 1));
</script>

</body>
</html>

Fun.html
Sum of all Arguments

<!DOCTYPE html> Out PUT


<html>
<body> 871
<script>
function sumAll() {
var i;
var sum = 0;
for(i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
document.write(
sumAll(1, 123, 500, 115, 44, 88));
</script>

</body>
</html>
Parameter Checking
➢ JavaScript checks neither the type nor number of parameters in a function call
• Formal parameters have no type specified
• Extra actual parameters are ignored (however, see below)
• If there are fewer actual parameters than formal parameters, the extra formal parameters remain
undefined
➢ This is typical of scripting languages
➢ A property array named arguments holds all of the actual parameters, whether or not there are more of
them than there are formal parameters
• Example params.js illustrates this
The sort Method, Revisited
➢ A parameter can be passed to the sort method to specify how to sort elements in an array
• The parameter is a function that takes two parameters
• The function returns a negative value to indicate the first parameter should come before the second
• The function returns a positive value to indicate the first parameter should come after the second
• The function returns 0 to indicate the first parameter and the second parameter are equivalent as far
as the ordering is concerned
➢ Example median.js illustrates the sort method
Develop and demonstrate a XHTML file that includes Javascript script for the following problems:
a) Input: A number n obtained using prompt
Output: The first n Fibonacci numbers
b) Input: A number n obtained using prompt
Output: A table of numbers from 1 to n and their squares using alert
Constructors
➢ Constructors are functions that create an initialize properties for new objects
➢ A constructor uses the keyword “this” in the body to reference the object being initialized
➢ Object methods are properties that refer to functions
• A function to be used as a method may use the keyword “this” to refer to the object for
which it is acting
➢ Example:
function car( n_make, n_model,n_year)
{ this.make=n_make; this.model=n_model; this.year=n_year;
}
Can be used as follows:- my_car= new car(“ford”,”SVY”, “2000”);
<html>
<body>
<h2>JavaScript Object Constructors</h2>
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create two Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
// Display age
document.write("My father is " + myFather.age + ". My mother
is " + myMother.age + ".“);
</script>

</body>
</html>
1. JavaScript can "display" data in different ways:

• Writing into an HTML element, using innerHTML.


• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log(). (Note: For debugging purposes, you can use
the console.log() method to display data.)
2. To access an HTML element, JavaScript can use the document.getElementById(id) method.
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6; Console.log(5+6)
//document.write(5+6); window.alert(5+6);
</script>

</body>
</html>
<!DOCTYPE html> Get element by ID, Onclick event
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML


content.</p>

<button type="button"
onclick='document.getElementById("demo
").innerHTML = "Hello JavaScript!"'>Click
Me!</button>

</body>
</html>
Using Regular Expressions
➢ A regular expression is a sequence of characters that forms a search pattern
➢ Regular expressions are used to specify the search patterns in strings
➢ JavaScript provides two methods to use regular expressions in pattern matching
• String methods
• RegExp objects
Syntax :
/pattern/modifiers; ex: var patt = /school/i; → search: school, and i a
modifier to search case -insensitive
➢ A literal regular expression pattern is indicated by enclosing the pattern in slashes
➢ The search method returns the position of a match, if found, or -1 if no match was found
Other Modifiers
➢ Example: Pto i - case-insensitive matching
g - global match (for all matches)
m - multiline
<html> Output:
<body> 11

<p>Search a string for "w3Schools", and display the position of


the match:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = “Welcome to DSCE!";
var n = str.search(/DSCE/i);
document.getElementById("demo").innerHTML = n;
}
</script>
Note: if Not found returns -1
</body>
</html>
String replace() With a Regular Expression
OUTPUT:
<html> Please visit Microsoft!
<body>
<h2>JavaScript String Methods</h2>
Changed to
<button onclick="myFunction()">Try it</button> Please visit DSCE!
<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/microsoft/i,"DSCE");
//or var txt = str.replace("Microsoft","W3Schools");
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>
Characters and Character-Classes

➢ Metacharacters have special meaning in regular expressions


• \ | ( ) [ ] { } ^ $ * + ? .
• These characters may be used literally by escaping them with \
➢ Other characters represent themselves
➢ A character class matches one of a specified set of characters
• [character set]
• List characters individually: [abcdef]
• Give a range of characters: [a-z]
• Beware of [A-z]
• ^ at the beginning negates the class
❑ Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

❑ Predefined character classes

Name Equivalent Pattern Matches


\d [0-9] A digit
\D [^0-9] Not a digit
\w [A-Za-z_0-9] A word character (alphanumeric)
\W [^A-Za-z_0-9] Not a word character
\s [ \r\t\n\f] A whitespace character
\S [^ \r\t\n\f] Not a whitespace character
Repeated Matches
➢ A pattern can be repeated a fixed number of times by following it with a pair of curly
braces enclosing a count
➢ A pattern can be repeated by following it with one of the following special characters
• * indicates zero or more repetitions of the previous pattern
• + indicates one or more of the previous pattern
• ? indicates zero or one of the previous pattern
➢ Examples
• /\(\d{3}\)\d{3}-\d{4}/ might represent a telephone number
• /[$_a-zA-Z][$_a-zA-Z0-9]*/ matches identifiers

Anchors
➢ Anchors in regular expressions match positions rather than characters
• Anchors are 0 width and may not take multiplicity modifiers
➢ Anchoring to the end of a string
• ^ at the beginning of a pattern matches the beginning of a
string
• $ at the end of a pattern matches the end of a string
• The $ in /a$b/ matches a $ character
➢ Anchoring at a word boundary
• \b matches the position between a word character and a
non-word character or the beginning or the end of a string
• /\bthe\b/ will match ‘the’ but not ‘theatre’ and will also
match ‘the’ in the string ‘one of the best’
Pattern Modifiers
➢ Pattern modifiers are specified by characters that follow the closing / of a pattern
➢ Modifiers modify the way a pattern is interpreted or used
➢ The x modifier causes whitespace in the pattern to be ignored
• This allows better formatting of the pattern
• \s still retains its meaning
➢ The g modifier is explained in the following
Other Pattern Matching Methods
➢ The replace method takes a pattern parameter and a string parameter
The method replaces a match of the pattern in the target string with the second parameter
A g modifier on the pattern causes multiple replacements
➢ Parentheses can be used in patterns to mark sub-patterns
The pattern matching machinery will remember the parts of a matched string that correspond to
sub-patterns
➢ The match method takes one pattern parameter
Without a g modifier, the return is an array of the match and parameterized sub-matches
With a g modifier, the return is an array of all matches
➢ The split method splits the object string using the pattern to specify the split points
Errors in Scripts
➢ JavaScript errors are detected by the browser
➢ Different browsers report this differently
• Firefox uses a special console
➢ Support for debugging is provided
• In IE 7, the debugger is part of the browser
• For Firefox 2, plug-ins are available
• These include Venkman and Firebug
Develop and demonstrate, using Javascript script, a XHTML document that collects the USN ( the valid format is: A digit
from 1 to 4 followed by two upper-case characters followed by two digits followed by two upper-case characters
followed by three digits; no embedded spaces allowed) of the user. Event handler must be included for the form element
that collects this information to validate the input. Messages in the alert windows must be produced when errors are
detected.
b) Modify the above program to get the current semester also (restricted
to be a number from 1 to 8)

You might also like