Module2 JS
Module2 JS
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
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>
➢ 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
• //
• /* … */
</head>
<body>
<script type="text/javascript">
document.write("Hello World Program");
</script>
</body>
</html>
Primitive Types
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)
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
Var str=“George”
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
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
}
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)
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
• 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:- " + fruits.join(" : "), "<br/>");
document.write("Rev Operation:- " + fruits.reverse(), "<br/>");
document.write("Sort Operation:- " + num.sort(), "<br/>");
document.write("Slice Operation:- " + 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/>");
</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 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
</body>
</html>
Fun.html
Sum of all Arguments
</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:
</body>
</html>
<!DOCTYPE html> Get element by ID, Onclick event
<html>
<body>
<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 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
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 |
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)