Javascript Notes by Heera Singh Bellary
Javascript Notes by Heera Singh Bellary
Javascript Notes by Heera Singh Bellary
=======================================================================
What is JavaScript?
JavaScript started life as LiveScript, but Netscape changed the
name, possibly because of the excitement being generated by Java
To JavaScript. JavaScript made its first appearance in Netscape 2.0 in
1995 with a name LiveScript.
JavaScript is a lightweight, interpreted programming language
with object-oriented capabilities that allows you to build interactivity
into otherwise static HTML pages.
The general-purpose core of the language has been embedded
in Netscape, Internet Explorer, and other web browsers
The ECMA-262 Specification defined a standard version of the
core JavaScript language.
JavaScript is:
1) JavaScript is a lightweight, interpreted programming language
2) Designed for creating network-centric applications
3) Complementary to and integrated with Java
4) Complementary to and integrated with HTML
5) Open and cross-platform
==============================================
=========================
Prepared by HEERA SINGH .T
1
JavaScript
=======================================================================
==============================================
=========================
Prepared by HEERA SINGH .T
2
JavaScript
=======================================================================
1.6.1 language:
This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of
HTML (and XHTML, its successor) have phased out the use of this
attribute.
1.6.2 type:
This attribute is what is now recommended to indicate the
scripting language in use and its value should be set to
"text/javascript".
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
==============================================
=========================
Prepared by HEERA SINGH .T
3
JavaScript
=======================================================================
signifies a comment in Javascript, so we add that to prevent a
browser from reading the end of the HTML comment in as a piece of
Javascript code.
Next, we call a function document.write which writes a string
into our HTML document. This function can be used to write text,
HTML, or both. So above code will display following result:
Hello World!
==============================================
=========================
Prepared by HEERA SINGH .T
4
JavaScript
=======================================================================
NOTE: Care should be taken while writing your variable and
function names in JavaScript.
Example:
<script language="javascript" type="text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
5
JavaScript
=======================================================================
2.2 JavaScript in Firefox:
Here are simple steps to turn on or turn off JavaScript in your
Firefox:
1) Follow Tools-> Optionsfrom the menu
2) Select Content option from the dialog box
3) Select Enable JavaScript checkbox
4) Finally click OK and come out
To disable JavaScript support in your Firefox, you should not
select Enable JavaScript checkbox.
==============================================
=========================
Prepared by HEERA SINGH .T
6
JavaScript
=======================================================================
3) Script in <body>...</body> and <head>...</head>
sections.
4) Script in and external file and then include in
<head>...</head> section.
In the following section we will see how we can put JavaScript
in different ways:
sayHello
==============================================
=========================
Prepared by HEERA SINGH .T
7
JavaScript
=======================================================================
This will produce following result:
Hello World
This is web page body
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say
Hello" />
</body>
</html>
<html>
<head>
==============================================
=========================
Prepared by HEERA SINGH .T
8
JavaScript
=======================================================================
==============================================
=========================
Prepared by HEERA SINGH .T
9
JavaScript
=======================================================================
place data into these containers and then refer to the data simply by
naming the container.
Before you use a variable in a JavaScript program, you must
declare it. Variables are declared with the var keyword as follows:
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as
follows:
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
10
JavaScript
=======================================================================
1) Global Variables: A global variable has global scope which
means it is defined everywhere in your JavaScript code.
2) Local Variables: A local variable will be visible only within
a function where it is defined. Function parameters are
always local to that function.
Within the body of a function, a local variable takes
precedence over a global variable with the same name. If you declare
a local variable or function parameter with the same name as a
global variable, you effectively hide the global variable. Following
example explains it:
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
11
JavaScript
=======================================================================
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
2. JavaScript Operators
5.1 What is an operator?
Simple answer can be given using expression 4 + 5 is equal to
9. Here 4 and 5 are called operands and + is called operator.
JavaScript language supports following type of operators.
1) Arithmetic Operators
2) Comparision Operators
3) Logical (or Relational) Operators
4) Assignment Operators
5) Conditional (or ternary) Operators
Lets have a look on all operators one by one.
A + B will
+ Adds two operands
give 30
A * B will give
* Multiply both operands
200
B / A will give
/ Divide numerator by denumerator
2
==============================================
=========================
Prepared by HEERA SINGH .T
12
JavaScript
=======================================================================
Note: Addition operator (+) works for Numeric as well as
Strings. e.g. "a" + 10 will give "a10".
==============================================
=========================
Prepared by HEERA SINGH .T
13
JavaScript
=======================================================================
then condition becomes true.
==============================================
=========================
Prepared by HEERA SINGH .T
14
JavaScript
=======================================================================
preserve the sign of the result. If the
first operand is positive, the result
has zeros placed in the high bits; if
the first operand is negative, the
result has ones placed in the high
bits. Shifting a value right one place
is equivalent to dividing by 2
(discarding the remainder), shifting
right two places is equivalent to
integer division by 4, and so on.
Operato
Description Example
r
==============================================
=========================
Prepared by HEERA SINGH .T
15
JavaScript
=======================================================================
Operato
Description Example
r
If Condition is true ?
?: Conditional Expression Then value X :
Otherwise value Y
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
==============================================
=========================
Prepared by HEERA SINGH .T
16
JavaScript
=======================================================================
JavaScript supports conditional statements which are used to
perform different actions based on different conditions. Here we will
explain if..else statement.
JavaScript supports following forms of if..else statement:
1) if statement
2) if...else statement
3) if...else if... statement.
6.1 if statement:
The if statement is the fundamental control statement that
allows JavaScript to make decisions and execute statements
conditionally.
Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
==============================================
=========================
Prepared by HEERA SINGH .T
17
JavaScript
=======================================================================
<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
18
JavaScript
=======================================================================
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
==============================================
=========================
Prepared by HEERA SINGH .T
19
JavaScript
=======================================================================
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
Example:
Consider a case if you do not use break statement:
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//--> </script>
==============================================
=========================
Prepared by HEERA SINGH .T
20
JavaScript
=======================================================================
Unknown grade
Exiting switch block
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
21
JavaScript
=======================================================================
Current Count : 9
Loop stopped!
==============================================
=========================
Prepared by HEERA SINGH .T
22
JavaScript
=======================================================================
3) The iteration statement where you can increase or decrease
your counter.
You can put all the three parts in a single line separated by a
semicolon.
Syntax:
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example:
Following example illustrates a basic for loop:
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
23
JavaScript
=======================================================================
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
24
JavaScript
=======================================================================
come out of any loop or to start the next iteration of any loop
respectively.
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
25
JavaScript
=======================================================================
This example illustrates the use of a continue statement with
a while loop. Notice how the continue statement is used to skip
printing when the index held in variable x reaches 5:
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Example 1:
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++)
{
==============================================
=========================
Prepared by HEERA SINGH .T
26
JavaScript
=======================================================================
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++)
{
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Example 2:
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
==============================================
=========================
Prepared by HEERA SINGH .T
27
JavaScript
=======================================================================
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
==============================================
=========================
Prepared by HEERA SINGH .T
28
JavaScript
=======================================================================
}
//-->
</script>
Example:
A simple function that takes no parameters called sayHello is
defined here:
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>
==============================================
=========================
Prepared by HEERA SINGH .T
29
JavaScript
=======================================================================
<script type="text/javascript">
<!--
sayHello('Zara', 7 );
//-->
</script>
<script type="text/javascript">
<!--
function concatenate(first, last)
{
var full;
==============================================
=========================
Prepared by HEERA SINGH .T
30
JavaScript
=======================================================================
13. JavaScript Events
13.1 What is an Event ?
JavaScript's interaction with HTML is handled through events
that occur when the user or browser manipulates a page.
When the page loads, that is an event. When the user clicks a
button, that click, too, is an event. Another example of events are like
pressing any key, closing window, resizing window etc.
Developers can use these events to execute JavaScript coded
responses, which cause buttons to close windows, messages to be
displayed to users, data to be validated, and virtually any other type
of response imaginable to occur.
Events are a part of the Document Object Model (DOM) Level 3
and every HTML element have a certain set of events which can
trigger JavaScript Code.
Please go through this small tutorial for a better understanding
HTML Event Reference. Here we will see few examples to
understand a relation between Event and JavaScript:
This will produce following result and when you click Hello
button then onclick event will occur which will trigger sayHello()
function.(in the result I have pasted a box by typing say
hello ,when u try this example u come to know the result
onclick try it)
Say Hello
==============================================
=========================
Prepared by HEERA SINGH .T
31
JavaScript
=======================================================================
==============================================
=========================
Prepared by HEERA SINGH .T
32
JavaScript
=======================================================================
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
You can change different images using these two event types
or you can create help baloon to help your users.
==============================================
=========================
Prepared by HEERA SINGH .T
33
JavaScript
=======================================================================
onmouseout script Script runs when mouse pointer
moves out of an element
==============================================
=========================
Prepared by HEERA SINGH .T
34
JavaScript
=======================================================================
JavaScript can also manipulate cookies using the cookie
property of the Document object. JavaScript can read, create, modify,
and delete the cookie or cookies that apply to the current web page.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) +
";";
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie"
onclick="WriteCookie();"/>
</form>
</body>
</html>
==============================================
=========================
Prepared by HEERA SINGH .T
35
JavaScript
=======================================================================
This will produce following result. Now enter something in the
text box and press the button "Set Cookie" to set the cookies.
Now your machine has a cookie called name. You can set
multiple cookies using multiple key=value pairs separated by
comma.
==============================================
=========================
Prepared by HEERA SINGH .T
36
JavaScript
=======================================================================
(in the result I have pasted a box by typing say hello
,when u try this example u come to know the result try it)
==============================================
=========================
Prepared by HEERA SINGH .T
37
JavaScript
=======================================================================
The following example illustrates how to delete cookie by
setting expiration date one Month in past :
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) +
";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.getGMTString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie"
onclick="WriteCookie()"/>
</form>
</body>
</html>
Note: Instead of setting date, you can see new time using setTime()
function.
1) You did not like the name of your domain and you are moving
to a new one. Same time you want to direct your all visitors to
new site. In such case you can maintain your old domain but
put a single page with a page re-direction so that your all old
domain visitors can come to your new domain.
2) You have build-up various pages based on browser versions or
their names or may be based on different countries, then
instead of using your server side page redirection you can use
client side page redirection to land your users on appropriate
page.
==============================================
=========================
Prepared by HEERA SINGH .T
38
JavaScript
=======================================================================
3) The Search Engines may have already indexed your pages. But
while moving to another domain then you would not like to lose
your visitors coming through search engines. So you can use
client side page redirection. But keep in mind this should not
be done to make search engine a fool otherwise this could get
your web site banned.
Example 2:
You can show an appropriate message to your site visitors
before redirecting them to a new page. This would need a bit time
delay to load a new page. Following is the simple example to
implement the same:
<head>
<script type="text/javascript">
<!--
function Redirect()
{
window.location="http://www.newlocation.com";
}
document.write("You will be redirected to main page in 10
sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
Here setTimeout() is a built-in JavaScript function which can be
used to execute another function after a given time interval.
Example 3:
Following is the example to redirect site visitors on different
pages based on their browsers :
<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName;
if( browsername == "Netscape" )
==============================================
=========================
Prepared by HEERA SINGH .T
39
JavaScript
=======================================================================
{
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
window.location="http://www.location.com/ie.htm";
}
else
{
window.location="http://www.location.com/other.htm";
}
//-->
</script>
</head>
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>
==============================================
=========================
Prepared by HEERA SINGH .T
40
JavaScript
=======================================================================
If the user clicks on OK button the window method confirm()
will return true. If the user clicks on the Cancel button confirm()
returns false. You can use confirmation dialog box as follows:
<head>
<script type="text/javascript">
<!--
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
</head>
<head>
<script type="text/javascript">
<!--
var retVal = prompt("Enter your name : ", "your name
here");
alert("You have entered : " + retVal );
//-->
</script>
</head>
==============================================
=========================
Prepared by HEERA SINGH .T
41
JavaScript
=======================================================================
<script type="text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1:
The most common use for this operator is in a client-side
javascript: URL, where it allows you to evaluate an expression for its
side effects without the browser displaying the value of the evaluated
expression.
Here the expression alert('Warning!!!') is evaluated but it is not
loaded back into the current document:
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
Example 2:
Another example the following link does nothing because the
expression "0" has no effect in JavaScript. Here the expression "0" is
evaluated but it is not loaded back into the current document:
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(0))">Click me!</a>
</body>
Example 3:
Another use for void is to purposely generate the undefined
value as follows:
<head>
<script type="text/javascript">
<!--
==============================================
=========================
Prepared by HEERA SINGH .T
42
JavaScript
=======================================================================
function getValue(){
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script></head>
This will produce following button which let you print this page.
Try it by clicking:(Try this example) .(in the result I have pasted a
box by typing say hello ,when u try this example u come to
know the result onclick try it)
Print
This serves your purpose to get page printed out, but this is
not a recommended way of giving printing facility. A printer friendly
page is really just a page with text, no images, graphics, or
advertising.
You can do one of the followings to make a page printer
friendly:
1) Make a copy of the page and leave out unwanted text and
graphics, then link to that printer friendly page from the
original. Check Example.
2) If you do not want to keep extra copy of a page then you can
mark your printable text using proper comments like <!--
PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then
you can use PERL or any other script in background to purge
==============================================
=========================
Prepared by HEERA SINGH .T
43
JavaScript
=======================================================================
printable text and display for final printing. Our site is using
same method to give print facility to our site visitors. Check
Example.
Example:
Following is a simple example to show how to get a document
title using "title" property of document object:
var str = document.title;
==============================================
=========================
Prepared by HEERA SINGH .T
44
JavaScript
=======================================================================
Methods are useful for everything from displaying the contents
of the object to the screen to performing complex mathematical
operations on a group of local properties and parameters.
Example:
Following is a simple example to show how to use write()
method of document object to write any content on the document:
document.write("This is test");
Example 2:
==============================================
=========================
Prepared by HEERA SINGH .T
45
JavaScript
=======================================================================
This example demonstrates how to create an object with a
User-Defined Function. Here this keyword is used to refer to the
object that has been passed to a function:
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}</script></head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author +
"<br>");
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
46
JavaScript
=======================================================================
Example:
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}</script></head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author +
"<br>");
document.write("Book price is : " + myBook.price +
"<br>");
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
47
JavaScript
=======================================================================
19.6.5 JavaScript Date Object
19.6.6 JavaScript Math Object
19.6.7 JavaScript RegExp Object
Property Description
==============================================
=========================
Prepared by HEERA SINGH .T
48
JavaScript
=======================================================================
var val = Number.MAX_VALUE;
Example:
Here is the example showing the usage of this property.
<html><head>
<script type="text/javascript">
<!--
function showValue()
{
var val = Number.MAX_VALUE;
alert("Value of Number.MAX_VALUE : " + val );
}
//-->
</script></head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();"
/>
</form></body></html>
Example:
Here is the example showing the usage of this property.
<html><head>
<script type="text/javascript">
<!--
function showValue()
{
var val = Number.MIN_VALUE;
alert("Value of Number.MIN_VALUE : " + val );
}
//--></script></head>
<body>
<p>Click the following to see the result:</p>
<form>
==============================================
=========================
Prepared by HEERA SINGH .T
49
JavaScript
=======================================================================
<input type="button" value="Click Me" onclick="showValue();"
/>
</form></body></html>
Example:
Here dayOfMonth is assigned NaN if it is greater than 31, and a
message is displayed indicating the valid range:
<html><head>
<script type="text/javascript">
<!--
function showValue()
{
var dayOfMonth = 50;
if (dayOfMonth < 1 || dayOfMonth > 31)
{
dayOfMonth = Number.NaN
alert("Day of Month must be between 1 and 31.")
} alert("Value of dayOfMonth : " + dayOfMonth );
}//--></script></head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();"
/>
</form></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
50
JavaScript
=======================================================================
This is a special numeric value representing a value less than
Number.MIN_VALUE. This value is represented as "-Infinity". This
value resembles an infinity in its mathematical behavior. For
example, anything multiplied by NEGATIVE_INFINITY is
NEGATIVE_INFINITY, and anything divided by NEGATIVE_INFINITY is
zero.
Because NEGATIVE_INFINITY is a constant, it is a read-only
property of Number.
Syntax:
You can access this property using the following syntax:
var val = Number.NEGATIVE_INFINITY;
Example:
Here is an example showing usage of this property:
<html><head>
<script type="text/javascript">
<!--
function showValue(){
var smallNumber = (-Number.MAX_VALUE) * 2
if (smallNumber == Number.NEGATIVE_INFINITY) {
alert("Value of smallNumber : " + smallNumber );
}}//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();"
/>
</form></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
51
JavaScript
=======================================================================
<html><head>
<script type="text/javascript">
<!--
function showValue()
{
var bigNumber = Number.MAX_VALUE * 2
if (bigNumber == Number.POSITIVE_INFINITY) {
alert("Value of bigNumber : " + bigNumber );
}
}//--></script></head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();"
/>
</form></body></html>
Description:
The prototype property allows you to add properties and
methods to any object (Number, Boolean, String and Date etc).
Note: Prototype is a global property which is available with
almost all the objects.
Syntax:
object.prototype.name = value
Example:
Here is an example showing how to use the prototype property
to add a property to an object:
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}</script></head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author +
==============================================
=========================
Prepared by HEERA SINGH .T
52
JavaScript
=======================================================================
"<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script></body></html>
The Number object contains only the default methods that are
part of every object's definition.
Method Description
==============================================
=========================
Prepared by HEERA SINGH .T
53
JavaScript
=======================================================================
Syntax:
number.constructor()
Here is the detail of parameters:
• NA
Return Value:
Returns the function that created this object's instance.
Example:
<html><head>
<title>JavaScript constructor() Method</title></head>
<body>
<script type="text/javascript">
var num = new Number( 177.1234 );
document.write("num.constructor() is : " + num.constructor);
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
54
JavaScript
=======================================================================
document.write("num.toExponential(4) is : " + val );
document.write("<br />");
val = num.toExponential(2);
document.write("num.toExponential(2) is : " + val);
document.write("<br />");
val = 77.1234.toExponential();
document.write("77.1234.toExponential()is : " + val );
document.write("<br />");
val = 77.1234.toExponential();
document.write("77 .toExponential() is : " + val);
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
55
JavaScript
=======================================================================
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
56
JavaScript
=======================================================================
<html><head>
<title>JavaScript toPrecision() Method </title></head>
<body>
<script type="text/javascript">
var num = new Number(7.123456);
document.write("num.toPrecision() is " + num.toPrecision());
document.write("<br />");
document.write("num.toPrecision(4) is " +
num.toPrecision(4));
document.write("<br />");
document.write("num.toPrecision(3) is " +
num.toPrecision(2));
document.write("<br />");
document.write("num.toPrecision(1) is " +
num.toPrecision(1));
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
57
JavaScript
=======================================================================
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
58
JavaScript
=======================================================================
Returns a reference to the Boolean
a) constructor
function that created the object.
==============================================
=========================
Prepared by HEERA SINGH .T
59
JavaScript
=======================================================================
</script></head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author +
"<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
60
JavaScript
=======================================================================
<script type="text/javascript">
function book(title, publisher, price)
{
this.title = title;
this.publisher = publisher;
this.price = price;
}
var newBook = new book("Perl","Leo Inc",200);
document.write(newBook.toSource());
</script></body></html>
This will produce following result:
({title:"Perl", publisher:"Leo Inc", price:200})
==============================================
=========================
Prepared by HEERA SINGH .T
61
JavaScript
=======================================================================
<html><head>
<title>JavaScript valueOf() Method</title></head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.valueOf is : " + flag.valueOf() );
</script></body></html>
This will produce following result:
flag.valueOf is : false
==============================================
=========================
Prepared by HEERA SINGH .T
62
JavaScript
=======================================================================
<html><head>
<title>JavaScript String constructor Method</title></head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.constructor is:" + str.constructor);
</script></body></html>
Example:
Here is an example showing how to use the prototype property
to add a property to an object:
<html><head>
==============================================
=========================
Prepared by HEERA SINGH .T
63
JavaScript
=======================================================================
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;}
</script></head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author +
"<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
64
JavaScript
=======================================================================
same as the given string in sort
order.
==============================================
=========================
Prepared by HEERA SINGH .T
65
JavaScript
=======================================================================
Example:
<html><head>
<title>JavaScript String charAt() Method</title></head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("<br />str.charAt(1) is:" + str.charAt(1));
document.writeln("<br />str.charAt(2) is:" + str.charAt(2));
document.writeln("<br />str.charAt(3) is:" + str.charAt(3));
document.writeln("<br />str.charAt(4) is:" + str.charAt(4));
document.writeln("<br />str.charAt(5) is:" + str.charAt(5));
</script></body></html>
This will produce following result:
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
==============================================
=========================
Prepared by HEERA SINGH .T
66
JavaScript
=======================================================================
string.charCodeAt(index);
index: An integer between 0 and 1 less than the length of the string;
if unspecified, defaults to 0.
Return Value:
Returns a number indicating the Unicode value of the
character at the given index. This returns NaN if the given index is
not between 0 and 1 less than the length of the string.
Example:
<html><head>
<title>JavaScript String charCodeAt() Method</title></head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
document.write("<br />str.charCodeAt(1) is:" +
str.charCodeAt(1));
document.write("<br />str.charCodeAt(2) is:" +
str.charCodeAt(2));
document.write("<br />str.charCodeAt(3) is:" +
str.charCodeAt(3));
document.write("<br />str.charCodeAt(4) is:" +
str.charCodeAt(4));
document.write("<br />str.charCodeAt(5) is:" +
str.charCodeAt(5));
</script></body></html>
This will produce following result:
str.charCodeAt(0) is:84
str.charCodeAt(1) is:104
str.charCodeAt(2) is:105
str.charCodeAt(3) is:115
str.charCodeAt(4) is:32
str.charCodeAt(5) is:105
c) concat()
Description:
This method adds two or more strings and returns a new single
string.
Syntax:
string.concat(string2, string3[, ..., stringN]);
Here is the detail of parameters:
• string2...stringN : These are the strings to be concatenated.
Return Value:
Returns a single concatenated string.
Example:
==============================================
=========================
Prepared by HEERA SINGH .T
67
JavaScript
=======================================================================
<html><head>
<title>JavaScript String concat() Method</title></head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );
document.write("Concatenated String :" + str3);
</script></body></html>
This will produce following result:
Concatenated String :This is string oneThis is string two.
d) indexOf()
Description:
This method returns the index within the calling String object
of the first occurrence of the specified value, starting the search at
fromIndex or -1 if the value is not found.
Syntax:
string.indexOf(searchValue[, fromIndex])
Here is the detail of parameters:
1) searchValue : A string representing the value to search for.
2) fromIndex : The location within the calling string to start the
search from. It can be any integer between 0 and the length of
the string. The default value is 0.
Return Value:
Returns the index of the found occurrence otherwise -1 if not found.
Example:
<html><head>
<title>JavaScript String indexOf() Method</title></head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var index = str1.indexOf( "string" );
document.write("indexOf found String :" + index );
document.write("<br />");
var index = str1.indexOf( "one" );
document.write("indexOf found String :" + index );
</script></body></html>
This will produce following result:
indexOf found String :8
indexOf found String :15
e) lastIndexOf()
Description:
==============================================
=========================
Prepared by HEERA SINGH .T
68
JavaScript
=======================================================================
This method returns the index within the calling String object
of the last occurrence of the specified value, starting the search at
fromIndex or -1 if the value is not found.
Syntax:
string.lastIndexOf(searchValue[, fromIndex])
Here is the detail of parameters:
1) searchValue : A string representing the value to search for.
2) fromIndex : The location within the calling string to start the
search from. It can be any integer between 0 and the length of the
string. The default value is 0.
Return Value:
Returns the index of the last found occurrence otherwise -1 if
not found.
Example:
<html><head>
<title>JavaScript String lastIndexOf() Method</title></head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
document.write("lastIndexOf found String :" + index );
document.write("<br />");
var index = str1.lastIndexOf( "one" );
document.write("lastIndexOf found String :" + index );
</script></body></html>
This will produce following result:
lastIndexOf found String :29
lastIndexOf found String :15
f) localeCompare()
Description:
This method returns a number indicating whether a reference
string comes before or after or is the same as the given string in sort
order.
Syntax:
string.localeCompare( param )
Here is the detail of parameters:
1) param : A string to be compared with string object.
Return Value:
0: It string matches 100%.
-1 : no match, and the parameter value comes before the string
object's value in the locale sort order
1 : no match, and the parameter value comes after the string
object's value in the locale sort order
Example:
<html><head>
==============================================
=========================
Prepared by HEERA SINGH .T
69
JavaScript
=======================================================================
<title>JavaScript String localeCompare() Method</title></head>
<body>
<script type="text/javascript">
var str1 = new String( "This is beautiful string" );
var index = str1.localeCompare( "XYZ" );
document.write("localeCompare first :" + index );
document.write("<br />" );
var index = str1.localeCompare( "AbCD ?" );
document.write("localeCompare second :" + index );
</script></body></html>
This will produce following result:
localeCompare first :-1
localeCompare second :1
g) match()
Description:
This method is used to retrieve the matches when matching a
string against a regular expression.
Syntax:
string.match( param )
Here is the detail of parameters:
param : A regular expression object.
Return Value:
If the regular expression does not include the g flag, returns the
same result as regexp.exec(string).
If the regular expression includes the g flag, the method returns an
Array containing all matches.
Example:
<html><head>
<title>JavaScript String match() Method</title></head>
<body>
<script type="text/javascript">
var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match( re );
document.write(found );
</script></body></html>
h) replace()
Description:
This method finds a match between a regular expression and a
string, and replaces the matched substring with a new substring.
The replacement string can include the following special
replacement patterns:
==============================================
=========================
Prepared by HEERA SINGH .T
70
JavaScript
=======================================================================
Patter
Inserts
n
$$ Inserts a "$".
==============================================
=========================
Prepared by HEERA SINGH .T
71
JavaScript
=======================================================================
<script type="text/javascript">
var re = /(\w+)\s(\w+)/;
var str = "Gopi Heera";
var newstr = str.replace(re, "$2, $1");
document.write(newstr);
</script></body></html>
i) search()
Description:
This method Executes the search for a match between a
regular expression and this String object.
Syntax:
string.search(regexp);
Here is the detail of parameters:
regexp : A regular expression object. If a non-RegExp object obj
is passed, it is implicitly converted to a RegExp by using new
RegExp(obj)
Return Value:
If successful, search returns the index of the regular expression
inside the string. Otherwise, it returns -1.
Example:
<html><head>
<title>JavaScript String search() Method</title></head>
<body>
<script type="text/javascript">
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
if ( str.search(re) == -1 ){
document.write("Does not contain Apples" );
}else{
document.write("Contains Apples" );
}
</script></body></html>
This will produce following result:
Contains Apples
j) slice()
Description:
This method extracts a section of a string and returns a new string.
Syntax:
string.slice( beginslice [, endSlice] );
Here is the detail of parameters:
beginSlice : The zero-based index at which to begin extraction.
endSlice : The zero-based index at which to end extraction. If
omitted, slice extracts to the end of the string.
==============================================
=========================
Prepared by HEERA SINGH .T
72
JavaScript
=======================================================================
Note: As a negative index, endSlice indicates an offset from
the end of the string. string.slice(2,-1) extracts the third character
through the second to last character in the string.
Return Value:
If successful, slice returns the index of the regular expression
inside the string. Otherwise, it returns -1.
Example:
<html><head>
<title>JavaScript String slice() Method</title></head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
var sliced = str.slice(3, -2);
document.write( sliced );
</script></body></html>
This will produce following result:
les are round, and apples are juic
k) split()
Description:
This method splits a String object into an array of strings by
separating the string into substrings.
Syntax:
string.split([separator][, limit]);
Here is the detail of parameters:
separator : Specifies the character to use for separating the
string. If separator is omitted, the array returned contains one
element consisting of the entire string.
limit : Integer specifying a limit on the number of splits to be
found.
Return Value:
The split method returns the new array. Also, when the string
is empty, split returns an array containing one empty string, rather
than an empty array.
Example:
<html><head>
<title>JavaScript String split() Method</title></head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
document.write( splitted );
</script></body></html>
This will produce following result:
Apples,are,round,
==============================================
=========================
Prepared by HEERA SINGH .T
73
JavaScript
=======================================================================
l) substr()
Description:
This method returns the characters in a string beginning at the
specified location through the specified number of characters.
Syntax:
string.substr(start[, length]);
Here is the detail of parameters:
start : Location at which to begin extracting characters (an
integer between 0 and one less than the length of the string).
length : The number of characters to extract.
Note: If start is negative, substr uses it as a character index
from the end of the string.
Return Value:
• The substr method returns the new sub string based on given
parameters.
Example:
<html><head>
<title>JavaScript String substr() Method</title></head>
<body>
<script type="text/javascript">
var str = "JavaScript material by heera singh. T.";
document.write("(1,2): " + str.substr(1,2));
document.write("<br />(-2,2): " + str.substr(-2,2));
document.write("<br />(1): " + str.substr(1));
document.write("<br />(-20, 2): " + str.substr(-20,2));
document.write("<br />(20, 2): " + str.substr(20,2));
</script></body></html>
This will produce following result:
(1,2):av
(-2,2):Ja
(1):avaScript material by heera singh. T.
(-20, 2): Ja
(20, 2): by
m) substring()
Description:
This method returns a subset of a String object.
Syntax:
string.substring(indexA, [indexB])
Here is the detail of parameters:
indexA : An integer between 0 and one less than the length of
the string.
indexB : (optional) An integer between 0 and the length of the
string.
Return Value:
• The substring method returns the new sub string based on
given parameters.
==============================================
=========================
Prepared by HEERA SINGH .T
74
JavaScript
=======================================================================
Example:
<html><head>
<title>JavaScript String substring() Method</title></head>
<body>
<script type="text/javascript">
var str = "JavaScript material by heera singh. T.";
document.write("(1,2): " + str.substring(1,2));
document.write("<br />(0,10): " + str.substring(0, 10));
document.write("<br />(5): " + str.substring(5));
</script></body></html>
This will produce following result:
(1,2): a
(0,10): JavaScript
(5): cript material by heera singh. T.
n) toLocaleLowerCase()
Description:
This method is used to convert the characters within a string to
lower case while respecting the current locale. For most languages,
this will return the same as toLowerCase.
Syntax:
string.toLocaleLowerCase( )
Here is the detail of parameters:
NA
Return Value:
• A string into lower case with the current locale.
Example:
<html><head>
<title>JavaScript String toLocaleLowerCase()
Method</title></head>
<body>
<script type="text/javascript">
var str = " JavaScript material by heera singh. T.";
document.write(str.toLocaleLowerCase( ));
</script></body></html>
This will produce following result:
javascript material by heera singh. t.
o) toLocaleUpperCase()
Description:
This method is used to convert the characters within a string to
upper case while respecting the current locale. For most languages,
this will return the same as toUpperCase.
Syntax:
string.toLocaleUpperCase( )
==============================================
=========================
Prepared by HEERA SINGH .T
75
JavaScript
=======================================================================
Here is the detail of parameters:
NA
Return Value:
A string into upper case with the current locale.
Example:
<html><head>
<title>JavaScript String toLocaleUpperCase()
Method</title></head>
<body>
<script type="text/javascript">
var str = " JavaScript material by heera singh. T.";
document.write(str.toLocaleUpperCase( ));
</script></body></html>
This will produce following result:
JAVASCRIPT MATERIAL BY HEERA SINGH. T.
p) toLowerCase()
Description:
This method returns the calling string value converted to lowercase.
Syntax:
string.toLowerCase( )
Here is the detail of parameters:
• NA
Return Value:
• Returns the calling string value converted to lowercase.
Example:
<html><head>
<title>JavaScript String toLowerCase()
Method</title></head>
<body>
<script type="text/javascript">
var str = " JAVASCRIPT MATERIAL BY HEERA SINGH. T.";
document.write(str.toLowerCase( ));
</script></body></html>
q) toString()
Description:
This method returns a string representing the specified object.
Syntax:
string.toString( )
==============================================
=========================
Prepared by HEERA SINGH .T
76
JavaScript
=======================================================================
Here is the detail of parameters:
• NA
Return Value:
• Returns a string representing the specified object.
Example:
<html><head>
<title>JavaScript String toString() Method</title></head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
</script></body></html>
This will produce following result:
Apples are round, and Apples are Juicy.
r) toUpperCase()
Description:
This method returns the calling string value converted to uppercase.
Syntax:
string.toUpperCase( )
Here is the detail of parameters:
• NA
Return Value:
• Returns a string representing the specified object.
Example:
<html><head>
<title>JavaScript String toUpperCase()
Method</title></head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toUpperCase( ));
</script></body></html>
This will produce following result:
APPLES ARE ROUND, AND APPLES ARE JUICY.
s) valueOf()
Description:
This method returns the primitive value of a String object.
Syntax:
string.valueOf( )
Here is the detail of parameters:
• NA
Return Value:
==============================================
=========================
Prepared by HEERA SINGH .T
77
JavaScript
=======================================================================
• Returns the primitive value of a String object.
Example:
<html><head>
<title>JavaScript String valueOf() Method</title></head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
document.write(str.valueOf( ));
</script></body></html>
This will produce following result:
Hello world
19.6.3 JavaScript Array Object
The Array object let's you store multiple values in a single
variable.
Syntax:
Creating a Array object:
var list = new Array( "three", "four", "five",1,2,3 );
The Array parameter is a list of strings or integers. When you
specify a single numeric parameter with the Array constructor, you
specify the initial length of the array. The maximum length allowed
for an array is 4,294,967,295.
You can create array by simply assigning values as follows:
var list = [ "three", "four", "five",1,2,3 ];
You will use ordinal numbers to access and to set values inside
an array as follows:
list[0] is the first element
list[1] is the second element
list[2] is the third element
list[3] is the third element
list[4] is the third element
list[5] is the third element
Array Properties:
Here is a list of each property and their description.
Property Description
==============================================
=========================
Prepared by HEERA SINGH .T
78
JavaScript
=======================================================================
The prototype property allows you to add
prototype
properties and methods to an object.
Array Methods
Here is a list of each method and its description.
Method Description
==============================================
=========================
Prepared by HEERA SINGH .T
79
JavaScript
=======================================================================
returns that element.
==============================================
=========================
Prepared by HEERA SINGH .T
80
JavaScript
=======================================================================
array.length
Here is the detail of parameters:
• NA
Return Value:
Returns the length of the array.
Example:
<html><head>
<title>JavaScript Array length Property</title></head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.length is : " + arr.length);
</script></body></html>
This will produce following result:
arr.length is : 3
==============================================
=========================
Prepared by HEERA SINGH .T
81
JavaScript
=======================================================================
array.every(callback[, thisObject]);
Here is the detail of parameters:
• callback : Function to test for each element.
• thisObject : Object to use as this when executing callback.
Return Value:
Returns true if every element in this array satisfies the provided
testing function.
Compatibility:
This method is a JavaScript extension to the ECMA-262
standard; as such it may not be present in other implementations of
the standard. To make it work you need to add following code at the
top of your script:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
Example:
<html><head>
<title>JavaScript Array every Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
==============================================
=========================
Prepared by HEERA SINGH .T
82
JavaScript
=======================================================================
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
document.write("First Test Value : " + passed );
passed = [12, 54, 18, 130, 44].every(isBigEnough);
document.write("Second Test Value : " + passed );
</script></body></html>
This will produce following result:
First Test Value : falseSecond Test Value : true
==============================================
=========================
Prepared by HEERA SINGH .T
83
JavaScript
=======================================================================
};
}
Example:
<html><head>
<title>JavaScript Array filter Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
document.write("Filtered Value : " + filtered );
</script></body></html>
This will produce following result:
Filtered Value : 12,130,44
==============================================
=========================
Prepared by HEERA SINGH .T
84
JavaScript
=======================================================================
Return Value:
Returns the index of the found element.
Compatibility:
This method is a JavaScript extension to the ECMA-262
standard; as such it may not be present in other implementations of
the standard. To make it work you need to add following code at the
top of your script:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Example:
<html><head>
<title>JavaScript Array indexOf Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
==============================================
=========================
Prepared by HEERA SINGH .T
85
JavaScript
=======================================================================
};
}
var index = [12, 5, 8, 130, 44].indexOf(8);
document.write("index is : " + index );
var index = [12, 5, 8, 130, 44].indexOf(13);
document.write("<br />index is : " + index );
</script></body></html>
This will produce following result:
index is : 2
index is : -1
==============================================
=========================
Prepared by HEERA SINGH .T
86
JavaScript
=======================================================================
array.lastIndexOf(searchElement[, fromIndex]);
Here is the detail of parameters:
• searchElement : Element to locate in the array.
• fromIndex : The index at which to start searching backwards.
Defaults to the array's length, i.e. the whole array will be
searched. If the index is greater than or equal to the length of the
array, the whole array will be searched. If negative, it is taken as
the offset from the end of the array.
Return Value:
Returns index of the found element from the last.
Compatibility:
This method is a JavaScript extension to the ECMA-262
standard; as such it may not be present in other implementations of
the standard. To make it work you need to add following code at the
top of your script:
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]);
if (isNaN(from))
{
from = len - 1;
}
else
{
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
else if (from >= len)
from = len - 1;
}
for (; from > -1; from--)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Example:
<html><head>
<title>JavaScript Array lastIndexOf Method</title></head>
<body>
==============================================
=========================
Prepared by HEERA SINGH .T
87
JavaScript
=======================================================================
<script type="text/javascript">
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
==============================================
=========================
Prepared by HEERA SINGH .T
88
JavaScript
=======================================================================
• thisObject : Object to use as this when executing callback.
Return Value:
Returns created array.
Compatibility:
This method is a JavaScript extension to the ECMA-262
standard; as such it may not be present in other implementations of
the standard. To make it work you need to add following code at the
top of your script:
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
Example:
<html><head>
<title>JavaScript Array map Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
document.write("roots is : " + roots );
==============================================
=========================
Prepared by HEERA SINGH .T
89
JavaScript
=======================================================================
</script></body></html>
This will produce following result:
roots is : 1,2,3
==============================================
=========================
Prepared by HEERA SINGH .T
90
JavaScript
=======================================================================
var numbers = new Array(1, 4, 9);
var length = numbers.push(10);
document.write("new numbers is : " + numbers );
length = numbers.push(20);
document.write("<br />new numbers is : " + numbers );
</script></body></html>
if (!Array.prototype.reduce)
{
Array.prototype.reduce = function(fun /*, initial*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
==============================================
=========================
Prepared by HEERA SINGH .T
91
JavaScript
=======================================================================
{
do
{
if (i in this)
{
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
}
while (true);
}
for (; i < len; i++)
{
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
Example:
<html><head>
<title>JavaScript Array reduce Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.reduce)
{
Array.prototype.reduce = function(fun /*, initial*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
rv = this[i++];
break;
==============================================
=========================
Prepared by HEERA SINGH .T
92
JavaScript
=======================================================================
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
}
while (true);
}
for (; i < len; i++)
{
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
var total = [0, 1, 2, 3].reduce(function(a, b){ return a +
b; });
document.write("total is : " + total );
</script></body></html>
array.reduceRight(callback[, initialValue]);
Here is the detail of parameters:
• callback : Function to execute on each value in the array.
• initialValue : Object to use as the first argument to the first call
of the callback.
Return Value:
Returns the reduceRightd single value of the array.
Compatibility:
This method is a JavaScript extension to the ECMA-262
standard; as such it may not be present in other implementations of
the standard. To make it work you need to add following code at the
top of your script:
if (!Array.prototype.reduceRight)
{
Array.prototype.reduceRight = function(fun /*, initial*/)
{
var len = this.length;
==============================================
=========================
Prepared by HEERA SINGH .T
93
JavaScript
=======================================================================
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value, empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = len - 1;
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
rv = this[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError();
}
while (true);
}
for (; i >= 0; i--)
{
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
Example:
<html><head>
<title>JavaScript Array reduceRight Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.reduceRight)
{
Array.prototype.reduceRight = function(fun /*, initial*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value, empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = len - 1;
==============================================
=========================
Prepared by HEERA SINGH .T
94
JavaScript
=======================================================================
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
rv = this[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError();
}
while (true);
}
for (; i >= 0; i--)
{
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
var total = [0, 1, 2, 3].reduceRight(function(a, b)
{ return a + b; });
document.write("total is : " + total );
</script></body></html>
This will produce following result:
total is : 6
array.reverse();
Here is the detail of parameters:
• NA
Return Value:
Returns the reversed single value of the array.
Example:
<html><head>
==============================================
=========================
Prepared by HEERA SINGH .T
95
JavaScript
=======================================================================
<title>JavaScript Array reverse Method</title></head>
<body>
<script type="text/javascript">
var arr = [0, 1, 2, 3].reverse();
document.write("Reversed array is : " + arr );
</script></body></html>
array.some(callback[, thisObject]);
Here is the detail of parameters:
callback : Function to test for each element.
thisObject : Object to use as this when executing callback.
Return Value:
If some element pass the test then it returns true otherwise false.
Compatibility:
==============================================
=========================
Prepared by HEERA SINGH .T
96
JavaScript
=======================================================================
This method is a JavaScript extension to the ECMA-262
standard; as such it may not be present in other implementations of
the standard. To make it work you need to add following code at the
top of your script:
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
Example:
<html><head>
<title>JavaScript Array some Method</title></head>
<body>
<script type="text/javascript">
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
document.write("Returned value is : " + retval );
var retval = [12, 5, 8, 1, 4].some(isBigEnough);
==============================================
=========================
Prepared by HEERA SINGH .T
97
JavaScript
=======================================================================
document.write("<br />Returned value is : " + retval );
</script></body></html>
Syntax:
array.splice(index, howMany, [element1][, ..., elementN]);
Here is the detail of parameters:
• index : Index at which to start changing the array.
• howMany : An integer indicating the number of old array
elements to remove. If howMany is 0, no elements are removed.
• element1, ..., elementN : The elements to add to the array. If
you don't specify any elements, splice simply removes elements
from the array.
Return Value:
Returns the extracted array based on the passed parameters.
==============================================
=========================
Prepared by HEERA SINGH .T
98
JavaScript
=======================================================================
Example:
<html><head>
<title>JavaScript Array splice Method</title></head>
<body>
<script type="text/javascript">
var arr = ["orange", "mango", "banana", "sugar", "tea"];
var removed = arr.splice(2, 0, "water");
document.write("After adding 1: " + arr );
document.write("<br />removed is: " + removed);
removed = arr.splice(3, 1);
document.write("<br />After adding 1: " + arr );
document.write("<br />removed is: " + removed);
</script></body></html>
Syntax:
array.toSource();
Here is the detail of parameters:
• NA
Return Value:
Returns a string representing the source code of the array.
Example:
<html><head>
<title>JavaScript Array toSource Method</title></head>
<body><script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
var str = arr.toSource();
document.write("Returned string is : " + str );
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
99
JavaScript
=======================================================================
String HTML wrappers
Here is a list of each method which returns a copy of the string
wrapped inside the appropriate HTML tag.
Method Description
==============================================
=========================
Prepared by HEERA SINGH .T
100
JavaScript
=======================================================================
Once a Date object is created, a number of methods allow you
to operate on it. Most methods simply allow you to get and set the
year, month, day, hour, minute, second, and millisecond fields of the
object, using either local time or UTC (universal, or GMT) time.
Syntax:
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
==============================================
=========================
Prepared by HEERA SINGH .T
101
JavaScript
=======================================================================
6. second: Integer value representing the second segment of a
time reading.
7. millisecond: Integer value representing the millisecond
segment of a time reading.
Property Description
1) constructor Specifies the function that creates
an object's prototype.
2) prototype The prototype property allows you
to add properties and methods to
an object.
Method Description
==============================================
=========================
Prepared by HEERA SINGH .T
102
JavaScript
=======================================================================
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date
according to local time.
getDay() Returns the day of the week for the specified date
according to local time.
getFullYear( Returns the year of the specified date according to
) local time.
getHours() Returns the hour in the specified date according to
local time.
getMilliseco Returns the milliseconds in the specified date
nds() according to local time.
getMinutes( Returns the minutes in the specified date according
) to local time.
getMonth() Returns the month in the specified date according
to local time.
getSeconds( Returns the seconds in the specified date according
) to local time.
getTime() Returns the numeric value of the specified date as
the number of milliseconds since January 1, 1970,
00:00:00 UTC.
getTimezon Returns the time-zone offset in minutes for the
eOffset() current locale.
getUTCDate Returns the day (date) of the month in the specified
() date according to universal time.
getUTCDay( Returns the day of the week in the specified date
) according to universal time.
getUTCFullY Returns the year in the specified date according to
ear() universal time.
getUTCHour Returns the hours in the specified date according to
s() universal time.
getUTCMillis Returns the milliseconds in the specified date
econds() according to universal time.
getUTCMinu Returns the minutes in the specified date according
tes() to universal time.
getUTCMont Returns the month in the specified date according
h() to universal time.
getUTCSeco Returns the seconds in the specified date according
nds() to universal time.
getYear() Deprecated - Returns the year in the specified
==============================================
=========================
Prepared by HEERA SINGH .T
103
JavaScript
=======================================================================
date according to local time. Use getFullYear
instead.
setDate() Sets the day of the month for a specified date
according to local time.
setFullYear( Sets the full year for a specified date according to
) local time.
setHours() Sets the hours for a specified date according to
local time.
setMilliseco Sets the milliseconds for a specified date according
nds() to local time.
setMinutes( Sets the minutes for a specified date according to
) local time.
setMonth() Sets the month for a specified date according to
local time.
setSeconds( Sets the seconds for a specified date according to
) local time.
setTime() Sets the Date object to the time represented by a
number of milliseconds since January 1, 1970,
00:00:00 UTC.
setUTCDate Sets the day of the month for a specified date
() according to universal time.
setUTCFullY Sets the full year for a specified date according to
ear() universal time.
setUTCHour Sets the hour for a specified date according to
s() universal time.
setUTCMillis Sets the milliseconds for a specified date according
econds() to universal time.
setUTCMinu Sets the minutes for a specified date according to
tes() universal time.
setUTCMont Sets the month for a specified date according to
h() universal time.
setUTCSeco Sets the seconds for a specified date according to
nds() universal time.
==============================================
=========================
Prepared by HEERA SINGH .T
104
JavaScript
=======================================================================
toLocaleDat Returns the "date" portion of the Date as a string,
eString() using the current locale's conventions.
toLocaleFor Converts a date to a string, using a format string.
mat()
toLocaleStri Converts a date to a string, using the current
ng() locale's conventions.
toLocaleTim Returns the "time" portion of the Date as a string,
eString() using the current locale's conventions.
toSource() Returns a string representing the source for an
equivalent Date object; you can use this value to
create a new object.
toString() Returns a string representing the specified Date
object.
toTimeStrin Returns the "time" portion of the Date as a human-
g() readable string.
toUTCString Converts a date to a string, using the universal time
() convention.
Method Description
Parses a string representation of a date and time
Date.parse( ) and returns the internal millisecond representation
of that date.
Returns the millisecond representation of the
Date.UTC( )
specified UTC date and time.
Description:
This returns the day of the month for the specified date according to
local time. The value returned by getDate is an integer between 1
and 31.
Syntax:
Date.getDate()
Here is the detail of parameters:
NA
Return Value:
Returns today's date and time
==============================================
=========================
Prepared by HEERA SINGH .T
105
JavaScript
=======================================================================
Example:
<html><head>
<title>JavaScript getDate
Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995
23:15:00");
document.write("getDate() : " +
dt.getDate() );
</script></body></html>
getDay() : 1
==============================================
=========================
Prepared by HEERA SINGH .T
106
JavaScript
=======================================================================
Description:
This returns the day of the week for the specified date according to
local time.The value returned by getDay is an integer corresponding
to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and
so on.
Syntax:
Date.getDay()
• NA
Return Value:
Returns the day of the week for the specified date according to local
time.
Example:
<html><head>
<title>JavaScript getDay Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getDay() : " + dt.getDay() );
</script></body></html>
getDay() : 1
Description:
Syntax:
Date.getFullYear()
Here is the detail of parameters:
==============================================
=========================
Prepared by HEERA SINGH .T
107
JavaScript
=======================================================================
•NA
Return Value:
Returns the year of the specified date according to local time.
Example:
<html><head>
<title>JavaScript getFullYear Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getFullYear() : " + dt.getFullYear() );
</script></body></html>
getFullYear() : 1995
Date.getHours()
Here is the detail of parameters:
•NA
Return Value:
Returns the hour in the specified date according to local time.
Example:
<html><head>
<title>JavaScript getHours Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getHours() : " + dt.getHours() );
</script></body></html>
getHours() : 23
==============================================
=========================
Prepared by HEERA SINGH .T
108
JavaScript
=======================================================================
This returns the milliseconds in the specified date according to local
time. The value returned by getMilliseconds is a number between 0
and 999.
Syntax:
Date.getMilliseconds()
Here is the detail of parameters:
•NA
Return Value:
Returns the milliseconds in the specified date according to local time.
Example:
<html><head>
<title>JavaScript getMilliseconds Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date( );
document.write("getMilliseconds() : " + dt.getMilliseconds() );
</script></body></html>
getMilliseconds() : 578
Date.getMinutes()
Here is the detail of parameters:
•NA
Return Value:
Returns the minutes in the specified date according to local time.
Example:
<html><head>
<title>JavaScript getMinutes Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:00" );
document.write("getMinutes() : " + dt.getMinutes() );
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
109
JavaScript
=======================================================================
This will produce following result:
getMinutes() : 15
Syntax:
Date.getMonth()
Here is the detail of parameters:
•NA
Return Value:
Returns the month in the specified date according to local time.
Example:
<html><head>
<title>JavaScript getMonth Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:00" );
document.write("getMonth() : " + dt.getMonth() );
</script></body></html>
getMonth() : 11
Date.getSeconds()
Here is the detail of parameters:
•NA
Return Value:
Returns the seconds in the specified date according to local time.
Example:
==============================================
=========================
Prepared by HEERA SINGH .T
110
JavaScript
=======================================================================
<html><head>
<title>JavaScript getSeconds Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getSeconds() : " + dt.getSeconds() );
</script></body></html>
getSeconds() : 20
Date.getTime()
Here is the detail of parameters:
•NA
Return Value:
Returns the numeric value corresponding to the time for the specified
date according to universal time.
Example:
<html><head>
<title>JavaScript getTime Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getTime() : " + dt.getTime() );
</script></body></html>
getTime() : 819913520000
==============================================
=========================
Prepared by HEERA SINGH .T
111
JavaScript
=======================================================================
Date.getYear()
Here is the detail of parameters:
•NA
Return Value:
Returns the year in the specified date according to universal time.
Example:
<html><head>
<title>JavaScript getYear Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getYear() : " + dt.getYear() );
</script></body></html>
getYear() : 208
Date.parse(datestring)
<html><head>
<title>JavaScript parse Method</title></head>
<body>
==============================================
=========================
Prepared by HEERA SINGH .T
112
JavaScript
=======================================================================
<script type="text/javascript">
var msecs = Date.parse("Jul 8, 2008");
document.write( "Number of milliseconds from 1970: " +
msecs );
</script></body></html>
Date.setDate( dayValue )
Here is the detail of parameters:
•dayValue : An integer from 1 to 31, representing the day of the
month.
Return Value:
NA
Example:
The second statement below changes the day to Aug 24 from its
original value.
<html><head>
<title>JavaScript setDate Method</title></head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setDate( 24 );
document.write( dt );
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
113
JavaScript
=======================================================================
Syntax:
Date()
Here is the detail of parameters:
•NA
Return Value:
Returns today's date and time
Example:
<html><head>
<title>JavaScript Date Method</title></head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt );
</script></body></html>
Syntax:
==============================================
=========================
Prepared by HEERA SINGH .T
114
JavaScript
=======================================================================
LN10 Natural logarithm of 10, approximately 2.302.
Math Methods
Here is a list of each method and its description.
Method Description
==============================================
=========================
Prepared by HEERA SINGH .T
115
JavaScript
=======================================================================
Returns the value of a number rounded to the
round()
nearest integer.
Math.abs( x ) ;
Here is the detail of parameters:
• x : A number.
Return Value:
Returns the absolute value of a number.
Example:
<html><head>
<title>JavaScript Math abs() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.abs(-1);
document.write("First Test Value : " + value );
var value = Math.abs(null);
document.write("<br />Second Test Value : " + value );
var value = Math.abs(20);
document.write("<br />Third Test Value : " + value );
var value = Math.abs("string");
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
116
JavaScript
=======================================================================
This method returns the arccosine in radians of a number. The acos
method returns a numeric value between 0 and pi radians for x
between -1 and 1. If the value of number is outside this range, it
returns NaN.
Syntax:
Math.acos( x ) ;
Here is the detail of parameters:
• x : A number.
Return Value:
Returns the arccosine in radians of a number.
Example:
<html><head>
<title>JavaScript Math acos() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.acos(-1);
document.write("First Test Value : " + value );
var value = Math.acos(null);
document.write("<br />Second Test Value : " + value );
var value = Math.acos(30);
document.write("<br />Third Test Value : " + value );
var value = Math.acos("string");
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
Math.asin( x ) ;
==============================================
=========================
Prepared by HEERA SINGH .T
117
JavaScript
=======================================================================
Returns the arcsine in radians of a number.
Example:
<html><head>
<title>JavaScript Math asin() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.asin(-1);
document.write("First Test Value : " + value );
var value = Math.asin(null);
document.write("<br />Second Test Value : " + value );
var value = Math.asin(30);
document.write("<br />Third Test Value : " + value );
var value = Math.asin("string");
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
Math.atan2( x, y ) ;
Here is the detail of parameters:
• x and y : Numbers.
Return Value:
Returns the arctangent in radians of a number.
==============================================
=========================
Prepared by HEERA SINGH .T
118
JavaScript
=======================================================================
Example:
<html><head>
<title>JavaScript Math atan2() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.atan2(90,15);
document.write("First Test Value : " + value );
var value = Math.atan2(15,90);
document.write("<br />Second Test Value : " + value );
var value = Math.atan2(0, -0);
document.write("<br />Third Test Value : " + value );
var value = Math.atan2(+Infinity, -Infinity);
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
Math.atan( x ) ;
Here is the detail of parameters:
• x : A number.
Return Value:
Returns the arctangent in radians of a number.
Example:
<html><head>
<title>JavaScript Math atan() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.atan(-1);
document.write("First Test Value : " + value );
var value = Math.atan(.5);
document.write("<br />Second Test Value : " + value );
var value = Math.atan(30);
document.write("<br />Third Test Value : " + value );
var value = Math.atan("string");
==============================================
=========================
Prepared by HEERA SINGH .T
119
JavaScript
=======================================================================
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
Math.ceil( x ) ;
• x : A numbers.
Return Value:
Example:
<html><head>
<title>JavaScript Math ceil() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.ceil(45.95);
document.write("First Test Value : " + value );
var value = Math.ceil(45.20);
document.write("<br />Second Test Value : " + value );
var value = Math.ceil(-45.95);
document.write("<br />Third Test Value : " + value );
var value = Math.ceil(-45.20);
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
120
JavaScript
=======================================================================
Third Test Value : -45
Fourth Test Value : -45
Math.cos( x ) ;
Here is the detail of parameters:
• x : A numbers.
Return Value:
Returns the cosine of a number.
Example:
<html><head>
<title>JavaScript Math cos() Method</title></head>
<body>
<script type="text/javascript">
var value = Math.cos(90);
document.write("First Test Value : " + value );
var value = Math.cos(30);
document.write("<br />Second Test Value : " + value );
var value = Math.cos(-1);
document.write("<br />Third Test Value : " + value );
var value = Math.cos(2*Math.PI);
document.write("<br />Fourth Test Value : " + value );
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
121
JavaScript
=======================================================================
Syntax:
A regular expression could be defined with the RegExp( ) constructor
like this:
Expression Description
The ranges shown above are general; you could also use the
range [0-3] to match any decimal digit ranging from 0 through 3, or
the range [b-v] to match any lowercase character ranging from b
through v.
Quantifiers:
The frequency or position of bracketed character sequences
and single characters can be denoted by a special character. Each
pecial character having a specific connotation. The +, *, ?, and $ flags
all follow a character sequence.
Expression Description
==============================================
=========================
Prepared by HEERA SINGH .T
122
JavaScript
=======================================================================
p's.
Examples:
Expression Description
Literal characters:
Character Description
Alphanumeric Itself
\t Tab (\u0009)
\n Newline (\u000A)
==============================================
=========================
Prepared by HEERA SINGH .T
123
JavaScript
=======================================================================
\v Vertical tab (\u000B)
Metacharacters
A metacharacter is simply an alphabetical character preceded
by a backslash that acts to give the combination a special meaning.
For instance, you can search for large money sums using the '\d'
metacharacter: /([\d]+)000/, Here \d will search for any string of
numerical character.
Character Description
. a single character
\s a whitespace character (space, tab,
newline)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[\b] a literal backspace (special case).
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the
given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers
Several modifiers are available that can make your work with regexps
much easier, like case sensitivity, searching in multiple lines etc.
Modifier Description
==============================================
=========================
Prepared by HEERA SINGH .T
124
JavaScript
=======================================================================
i Perform case-insensitive matching.
RegExp Properties:
Property Description
RegExp Methods:
Method Description
==============================================
=========================
Prepared by HEERA SINGH .T
125
JavaScript
=======================================================================
Syntax:
RegExp.constructor
Here is the detail of parameters:
• NA
Return Value:
Returns the function that created this object's instance.
Example:
<html><head>
<title>JavaScript RegExp constructor Property</title></head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
document.write("re.constructor is:" + re.constructor);
</script></body></html>
RegExpObject.exec( string );
Here is the detail of parameters:
• string : The string to be searched
Return Value:
Returns the matched text if a match is found, and null if not.
Example:
<html><head>
<title>JavaScript RegExp exec Method</title></head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.exec(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.exec(str);
document.write("<br />Test 2 - returned value : " + result);
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
126
JavaScript
=======================================================================
RegExpObject.global
Here is the detail of parameters:
• NA
Return Value:
Returns "TRUE" if the "g" modifier is set, "FALSE" otherwise.
Example:
<html><head>
<title>JavaScript RegExp global Property</title></head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.global ){
document.write("Test1 - Global property is set");
}else{
document.write("Test1 - Global property is not set");
}
re = new RegExp( "string", "g" );
if ( re.global ){
document.write("<br />Test2 - Global property is set");
}else{
document.write("<br />Test2 - Global property is not set");
}
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
127
JavaScript
=======================================================================
ignoreCase is a read-only boolean property of RegExp objects. It
specifies whether a particular regular expression performs case-
insensitive matchingi.e., whether it was created with the "i" attribute.
Syntax:
RegExpObject.ignoreCase
Here is the detail of parameters:
• NA
Return Value:
Returns "TRUE" if the "i" modifier is set, "FALSE" otherwise.
Example:
<html><head>
<title>JavaScript RegExp ignoreCase Property</title></head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.ignoreCase ){
document.write("Test1-ignoreCase property is set");
}else{
document.write("Test1-ignoreCase property is not set");
}
re = new RegExp( "string", "i" );
if ( re.ignoreCase ){
document.write("<br/>Test2-ignoreCase property is set");
}else{
document.write("<br/>Test2-ignoreCase property is not set");
}
</script></body> </html>
==============================================
=========================
Prepared by HEERA SINGH .T
128
JavaScript
=======================================================================
test( ) automatically reset lastIndex to 0 when they fail to find a match
(or another match).
Syntax:
RegExpObject.lastIndex
Here is the detail of parameters:
• NA
Return Value:
Returns an integer that specifies the character position immediately
following the last match.
Example:
<html><head>
<title>JavaScript RegExp lastIndex Property</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
document.write("Test 1 - Current Index: " + re.lastIndex);
re.test(str);
document.write("<br />Test 2 - Current Index: " + re.lastIndex);
</script></body></html>
RegExpObject.multiline
Here is the detail of parameters:
• NA
Return Value:
Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Example:
<html><head>
==============================================
=========================
Prepared by HEERA SINGH .T
129
JavaScript
=======================================================================
<title>JavaScript RegExp multiline Property</title></head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.multiline ){
document.write("Test1-multiline property is set");
}else{
document.write("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ){
document.write("<br/>Test2-multiline property is set");
}else{
document.write("<br/>Test2-multiline property is not set");
}
</script></body></html>
RegExpObject.source
Here is the detail of parameters:
• NA
Return Value:
Returns the text used for pattern matching
Example:
<html><head>
<title>JavaScript RegExp source Property</title></head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
document.write("The regular expression is : " + re.source);
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
130
JavaScript
=======================================================================
This will produce following result:
RegExpObject.test( string );
Here is the detail of parameters:
• string : The string to be searched
Return Value:
Returns the matched text if a match is found, and null if not.
Example:
<html><head>
<title>JavaScript RegExp test Method</title></head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.test(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.test(str);
document.write("<br />Test 2 - returned value : " + result);
</script></body></html>
RegExpObject.toSource();
Here is the detail of parameters:
==============================================
=========================
Prepared by HEERA SINGH .T
131
JavaScript
=======================================================================
• NA
Return Value:
Returns the string representing the source code of the object.
Example:
<html><head>
<title>JavaScript RegExp toSource Method</title></head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.toSource(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "/", "g" );
var result = re.toSource(str);
document.write("<br />Test 2 - returned value : " + result);
</script></body></html>
RegExpObject.toString();
Here is the detail of parameters:
• NA
Return Value:
Returns the string representation of a regular expression.
Example:
<html><head>
<title>JavaScript RegExp toString Method</title></head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.toString(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "/", "g" );
var result = re.toString(str);
==============================================
=========================
Prepared by HEERA SINGH .T
132
JavaScript
=======================================================================
document.write("<br />Test 2 - returned value : " + result);
</script></body></html>
==============================================
=========================
Prepared by HEERA SINGH .T
133