You are on page 1of 200

Strictly in accordance with the latest syllabus

S araswati
MULTIMEDIA & WEB TECHNOLOGY
Supplementary Reading Material
for
UNIT 3: WEB SCRIPTING
[FOR CLASS XI]

By
Gagan Sahoo
M.C.A.

New Saraswati House (India) Pvt. Ltd.


New Delhi-110002, INDIA

Date: 27-04-2015
SYLLABUS
UNIT 3: WEB SCRIPTING

JavaScript: Introduction to client side scripting using Java Script, Using Java Script in HTML page
with <SCRIPT> tag, external Java Script;
JavaScript Variables: Declaring variable, assigning values to variables, Java Script literals; Data
types in Java Script String, Number, Boolean, Object, Function, Null; Type casting in Java Script;
JavaScript Operators:
Arithmetic Operators: +, -, *, /, % , ++, - - ;
Assignment Operators : =, +=, - =, *=, /=, %= ;
Comparison Operators: <, >, <=, >=, !=, == ;
Logical Operators: &&, ||, !;
String Operator: + (for concatenation);
Bitwise Operators : &, |, ~, ^, <<, >> ;
Unary + operator; typeof operator;
Conditional operator : (?:)
JavaScript Popup Boxes: Alert, Confirm and Prompt box
Comments in JavaScript: Single line and multiline;
Control Structures in JavaScript:
Conditional statements: If, Else, Else If.., switch case; break and default statement;
Loops: For, While, Do While loops; continue statement;
JavaScript Functions: Define a function, execute a function, return statement, function using
arguments, Scope of variables;
Objects in JavaScript: Window object, document object, location object, form object, working with
control objects(Button, reset and submit objects, checkbox objects, and radio objects, select objects,
password, text, textarea object), date object, Creating Dynamic Interface with HTML form controls
and JavaScript;
Array object in Java Script: length property, join(), sort(), for in loop;
Responding to events: onLoad, onUnload, onFocus, onBlur, onChange, onMouseOver, Timing
Events setTimeout( ) and clearTimeout();

CONTENTS
Chapter1 Introduction to JavaScript ............................................................................ 3.13.38
Chapter2 JavaScript Functions .................................................................................. 3.393.64
Chapter3 Branching in JavaScript .............................................................................. 3.653.88
Chapter4 Looping in JavaScript .............................................................................. 3.893.138
Chapter5 Objects in JavaScript .............................................................................. 3.1393.154
Chapter6 Working with Control Objects ................................................................. 3.1553.198

(2)
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.1
U N I T 3
Introduction to JavaScript
1
1.1 INTRODUCTION

The World Wide Web (WWW) began as a text-only mediumthe first browsers did not even support images
within web pages. Todays websites can include a lot of features: graphics, sounds, animation, video, and
occasionally useful content. Web scripting languages also, known as client-side scripting languages, such as
JavaScript, are one of the easiest ways to add dynamic state to a Web page and to interact with users in new
ways. Client-side scripts can control browser actions associated with a Web page. Scripts are programs written
in a simple and easy-to-use language to specify control of other programs. Client-side scripts are almost always
written in the JavaScript language to control browser actions.
Tasks performed with client-side scripts include:
x Asking the browser to display information
x Making the Web page different depending on the browser and browser features
x Monitoring user events and specifying reactions
x Generating HTML code for parts of the page
x Modifying a page in response to events
x Checking correctness of user input
x Replacing and updating parts of a page
x Changing the style and position of displayed elements dynamically
Client-side scripting can make Web pages more dynamic and more responsive.

1.2 SCRIPTING LANGUAGE

Scripting languages are becoming more popular due to the emergence of web-based applications. Specialised
scripting languages include:
Perl (Practical Extraction and Report Language). This is a popular string processing language for
writing small scripts for system administrators and website maintainers. Much web development is
now done using Perl.
Hypertalk is another example. It is the underlying scripting language of HyperCard.
Lingo is the scripting language of Macromedia Director, an authoring system for developing high-
performance multimedia content and applications for CDs, DVDs and the Internet.
AppleScript, a scripting language for the Macintosh allows the user to send commands to the
operating system, for example open applications, to carry out complex data operations.
JavaScript, perhaps the most publicised and well-known scripting language was initially developed

3.1
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.2 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

by Netscape as LiveScript to allow more functionality and enhancement to web page authoring that
raw HTML could not accommodate. A standard version of JavaScript was later developed to work in
both Netscape and Microsofts Internet Explorer, thus making the language to a large extent, universal.
This means that JavaScript code can run on any platform that has a JavaScript interpreter.
VBScript, a cut-down version of Visual Basic, used to enhance the features of web pages in Internet
Explorer.
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely used open source general-
purpose scripting language that is especially suited for web development and can be embedded into
HTML.
Major advantages of scripting languages include:
x easy to learn and use.
x minimum programming knowledge or experience required.
x allow complex tasks to be performed in relatively few steps.
x allow simple creation and editing in a variety of text editors.
x allow the addition of dynamic and interactive activities to web pages.
x editing and running code is fast.
The major disadvantage of scripting languages is that executable code can inadvertently be downloaded
from a remote server to a web browsers machine, installed and run using the local browsers interpreter. This is
easily done by visiting dubious web sites or downloading programs without valid authenticity. The user is
probably unaware of anything devious occurring.
This is a weakness and major drawback in the formal rules defining scripting languages like JavaScript and
VBScript.

1.3 JAVASCRIPT
12345678901234567890
12345678901234567890
JavaScript (originally called LiveScript) is a widely used scripting 12345678901234567890
language originally developed by Netscape Communications 12345678901234567890
What is JavaScript?
12345678901234567890
Corporation for both client-side and server-side scripting. JavaScript 12345678901234567890
JavaScript is a cross-platform,
12345678901234567890
object-oriented scripting
is a lightweight programming language that is interpreted by the browser
engine when the web page is loaded.
12345678901234567890
12345678901234567890
language developed by
JavaScript is a widely supported language and it is available in 12345678901234567890
Netscape. JavaScript was
12345678901234567890
the following browsers: 12345678901234567890
created by
12345678901234567890
Netscape
x Netscape Navigator (beginning with version 2.0) 12345678901234567890
programmer Brendan Eich.
x Microsoft Internet Explorer (beginning with version 3.0)
x Firefox
x Safari
x Opera
x Google Chrome
Thus, most Internet users today have browsers that support JavaScript. That is why JavaScript is one of
the most popular tools in the Web developer's arsenal.
Client=Side Scripting. JavaScript code is executed/interpreted when an event is triggered. When
the code is executed, it is interpreted one line at a time. There are number of events that will trigger the
execution of a JavaScript, like clicking on a form button or the completion of a web page loading.
Server-Side Scripting. When the web server loads an .html page from the disk into the memory,
it automatically knows how to interpret the code in this document. Once the code has been interpreted,
the resulting HTML page is sent to the browser (client) making the request.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.3

It was the first web scripting language to be supported by browsers, and it is still by far the most popular.
JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents. It is a less
complex, interpreted scripting language similar to AppleScript. JavaScript is similar in some ways to Java, but
it does not require the programmer to understand or implement the complicated object-oriented syntax or worry
about programming issues like variable typing and object hierarchies. Thus, JavaScript is a programming
language that allows scripting of events, objects and actions to create Internet applications.
In fact, Java and JavaScript are so different that you can think of them with different titles depending on
your ability. It is convenient to think of creating programs of Java as programming and you can call creating
scripts in JavaScript authoring.
Here are a few of the things you can do with JavaScript:
x Display messages to the user as part of a web page, in the browsers status line, or in alert boxes.
x Validate the contents of a form and make calculations (for example, an order form can automatically
display a running total as you enter item quantities).
x Animate images or create images that change when you move the mouse over them.
x Create ad banners that interact with the user, rather than simply displaying a graphic.
x Detect the browser in use or its features and perform advanced functions only on browsers that
support them.
x Detect installed plug-ins and notify the user if a plug-in is required.
x Modify all or part of a web page without requiring the user to reload it.
x Display or interact with data retrieved from a remote server.
JavaScript is an object-oriented language and many constructs are similar to those in C++ or Java. It is
an interpreted programming language that can be embedded into an HTML web page or used in server side
scripting language.
The following are the major advantages of JavaScript:
x JavaScript is no more difficult to learn than HTML. It allows people with little or no programming
experience who are daunted by Javas complexity to create interactive and Web based applications.
x JavaScript can be used to solve common problems, such as validating forms input and can also be
used to create dramatic and visually appealing content, which would be impossible with HTML.
x JavaScript is the one of the Dynamic HTML available in both Netscape Navigator and Internet
Explorer.
x As JavaScript lives inside the HTML document, it can either exist as a complete script that is embedded
in the <head> or <body> elements or it can consist of event handlers that are written directly into the
HTML code.

1.4 JAVASCRIPT SYNTAX

JavaScript is based on an action-oriented model of the World Wide Web. Elements of a Web page, such as
a button or a checkbox may trigger actions or events. When one of these events occurs, a corresponding piece
of JavaScript code, usually a JavaScript function, is executed. That function, in turn, is composed of various
statements which perform calculations, examine or modify the contents of the Web page or perform other tasks
in order to respond in some way to that event. For example, pressing the SUBMIT button on an online order
form might invoke a JavaScript function that validates the contents of that form to ensure that the user
entered all the required information.
In general, the elements of a JavaScript program can be divided into following categories:
x StatementsStatements are the lines of code from which JavaScript programs are built.
x BlocksBlocks allow you to group statements.
x CommentsComments allow you to annotate your code with remarks.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.4 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

x DataData is the actual information your programs work on.


x Variables and their valuesVariables give you a place to store your data.
x ExpressionsExpressions manipulate those values, i.e., perform operations on data.
x Control structuresControl structures, which modify how statements are performed at runtime.
x FunctionsFunctions execute a block of statements with a name.
x ObjectsObjects allow you to group your data and functions together.
x ArraysArrays allow you to hold a great deal of data and to access individual elements easily.
Before discussing the above points, let us look at the basic JavaScript syntax, which creates a simple
program in HTML code with the syntax.

1.4.1 The <SCRIPT> Tag


N ote
The <SCRIPT> tag is used to add JavaScript commands to your
HTML pages. <SCRIPT> is a container tag that can accept the attribute The beginning <Script> tag
LANGUAGE, which allows you to specify the scripting language used includes a Language argument
that indicates the scripting
(JavaScript is generally the default). The syntax is:
language. The Language
<SCTIPT LANGUAGE = "lang_name" [SRC = "URL"> argument is required because
script code there is more than one scripting
</SCRIPT> language. Without the
Language argument, a web
From the above syntax,
browser would not know if the
x The <script> tags tell the browser to expect a script in between text between the tags was
them. JavaScript, VBScript or another
x The LANGUAGE is optionalyou probably would not need scripting language.
to use it while authoring JavaScript, but it cannot hurt.
x The element lang_name gives the language that is used in the
subsequent script code; this should be JavaScript.
x If the SRC attribute is specified then it should reference a URL containing code in the script language.
For JavaScript, this should be a valid URL for a file containing the JavaScript code.
x The filename should have the suffix .js.
x If the SRC attribute is given then the <SCRIPT> can be immediately terminated by a </SCRIPT>
directive. This attribute is implemented in Netscape 3.0.
For example,
<SCRIPT LANGUAGE = "type/JavaScript" SRC = "main/hello.js"
.....
.....
</SCRIPT>

This explicitly declares to the browser that your script is a JavaScript (instead of VBscript, for example).
The "LANGUAGE" attribute while not essential to declare, is useful in certain cases. But the <script
language="JavaScript"> is incorrect. <script language = "JavaScript"> is deprecated as
"language" value is an identifier which has no standards. The correct syntax is:
<SCRIPT type = "text/JavaScript" SRC = "main/hello.js"
.....
.....
</SCRIPT>

This overrides the default scripting language. Here, the <SCRIPT> block that loads JavaScript code from
a filename hello.js in a directory main relative to the document.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.5

x If the SRC attribute is not given then it is expected that all the code between <SCRIPT> and </
SCRIPT> is the script source itself.
x It is recommended that source included between <SCRIPT> and </SCRIPT> be enclosed within the
HTML comment delimiters <!-- and ->.
For example,
<SCRIPT type = "text/JavaScript">
<!--
/* Our script only requires one quick statement! */
// prints words to Web document
document.write("Hello! I am Rahul and a Web programmer in Class-XI");
// end hiding -->
</SCRIPT>

From the above example, the entire script body is enclosed with HTML comment tags. These are optional
but recommended. They tell browsers that don't support JavaScript (or with JavaScript disabled) to ignore the
code in between. This prevents the code from being written out to your website users. At present, you should
structure your script according to the following rules:
x Place the comment start (<!--) on a line of its own.
x Follow it with your JavaScript code.
x Terminate the code with <!-- and -> on its own line.
The part that writes the actual text is only 1 line
document.write(Hello! I am Rahul and a Web programmer in Class-XI)

This is how you write text to a web page in JavaScript.

1.4.2 External JavaScript


You can place all your scripts into an external file (with a .js extension), then link to that file from within your
HTML document. This is handy if you need to use the same scripts across multiple HTML pages, or a whole
website. To link to an external JavaScript file, you add a src attribute to your HTML script tag and specify the
location of the external JavaScript file. For example,
<script src="hello.js"></script>

 &UHDWLQJ ([WHUQDO -DYD6FULSW )LOH

We can create external JavaScript file and embed it in many HTML pages. It provides code reusability because
single JavaScript file can be used in several HTML pages. As we know that an external JavaScript file must be
saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed
of the web page. Let us create an external JavaScript file called hello.js that prints "Hello JavaScript
Programmer" in a dialog box.
function printMe() {
alert("Hello JavaScript Programmer");
}

Let us include the JavaScript file ( hello.js ) into html page. It calls the JavaScript function on button click.
<html>
<head>
<script type="text/javascript" src="hello.js"></script>
</head>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.6 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<body>
<p>Welcome to JavaScript programming</p>
<form>
<input type="button" value="Click Me" onclick="printMe()"/>
</form>
</body>
</html>

x As like HTML programming, save the file with index.html.


x Open the index.html file in either Netscape or IE. If you are using IE, then the screen will look like
Figure 1.1.

Figure 1.1 Showing message using external JavaScript file.

1.4.3 HTML and JavaScript

Before you begin programming, have a look at this general information about how to incorporate JavaScript
into HTML pages. First, you should know that JavaScript is a scripting language. That is, the code is not
compiled (translated into machine language), but instead it appears as ASCII text in an HTML file. For integrating
it into the HTML code, you have three possibilities.

 ,QFRUSRUDWLRQ LQ WKH +HDGHU

The first possibility is to incorporate the source code into the header of the HTML file. Here you can write code
that youll access later using one of the two other possibilities for incorporation. The source code for this
option looks like this:
<html>
<head>
<title>Title of the Page</title>
<script type="text/javascript">
<!--
Definition of Functions and Variables
//-->
</script>
...
...
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.7

Here, the tag <script language=JavaScript> introduces the JavaScript source code, the tag
</script> ends it. The codes <!-- and //--> cause source code from older browsers, ones that do not
support JavaScript, to be hidden. Within these tags, you can define functions, variables and other JavaScript
statements.

 &DUU\LQJ RXW &RGH JLYHQ 3DUWLFXODU $FWLRQV

The second possibility is to carry out JavaScript commands given a surfers particular actions. Such actions
can include the loading or leaving of a page or the following of a link with the mouse. In the following example,
the function hello is supposed to be carried out when the page is loaded. This must be defined in advance in
the header of the HTML file:
...
<body onLoad="hello()">
...

 ,QFRUSRUDWLRQ LQ WKH %RG\

In addition, you can incorporate JavaScript commands into a particular part of the page when youre building
the page. This is useful if, for example, youd like JavaScript to incorporate supplements such as text directly
into the HTML file. For example, if you want to incorporate a function write_time in the HTML BODY, then you
must define in the header as:
<BODY>
<script>
write_time()
</script>
<H3>JavaScript example:</H3>
</BODY>

1.4.4 Writing First Script


Let us start with a simple script as given:
<HTML>
<HEAD>
<TITLE>First JavaScript Example</TITLE>
<SCRIPT type="text/javascript">
<!--
function hello(){
/* Our script only requires one quick statement! */
// prints words to Web document
alert("Hello! I am Rahul and a Web programmer in Class-XI");
}
// end hiding -->
</SCRIPT>
</HEAD>
<BODY onLoad="hello()">
<H3>JavaScript example:</H3>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.8 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

x As with HTML programming, open your windows Notepad program and type the above code.
x Save the Notepad text with First.html.
x Open the First.html file in either Netscape or IE. If you are using IE, then the screen will look like
Figure 1.2.

Figure 1.2 First JavaScript screen output.

The JavaScript defines a function called hello() and a statement with alert() for displaying something in
the form of a message. More on about function will be discussed in subsequence chapters. Instead of using
alert() command, you can display the text in the browser window using Document object. For example,

document.write("Hello! I am Rahul and a Web programmer in Class-XI");

1.4.5 The Document Object


JavaScript uses an object called document. This object manages many of the instructions that JavaScript can
handle for HTML. One of the functions of object is to display a string on the screen. A string is a piece of text
that the browser is asked to use as is. The function used is called write. The syntax of the write function
of the document object is:
document.write(String)

The String for display can be provided in double quotes or as a variable that we will learn soon. Here is an
example of displaying somebodys name using the document.write() function:
<SCRIPT type="text/javascript">
document.write("Author: Gagan Sahoo ")
</SCRIPT>

To display various lines of text, use as many document.write() lines in between <Script> and
<Script> tag as shown in Figure 1.3 on the next page.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.9

Figure 1.3 Simple JavaScript code in Notepad window.

x Save the Notepad text file as: ...\Unit 3\Chapter 1\Author.html.


x Open the Author.html in Internet Explorer. You will notice that the Internet Explorer will display the
text as shown in Figure 1.4.

Figure 1.4 JavaScript code in Internet Explorer.

JavaScript allows you to mix its own syntax with HTML tags. When you include a string in your JavaScript
and send it to Internet Explorer, everything that is part of the string is sent to the browser as is. Once the
browser receives your string from the document.write() function, it gets rid of the document.write
wordsthe parentheses and double quotes. Then it treats the rest, the part of the string, as HTML code. If the
string that was sent is just a string, the browser would display the text. If you send any special character, the
browser would analyse it to find out if the character is a special HTML symbol. If it is, it would be treated
appropriately. For this reason, a script can result in complex code or difficult-to-interpret errors.
Based on this, you can include any HTML tag as part of the string. Here is an example:
<SCRIPT type="text/javascript">
document.write("Book Title: Multimedia and Web Technology<br>")
</Script>
When Internet Explorer receives this script, it gets rid of everything that is not part of the string. After this
operation, the remaining text becomes:
Book Title: Multimedia and Web Technology
This is what the browser would try to display. There is also an HTML tag in the code, namely, the break tag
<br>; therefore, the break tag would be applied. Let us see the following code:
<SCRIPT type="text/javascript">
document.write("Author: Gagan Sahoo<br>")
document.write("Book Title: Multimedia and Web Technology<br>")
document.write("Publisher: New Saraswati House (India) Pvt. Ltd. <br>")
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.10 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

document.write("Year Published (Revised): 2015")


</SCRIPT>
Now, save the file with ...\Unit 3\Chapter 1\Author1.html and preview the page in Internet Explorer
as shown in Figure 1.5.

Figure 1.5 Using HTML tags inside JavaScript.


After previewing the page, return to Notepad and to make the page more attractive, change it as depicted
below:
<SCRIPT type="text/javascript">
<!--
document.write("<h1><font face=Verdana color=red> About My Book</font></h1>")
document.write("<hr color=#FF9933><br>")
document.write("Author: Gagan Sahoo<br>");
document.write("Book Title: Multimedia and Web Technology<br>");
document.write("Publisher: New Saraswati House (India) Pvt. Ltd.<br>");
document.write("Year Published (Revised): 2015");
document.write("<hr color=#FF9933>")
// end hiding -->
</SCRIPT>

Now, save the file with ...\Unit 3\Chapter 1\Author2.html and preview the page in Internet Explorer
as shown in Figure 1.6.

Figure 1.6 Using more HTML tags inside JavaScript.


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.11

1.4.6 Statements
JavaScript programs are made of statements. Let us take a look at our previous example, which contains a line,

document.write("Author: Gagan Sahoo<br>");

This is a JavaScript statement. This line tells the browser to write the string "Author: Gagan Sahoo" to
the browser document window. As you saw the line "Author: Gagan Sahoo<br>" shows up just as if you had
included it as part of the HTML code.

1.4.7 Semicolon (;)


In JavaScript, a semicolon (;) is a way of saying that the statement has ended and that the script can be
executed. Semicolons are normally used at the end of each line, but you can place multiple statements on a line
if each is separated by a semicolon. If you do not like the idea of putting semicolons at the end of all your
statements, you will find that you can usually leave them off without generating an error. It is best, however, to
get in the habit of using semicolons, as it can make tracking down errors easier and is generally considered to
be better form.

1.4.8 Blocks
It is quite common in programming to want to group many statements together so that they can be treated as
one entity; this is often done with functions and in conditions.
This grouping of statements together into one entity is called a block. A block is created by surrounding
all the statements that it will contain with brackets ({ and }). For example,
{
document.write("Hello! I am Rahul and a Web programmer in Class-XII");
document.write("I am in DAV School, New Delhi");
}

1.4.9 Comments
Like other languages, JavaScript supports comments in its code. Comments are completely ignored by the
JavaScript interpreter, so you can type whatever descriptive text you want. You can write single-line or
multiline comments.

 6LQJOH/LQH &RPPHQW

If you just need to add a small amount of description to the code, you are writing a single-line comment which
is probably the best option. Placing two slashes (//) before your text makes it a single-line comment.
For example,
{
// This is a single-line comment.
document.write("Hello! I am Rahul and a Web programmer in Class-XII");
document.write("I am in DAV School, New Delhi");
}

You can also write a single-line comment as one line as:


document.write("I am in DAV School, New Delhi"); // Write to browser
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.12 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

 0XOWLOLQH &RPPHQW

Sometimes one line of comments is not enough for the description you want to provide. In this case, you can
use a multiline comment. Multiline comments are specified by surrounding the commented text with /* at the
beginning and */ at the end. For example,
{
/* This is the simple programming for Web to display texts
in a browser */
document.write("Hello! I am Rahul and a Web programmer in Class-XII");
document.write("I am in DAV School, New Delhi");
}

1.5 JAVASCRIPT VARIABLES

Variables enable you to define places to store this data. A variable may be initialized, meaning that it is given a
value when it is declared or it may be uninitialized. In addition, multiple variables can be declared on the same
line by separating their names with commas. JavaScript variables are untyped . They can contain values of any
data type.

 'HFODULQJ YDULDEOHV

All JavaScript variables are declared using the keyword var or let. The following rules are used to declare
variables in JavaScript:
x The variable names start contains letters, digits, underscores, and dollar signs.
x The first character in the name must be an alphabetic letter.
x The names can also begin with $ and _ (underscore).
x Characters subsequent to the first character in the variable name can be alphabetic letters, numbers or
underscores.
x Variable names are case sensitive (num and Num are different variables).
x Reserved words (like JavaScript keywords) cannot be used as names.
For example,
<SCRIPT type="text/javascript">
var MyName;
var MySchool = "DAV Public School";
var Age = 15;
document.write("My school: " + MySchool);
</SCRIPT>

 $VVLJQLQJ 9DOXHV WR 9DULDEOHV

After you create a variable, you must assign (give) or initialize a value to it. The ( = ) equal sign is called
assignment operator: you assign the value of what is on the right side of the = sign to whatever is on the left
side of the = sign. Its syntax is:

VariableName = Value

Here, the VariableName must be a valid variable name. It cannot be a value such as a numeric value or
a (double-quoted) string. Here is an example that assigns a numeric value to a variable:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.13

<SCRIPT type="text/javascript">
Salary = 1255;
</Script>

Once a variable has been declared and assigned a value, you can call the document.write() function to
display its value. For example:
<SCRIPT type="text/javascript">
Salary = 22550;
document.write(Salary);
</Script>

To improve, safeguard and make your code more efficient, you should declare a variable before using it.
This is done using the var keyword. The above script could be written as follows:
<SCRIPT type="text/javascript">
var Salary;
Salary = 22550;
document.write(Salary);
</Script>
Let us start an example for assigning values into variables with the following code in a Notepad window:
<SCRIPT type="text/javascript">
var Job1Wage, Job2Wage
Job1Wage = 2500.38
Job2Wage = 2300
document.write("<p>Salaries :</p>")
document.write("Wage 1: Rs. ")
document.write(Job1Wage)
document.write("<br>")
document.write("Wage 2: Rs. ")
document.write(Job2Wage)
</Script>
Save the file as: ...\Unit 3\Chapter 1\Assign.html. When you open the file in IE, the following
screen will appear as shown in Figure 1.7.

Figure 1.7 Using assignment operator for assigning values.


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.14 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

1.6 JAVASCRIPT DATA TYPES


One of the basic tenets of programs is that they have to work on data. Data is any type of information with
which you are working. Data can be words, such as "Hi Friends" or numbers, such as 100 or 250.60. In any case,
different programming languages enable you to work on different kinds of data. JavaScript provides different
data types to hold different types of values. There are two types of data types in JavaScript.
x Primitive data type
x Non-primitive (reference) data type
JavaScript is a dynamic type language, which means you don't need to specify type of the variable because
it is dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any
type of values such as numbers, strings, etc. For example,
var num = 40; // holding number
var MyName="Amitl"; // holding string

The Table 1.1 shows five types of primitive data types in JavaScript:

123456789012345678901234567890121234567890123456789012345
Table 1.1 JavaScript primitive data types.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Data Type Description Example
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
String Represents sequence of characters "Hello", "We are selected in IIT"
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Number Represents numeric values 100, 250.60
123456789012345678901234567890121234567890123456789012345
Boolean Represents boolean value either false or true true, false
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Undefined Represents undefined value
123456789012345678901234567890121234567890123456789012345
Null Represents null No value at all
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Object document, window
123456789012345678901234567890121234567890123456789012345
Array a[0] = 1

Table 1.2 shows the non-primitive data types in JavaScript:

123456789012345678901234567890121234567890123456789012345
Table 1.2 JavaScript primitive data types.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Data Type Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Object Represents instance through which we can access members.
123456789012345678901234567890121234567890123456789012345
Array Represents group of similar values.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
RegExp Represents regular expression.

 6WULQJV

A string is any grouping of characters that is surrounded by either double quotation marks (") or single
quotation marks ('). Strings are used anytime you want to use text in a program. For example,
"Hello"
"We are selected in IIT"

Usually, double quotation marks are used to denote strings. If you want to include double quotes in the
string itself, use string quotation marks instead. For example,
'Hello friends! The CBSE introduced a special course for "Web Developers" in 2004'

JavaScript strings are immutable, which means that there is no way to change the contents of a string.
Methods that operate on strings typically return a modified copy of the string.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.15

 1XPEHUV

There are two numeric types in JavaScript : integers and floating-point numbers. The rules for specifying both
types are almost identical. Integers may be specified in base 10 (decimal), base 8 (octal) or base 16 (hexadecimal)
formats. Any of the three forms can also start with a + or sign. The three forms are:
x 1-9 followed by any set of digits is a decimal integer. For example, 45 is a decimal integer.
x 0 followed by any set of the digits 0-7 is an octal integer. For example, 017 is an octal integer.
x 0x or 0X followed by any of 0-9, a-f or A-F is a hexadecimal integer. For example, 0x12EF5 is a hexadecimal
integer.
The minimum and maximum integers that can be used are implementation dependent, but at least 32 bits
should be expected.
Floating-point numbers can be specified in either the standard decimal point (.) format or the engineering
E-notation. Typically floating-point numbers should contain a decimal point or an exponent, which may begin
with either e or E. A floating-point number may also have a + or sign. 0.0, -1.4212 and 3.1424 are all valid
floating-point numbers.

 %RROHDQ

A Boolean is a simplest data type available. A Boolean value has only two possible valuestrue and false.
They are often used to represent whether something has been done or not. It is possible to think of true as 1 and
false as 0. JavaScript converts these logical values into 1 and 0, respectively. JavaScript also accepts any non-
zero integer in place of true, for example, so that 5 and 3 can both be used as stand-ins for true.

 2EMHFW

An object is a compound data type that contains any number of properties. Each property has a name and a
value. The . operator is used to access a named property of an object. For example, you can read and write
property values of an object o as follows:
Obj1.x = 1;
Obj1.y = 2;
Obj1.total = Obj1.x + Obj1.y;

Objects are created with the new operator. You can create a new object with no properties as follows:
var Obj1 = new Object( );

Similarly, to create a Data class object that represents the current time with its method,
var Now = new Date();

 )XQFWLRQV DQG 0HWKRGV

A function is a piece of JavaScript code that is defined once and can be executed multiple times by a program.
A function definition looks like this:
function sum(x, y) {
return x + y;
}
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.16 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Functions are invoked using the () operator and passing a list of argument values:
var total = sum(1,2); // Total is now 3

In JavaScript 1.1, you can create functions using the Function( ) constructor:
var sum = new Function (x, y, return x+y;);

1XOO

The value null has a very special role in the JavaScript language. The null data type only has one possible
value, i.e., null. When a variable is set to null, it means that it has no value. Variables are often set to null when
a value was to be returned to a function but instead none was generated.

1.7 JAVASCRIPT CONSTANTS

In JavaScript, constants are declared with const keyword and assigned at the time of the declaration. A
constant can be global or local to a function where it is declared. Constants are read-only, therefore you cannot
modify them later on.
Naming a constant in JavaScript follows the same rule of naming a variable except that the const keyword
is always required, even for global constants. If the keyword is omitted, the identifier is assumed to represent
a variable. For example,
const Country = India;
const Num = 20;

1.8 KEYWORDS

In Table 1.3, keywords are part of the JavaScript language, and have special meaning to the JavaScript interpreter.
These reserved words are called keywords. Therefore, they may not be used as identifiers.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Table 1.3 Useful keywords.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
abstract boolean break byte case catch char
123456789012345678901234567890121234567890123456789012345
class const continue default delete
123456789012345678901234567890121234567890123456789012345
do double
else extend false final finally float for
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
function goto if implements import in instanceof
123456789012345678901234567890121234567890123456789012345
int interface long native new null package
123456789012345678901234567890121234567890123456789012345
private protected public return short
123456789012345678901234567890121234567890123456789012345 static super
123456789012345678901234567890121234567890123456789012345
switch synchronized this throw throws transient
123456789012345678901234567890121234567890123456789012345
true try typeof var void while with

1.9 JAVASCRIPT LITERALS

Literals are the way you represent values in JavaScript. These are fixed values that you literally provide in your
application source, and are not variables.

 ,QWHJHU /LWHUDOV

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).
x Decimal integer literal can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading
zeros. For example, 123, -20, 12345.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.17

x Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number is octal.
For example, 173, -24, 30071.
x Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F or
a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal. For example, 7b, -14, 3039.

 )ORDWLQJ 1XPEHU /LWHUDOV

A floating-point literal can have the following parts:


x A decimal integer which can be signed (preceded by "+" or "-"),
x A decimal point ("."),
x A fraction (another decimal number),
x An exponent.
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-").
A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").
Some examples of floating-point literals are 3.1415, -3.1E12, .1e12 and 2E-12.

 %RROHDQ /LWHUDOV

The Boolean type has two literal values: true and false. You can use conditional statement to combine with a
Boolean. For example,
var Flag = true;
if(Flag == true) {
// If the condition evaluates to true
}
else {
// If the condition evaluates to false
}
It goes without saying that the Boolean object is an extremely important part of JavaScript. Without a
Boolean object, there wouldn't be anything to evaluate within conditional statements.

 6WULQJ /LWHUDOV

A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be delimited
by quotes of the same type; that is, either both single quotes or double quotes. For example,

var Str1 = "Multimedia & Web Technology"


var Str2 = 'Class - XI'
var Str3 = "JavaScript"
You can also use + operator to join strings. For example,
var NStr1 = "Multimedia & Web Technology" + 'Class - XI'
var NStr2 = Str2 + Str3
In addition to ordinary characters, you can include special characters in strings, as shown in Table 1.4.
var StrA = "Multimedia & Web Technology \n Class - XI"

Table 1.4 lists the special characters or escape characters that you can use in JavaScript strings.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.18 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

123456789012345678901234567890121234567890123456789012345
Table 1.4 JavaScript special characters.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Characters Meaning
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\b Backspace
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\f Form feed
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\n New line
123456789012345678901234567890121234567890123456789012345
\r Carriage return
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\t Tab
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\v Vertical tab
123456789012345678901234567890121234567890123456789012345
\' Apostrophe or single quote
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\" Double quote
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\\ Backslash character
123456789012345678901234567890121234567890123456789012345
\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\xXX The character with the Latin-1 encoding specified by the two hexadecimal digits XX
123456789012345678901234567890121234567890123456789012345
between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
symbol.
123456789012345678901234567890121234567890123456789012345
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX. For example,
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape
123456789012345678901234567890121234567890123456789012345
sequences.
123456789012345678901234567890121234567890123456789012345
You can insert quotes inside of strings by preceding them by a backslash. This is known as escaping the
quotes. For example,
var EQuote = "Hi friends! \"The CBSE multimedia course updated\" by Author: Gagan Sahoo."
document.write(EQuote)

The result of this would be


Hi friends! The CBSE multimedia course updated by Author: Gagan Sahoo.

 $UUD\ /LWHUDOV

In JavaScript an array literal is a list of expressions, each of which represents an array element, enclosed in a pair
of square brackets ' [ ] ' . When an array is created using an array literal, it is initialized with the specified values
as its elements, and its length is set to the number of arguments specified. If no value is supplied ,it creates an
empty array with zero length. For example, to create an empty array Num,
var Num = [ ];
To create an array with week names,
var WNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

 2EMHFW /LWHUDOV

An object literal is zero or more pairs of comma-separated list of property names and associated values,
enclosed by a pair of curly braces ({ }). To declare an object literal, we must maintain the following syntax rules:
x There is a colon (:) between property name and value.
x A comma separates each property name/value from the next.
x There will be no comma after the last property name/value pair.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.19

For example, to declare a Student object with its few properties,


var Student = {
First-name : "Amit",
Last-name : "Gulati",
Roll-No : 119
};

1.10 EXPRESSIONS
An operand or a combination of operands and operators that, when evaluated, yields a single value. Expressions
are constructs denoting rules of computation of obtaining values of variables and generating new values by
the application of operators. Expressions consist of operators and operands, i.e., variables, constants and
functions. For example,
(f 32) * 5 / 9

is an expression.

 1XPHULF ([SUHVVLRQV

A numeric expression is simply the rudimentary sort of mathematically operation.

For example,
10 + 5

is a numeric expression. Table 1.5 depicted some numeracal expression uisng numerical operators.

123456789012345678901234567890121234567890123456789012345
Table 1.5 Common numerical operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Example Definition
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
+ 10 + 5 Addition
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
10 5 Subtraction
123456789012345678901234567890121234567890123456789012345
* 10 * 5 Multiplication
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
/ 10 / 5 Division
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
% 10 % 5 Modulo: The remainder after division
123456789012345678901234567890121234567890123456789012345
(15 * 5) Unary negation

 /RJLFDO ([SUHVVLRQV

A logical (or Boolean) expression is an expression that when evaluated returns a result of either true or false.
Table 1.6 shows logical operators. For example,
true && false

which evaluates false because one of the sides is not true.

123456789012345678901234567890121234567890123456789012345
Table 1.6 Logical operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Example Definition
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
&& And (exp1 && exp2) returns true if both exp1 and exp2 are true, otherwise
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
returns false.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.20 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
| Or (exp1 || exp2) returns true if either exp1 or exp2 is true, otherwise returns
123456789012345678901234567890121234567890123456789012345
false.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
! Not (!exp) returns false only if exp1 is true or true if exp is false.

1.11 TYPECASTING

JavaScript is a loosely typed language. That means that you do not have to specify the datatype of a variable
when you declare it, and datatypes are converted automatically as needed during the course of script execution.
In JavaScript, when we add two strings, we use the + (concatenation) operator. But when we combine a
string with a number in the form:
stringthing + numberthing

the number is converted to a string and the + operator then glues the two things together (concatenation).

However, if they are combined in the opposite order:


numberthing + stringthing

then JavaScript attempts to convert the stringthing to a number and add it, numerically, to numberthing. If the
stringthing can be converted to a string, such as -10, then all goes well; if it cannot then an error result. This
illustrates the concept of implicit conversion in JavaScript. In JavaScript, we can say,
"This page has been accesses" + ctr + " times today"

without having to worry about the data type of the variable ctr. This construction will always give a valid string
and never an error.
JavaScript variables have to be declared in a var statement and each variable holds information of a
specific type. Internally, 3 and 3.00 and "3.00" are represented differently. JavaScript usually infers types from
context, does conversions automatically. For example,
"Sum = " + sum

and sometimes we have to be explicit:


x parseInt(...) which converts a sequence of characters into its integer value. For example,
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2) // "+" means "add"

x parseFloat() which converts a sequence of characters into its floating-point numbers.

1.12 OPERATORS

An operator is one that works on data items and performs some mathematical calculations or changes the data.
JavaScript operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,
compound assignment, conditional and type.
x Assignment Operators. For example, =
x Compound Assignment Operators. For example, +=, =, *=, /=, %=
x Arithmetical Operators. For example, , +, *, /, %, ++,
x Relational Operators. For example, >, <, >=, <=, ==, !=
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.21

x Logical Operators. For example, &&, ||, &, |, !, ^


x Unary Operators. For example, +, , ++, , !
x Conditional Operator. For example, ?.

We shall discuss some of these operators one by one in the following section.

 $VVLJQPHQW 2SHUDWRUV

The equal (=) sign is used for assigning a value to a variable. JavaScript, like all scripting languages, allows you
to assign values to variables. The syntax is:
variable = value;

Here, a value can be a constant, an expression or a variable.

We can assign a primitive variable using a literal or the result of an expression.


var x = 7; // Literal assignment
var y = x + 2; // Assignment with an expression
var z = x * y; // Assignment with an expression with literal

 &RPSRXQG $VVLJQPHQW 2SHUDWRUV

In addition, JavaScript has a set of compound assignment operators of the forms. The compound assignment
operators combine the simple assignment operator with another binary operator. The compound assignment
operators are also called shorthand operators. The syntax is:
argument1 operator=argument2;
Or
expression1 operator=expression2;
can be understood as:
argument1 = argument1 operator argument2;
Or
expression1 = expression1 operator expression2;

An example program is shown below that demonstrates the different compound operators in JavaScript.
var prod_amt = 10
prod_amt = prod_amt + 2.5; // Add 2.5 to current production

Instead of the above expression, you should use JavaScripts compound addition operator by coding the
update in this way:
prod_amt += 2.5; // Add 2.5 to the current production
The += is called the addition assignment operator. Let us see other examples:
var y;
y *= 2; //same as (y = y * 2) // Compound multiplication
var b1 = true, b2 = false;
b1 &= b2; //same as (b1 = b1 & b2)

Table 1.7 provides the shorthand operators.


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.22 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

123456789012345678901234567890121234567890123456789012345
Table 1.7 Compound assignment operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Name Example Equivalent
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
+= Addition assignment i+=5; i=i+5
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
-= Subtraction assignment j-=10; j=j-10;
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
*= Multiplication assignment k*=2; k=k*2;
123456789012345678901234567890121234567890123456789012345
/= Division assignment x/=10;
123456789012345678901234567890121234567890123456789012345
x=x/10;
123456789012345678901234567890121234567890123456789012345
%= Remainder assignment a%=4; a=a%4;

 0DWKHPDWLFDO RU $ULWKPHWLF 2SHUDWRUV

The computational operators are used in performing arithmetic computations. JavaScript supports the common
mathematical operations for both integers and reals. Table 1.8 shows all the usable arithmetic operators.

123456789012345678901234567890121234567890123456789012345
Table 1.8 Computational or arithmetic operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Name Example Result (When x = 20, y = 10 s = 0)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
+ Addition x+y Sum of x and y.
123456789012345678901234567890121234567890123456789012345
For example, s = x + y is equivalent to 30
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Subtraction x y Difference of x and y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
For example, s = x y is equivalent to 10
123456789012345678901234567890121234567890123456789012345
* Multiplication x*y Product of x and y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
For example, s = x * y is equivalent to 200
123456789012345678901234567890121234567890123456789012345
/ Division x/y Quotient of x and y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
% Modulus x%y
For example, s = x / y is equivalent to 2
123456789012345678901234567890121234567890123456789012345
Remainder of x divided by y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
For example, s = x % y is equivalent to 0

Other than this, the ++ (Preincrement, postincrement) and (predecrement, postdecrement) operators
are used with the variables as compound expression. The + operator is overload; it also has the extremely
important role of string concatenation.

 5HODWLRQDO&RPSDULVRQ 2SHUDWRUV

The relational operators are used to determine if a given relationship exists between the pairs of values. These
operators are always used for comparing strings, numbers and objects, returning a true or a false Boolean
value. Each relational operator always appears with two constants, variables, expressions, or a mix of these
one on each side of the operator. Table 1.9 shows the relational operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Table 1.9 Relational operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operators Description Example (Assume that x = 10 and y = 20)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
== equal to x == y is not True.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
> greater than x > y is not True.
123456789012345678901234567890121234567890123456789012345
< less than x < y is True.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
>= greater than or equal to x >= y is not True.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
<= less than or equal to x <= y is not True.
123456789012345678901234567890121234567890123456789012345
!= not equal to x != y is True.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.23

The six operators in the above listing provide the foundation for comparing data in JavaScript. Each
operator always appears with two constants, variables, expressions, or a mix of theseone on each side of the
operators.
The comparison is straight forward if the two operands being compared are of the same type. When they
are not, the following rules apply:
x When comparing a number to a string, the string is automatically converted to a number.
x When only one of the operands is a Boolean, it is converted to 1 for true and 0 for false.
x When comparing an object to a string or a number, the object is converted to a string (via its toString
method) or a number (via its valueOf method). Failure to convert generates a run-time error.
The strict equality operators === and !== can be used if the operands must be of the same type. Let us see
the difference between == and === operators.
x == is an equal to operator. That is, when we compare two variables of different type, e.g., a boolean
with a string or a number with String using == operator, it automatically converts one type into another
and returns value based upon content equality. For example,
0 == false // true, because false is equivalent of 0
2=="2" // true, 2 string automatically converted into number

x === is an equal value and equal type operator. It only return true if both variable of same type and also
contains same value. For example,
0 === false // false, because both operands are of different type
2 === "2" // false, since both operands are not of same type

 /RJLFDO 2SHUDWRUV

The logical operators are also called Boolean operators. With Boolean operators we perform logical operations.
These are most often used with if and while keywords. By combining logical operators with relational operators,
you can create more powerful data-testing statements ( for logical operators, see Table 1.6).
The following example tests the variables using if statement (which shall be discussed in succeeding
chapters).
If ((the variable a is less than the variable b) AND (the variable c is greater than the variable d)).
print results are invalid to the screen.
if ((a < b) && (c > d))
document.write("Result is invalid.");

 %LWZLVH 2SHUDWRUV

Bitwise operators work with bits of a binary number. Table 1.10 shows the bitwise operators.

123456789012345678901234567890121234567890123456789012345
Table 1.10 Bitwise operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Shorthand Expression Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
& And x&y Bits that are set in both x and y are set.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
| Or x|y Bits that are set in either x or y are set.
123456789012345678901234567890121234567890123456789012345
^ Xor x^y Bits that are set in x or y but not both are set.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
~ Not ~x Bits that are set in x are not set, and vice versa.
123456789012345678901234567890121234567890123456789012345
<< Shift left x <<y Shift the bits of x, y steps to the left.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
>> Shift right x >>y Shift the bits of x, y steps to the right.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.24 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Bitwise & (And) examines bit position in each of its operands. If both operators have a 1 bit in a given
position, then that bit will also be set to 1 in the result. In all other cases, the output bit position is zero.

 8QDU\ 2SHUDWRUV

The operators we have discussed so far are all binary operators. JavaScript provides two unary operators for
which only one variable is required. You can use the addition (+) and subtraction () operators by themselves.
When you do, they are called unary operators. For example, to assign four variables with different values
containing positive or negative numbers, the statements are:
var a = -40; // Assign 'a' a negative 40
var b = +40; // Assign 'b' a positive 40 (The plus sign is not needed)
var c = -a; // Assign 'c' the negative of 'a' (40)
var d = +b; // Assign 'd' the positive of 'b' (the plus sign is not needed)

 ,QFUHPHQW   DQG 'HFUHPHQW   2SHUDWRUV

The unary operators (++ and ) are called prefix increment or decrement operators when the increment or
decrement operators appear before the operand. Let us illustrate it by using an example:
a = 10;
d = 12;
b = a++; // Statement (1)
c = ++d; // Statement (2)

After the execution of aforementioned statements, the value of b becomes 10 and the value of c becomes
13 because the precedence of = is greater than the unary operator. So, in Statement (1), a is assigned a value
and then, it is incremented. In Statement (2), d is incremented first and then it is assigned to c.

After the execution of Statement (1) and Statement (2), the values of a and d are also incremented by 1.
So, the value of a becomes 11 and the value of d becomes 13. Here, Statement (1) is equivalent to the
following statements:
b = a;
a = a + 1;

Statement (2) is equivalent to the following statements:


d = d + 1;
c = d;
Also, from the previous two statements:
a++ means a = a + 1 and
++d means d = d + 1
Similarly, if we consider the pre-decrement operator ( ), then the above statements can be rewritten as:
a = 10;
d = 12;
b = a; // Statement (3)
c = d; // Statement (4)

From the Statement (3) and Statement (4),


a means a = a 1 and
d means d = d 1
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.25

Let us consider the following cases:


x If we use the increment operator before the operand in an expression as:
var sum = 0;
var a = 10;
sum = sum + ++a; // Or sum = sum + (++a) is a pre-increment;
then the values of a and sum are changed in the following manner:

sum a sum

0 10 0
0 11 (after ++a) 11 [after sum + (++a) is a pre-increment]

Here, the line:


sum = sum + ++a;
first increase the value of a as a = a + 1 and then the new value of a (11) is added to the old value
of sum. So, the execution of the equation becomes,
sum = 0 + 11;
i.e. the new sums value becomes 11.
x If we use the increment operator after the operand in an expression as:
var sum = 0;
var a = 10;
sum = sum + a++; // Or sum = sum + (a++) is a post-increment;
then the value of a and sum are changed in the following manner:
sum a sum

0 10 0

0 11 (after a++) 10 [after sum + (a++)]

Here, the line:


sum = sum + a++; // post-increment
first add the value a (10) with the old value of sum and then increase the value of a as 11. That is, for
the above line the increment value of a (11) does not affect the sum value. So, the execution of the
equation becomes,
sum = 0 + 10;

i.e. the new sums value becomes 10.


x If we use the decrement operator before the operand in an expression as:
var sum = 0;
var a = 10;
sum = sum + a; // Or sum = sum + (a) is a pre-decrement;
then the values of a and sum are changed in the following manner:

sum a sum
0 10 0

0 9 (after a) 9 [after sum + (a) is a pre-decrement]


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.26 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Here, the line:


sum = sum + a; //Pre-decrement

first decrease the value of a as a = a 1 and then the new value of a (9) is added to the old value of
sum. So, the execution of the equation becomes,

sum = 0 + 9;

i.e. the new sums value becomes 9.


x If we use the decrement operator after the operand in an expression as:
var sum = 0;
var a = 10;
sum = sum + a; // Or sum = sum + (a) is a post-decrement;
then the value of a and sum are changed in the following manner:

sum a sum

0 10 0
0 9 (after a) 10 [after sum + (a) is a post-decrement]

Here, the line:


sum = sum + a; //Post-decrement

first add the value a (10) with the old value of sum and then decrease the value of a as 9. That is, for
the above line, the decrement value of a (9) does not affect the sum value. So, the execution of the
equation becomes,
sum = 0 + 10;

i.e. the new sums value becomes 10.


It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to
declare another variable that would hold the new value.

 W\SHGHI 2SHUDWRU

The "typeof" operator in JavaScript allows you to probe the data type of its operand, such as whether a
variable is string, numeric, or even undefined. There are six possible values that typeof returns: "number,"
"string," "boolean," "object," "function" and "undefined." The parentheses are optional in the typeof syntax.
Table 1.11 lists the possible return values of typeof.
1234567890123456789012345678901
Table 1.11 typedef return values.
1234567890123456789012345678901
1234567890123456789012345678901
1234567890123456789012345678901
Evaluate to Indicates
1234567890123456789012345678901
1234567890123456789012345678901
"number" Operand is a number
1234567890123456789012345678901
1234567890123456789012345678901
"string" Operand is a string
1234567890123456789012345678901
"boolean" Operand is a Boolean
1234567890123456789012345678901
1234567890123456789012345678901
"object" Operand is an object
1234567890123456789012345678901
null Operand is null
1234567890123456789012345678901
1234567890123456789012345678901
"undefined" Operand is not defined
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.27

For example,
var Num = 5;
var result = (typeof Num === 'number'); // Returns true
var eBook = "Multimedia For Class-XI";
var result = (typeof eBook === 'string'); // Returns true
var Num;
var result = (Num === undefined); // Returns true
var result = (typedef Num === 'undefined'); // Returns true

 &RQGLWLRQDO 2SHUDWRU

The conditional operator, ? is JavaScripts only ternary operator. A ternary operator requires three operands
instead of the single and double operands of unary and binary operators. The conditional operator is used to
replace if-else logic situations. The format of the conditional operator is:
conditional_expression ? expression1 : expression2;

Here:
x conditional_expression, expression1 and expression2 are expressions.
x If the value of conditional_expression is true, then the expression1 is evaluated and becomes the value
of the conditional_expression, otherwise expression2 is evaluated and becomes the value of
conditional_expression.
Example Consider the following three statements and write if-else statement for this:
x = 10; // ....1
y = 15; // ....2
z = (x>y ? x : y); // ....3

Solution The statement 3 is equivalent to the following if-else:


if (x>y)
z = x;
else
z = y;

So the value of z = 15 because x is not greater than y.


Here is another example of the way the ? is employed:
flag = (age > 18 ? true : false);

When JavaScript evaluates this assignment expression, it first looks at the expression to the left of the
question mark. If age is greater than 18, then expression between the question mark (?) and the colon (:) is
evaluated and used as the value of the entire ? expression. If age is not greater than 18, then the expression
after the colon (:) is evaluated and used for the value of the entire ? expression. The result produced by the ?
operator is then assigned to flag.

 1XOO 9DOXH

The value of null has a very special role in the JavaScript language. It is the value of last resort, so to speak, for
every variable. For the beginning JavaScript programmer, its primary role will be initializing variables that do
not have any more meaningful initial value, e.g., to initialize y to some value, we should have actually written,
var y = null;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.28 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

This prevents JavaScript errors that arise when an uninitialized variable is accidentally used in an expression
that requires a value. It is important to realize that the value of null (not NULL) does not give the variable y and
implicit data type. Null also has the property that it may be converted to a form of all the other types. When it
is converted to a number it becomes 0, when it is converted to a string it becomes the empty thing " " and when
it is converted to a Boolean value it becomes false. This is the only case where it is permissible to change the
implicit data type of a variable after it is declared. Therefore, statements such as:
var ok = "Hello" + y;
var w = x + y;
result in ok having the value "Hello" (the same as ok) and w having the value to (the same as x). This is why the
value of null is an excellent way of initializing variablesit is guaranteed to be harmless.

1.13 JAVASCRIPT POPUP BOXES


JavaScript has three built-in windows methods which are used to create popup boxes. These are:
confirm(message). We can display a confirm box to the visitor and ask their opinion. This
confirm window will have two buttons, one for OK and other for CANCEL. Visitor can click one of the
two buttons and the user action can be captured by assigning this to a variable. The confirm box will
return TRUE if the OK button is clicked and it will return FALSE if Cancel button is clicked. For example,
var Choice = confirm("Do you want to continue ?");
if (Choice == true) {
alert("User wants to continue!");
}else{
alert("User does not want to continue!");
}
alert(message). An alert dialog box is mostly used to warn the user or alert him or her to
something. In the following cases, one can use the alert() function:
x Incorrect information in a form
x An invalid result from a calculation
x A warning that a service is not available on a given date
For example, the simplest way to direct output to a dialog box is to use the alert() method.
alert("Click Ok to continue.");
Example Sagarika works in a company where she was instructed to develop a web application to
show an alert window displaying a message called "Welcome to multimedia course" as
shown in given figure:

Write the complete code to satisfy the previous window.


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.29

Solution The code is: (alert.html)


<html>
<head>
<title>My page</title>
<SCRIPT type="text/javascript">
function show_alert() {
var msg = "Welcome to multimedia course";
alert(msg);
}
</SCRIPT>
</head>
<body>
<input type=button value='Click here to display alert message' OnClick="show_alert()">
</body>
</html>

prompt(message). The prompt command will display a window and ask visitor to enter some
data. We can collect the data entered by the user and store them in a variable. Thus, it enables you to
interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed
using a method called prompt() which takes two parameters:
(i) A label which you want to display in the text box.
(ii) A default string to display in the text box.
This dialog box is with two buttons: OK and Cancel. If the user clicks on the OK button, the window
method prompt() will return entered value from the text box. If the user clicks on the Cancel button, the
window method prompt() returns null.
For example,
var myName = prompt("Enter your name : ");
alert("You have entered : " + myName);
When the above code is executed, we can show some default text while displaying the prompt. Here is
an example where a default message is displayed for the visitor to enter first name.
var myName = prompt("Enter your name : ", "your first name");
alert("You have entered : " + myName);

Example Write a program in JavaScript to enter your name as FirstName and SecondName and
display the name in an alert window. For example,
if you enter the FirstName as Harapriya and the SecondName as Parikar, then the alert
window will display: Hello Harapriya Parikar.
Solution The code is:
<html>
<title>Use of concatenation operator</title>
<body>
<P> Concatenation
<SCRIPT type="text/javascript">
var FirstName, SecondName, Result
FirstName = prompt("Enter first name")
SecondName = prompt("Enter last name")
Result = FirstName + " " + SecondName // + means "join" here
alert("Hello, " + Result) // and here
</script>
</body>
</html>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.30 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

3RLQWVWR5HPHPEHU

1. A variable is a name for a memory location that is used to hold a value of a particular data type.
2. A variable can store only one value of its declared type.
3. Constants are similar to variables but they hold a particular value for the duration of their
existence.
4. The empty string is a string containing no characters.
5. Keywords (or reserved words) are reserved for use by JavaScript.
6. JavaScript is case-sensitiveuppercase and lowercase letters are different.
7. A constant is a meaningful name that takes the place of a number or string and never changes.
8. The prefix and postfix increment and decrement operators have subtle effects of programs,
because of differences, when they are evaluated.
9. Logical operators are a natural choice to implement a condition for a selection or repetition
statement because they return a Boolean value.
10. Logical operators are used to combine one or more than one relational expressions.
11. The comma enables us to put more than one expressions, separated by comma, on a single line.
12. Expressions are combinations of operators and operands used to perform a calculation.
13. JavaScript always performs multiplication, division and modulus first, then computes addition
and subtraction.
14. The arithmetic operators are binary operators because each operates on two operands.
15. The increment operator, ++ and the decrement operator , increase or decrease a variable by
1.
16. If the increment or decrement operator is prefixed to the variable, the variable is increased or
decreased by 1 first and then used in its expression.
17. If the increment or decrement operator is postfixed to the variable, the variable is used in its
expression, then increased or decreased by 1.
18. alert() function is used to display a message to a dialog box (also called alert box).
19. prompt() function asks the user to input some information and stores the information in a
variable.
20. confirm() function displays a confirm box to the visitor and asks their opinion. This confirm
window will have two buttons, one for OK and other for CANCEL.

SOLVED EXERCISES
1. What is JavaScript?
Ans. JavaScript is a scripting language designed primarily for adding interactivity to web pages and creating
web applications.
2. What are the advantages of the JavaScript ?
Ans. Following are the advantages of JavaScript:
x JavaScript is no more difficult to learn than HTML. It allows people with little or no programming
experience who are daunted by Javas complexity to create interactive and Web-based applications.
x JavaScript can be used to solve common problems, such as validating forms input and can also be
used to create dramatic and visually appealing content, which would be impossible with HTML.
x JavaScript is one of the Dynamic HTMLs available in both Netscape Navigator and Internet Explorer.
x As JavaScript lives inside the HTML document, it can either exist as a complete script that is
embedded in the <head> or <body> elements or it can consist of event handlers that are written
directly into the HTML code.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.31

3. Justify, JavaScript is an interpreted language.


Ans. JavaScript was a purely interpreted language. This means that scripts execute without preliminary
compilation, i.e., without conversion of the script text into system-dependent machine code. The user's
browser interprets the script, that is, analyses and immediately executes it.
4. What is the use of <SCRIPT> tag ? Explain with syntax.
Ans. The <SCRIPT> tag is used to add JavaScript commands to your HTML pages. <SCRIPT> is a container
tag that can accept the attribute LANGUAGE, which allows you to specify the scripting language used
(JavaScript is generally the default). The syntax is:
<SCRIPT LANGUAGE = "lang_name" [SRC = "URL">
script code
</SCRIPT>
5. What is the use of SRC in JavaScript syntax ?
Ans. If the SRC attribute is specified then it should reference a URL containing code in the script language.
For JavaScript, this should be a valid URL for a file containing the JavaScript code.
6. Is there any difference between <script language="JavaScript"> and type="text/javascript".
Ans. Yes. <script language="JavaScript"> is deprecated as "language" value is an identifier which has no
standards.
type="text/javascript" is the correct syntax. This overrides the default scripting language.
7. What is variable?
Ans. A variable is an identifier, which holds a value. In programming, we say that we assign a value to a
variable. Technically speaking, a variable is a reference to the computer memory, where the value is
stored.
8. What is reserve word?
Ans. Some words cannot be used as variable names in JavaScript. These words are called keywords or
reserved words.
9. How will you include comments in the JavaScript ?
Ans. Like other languages, JavaScript supports comments in its code. Comments are completely ignored by
the JavaScript interpreter, so you can type whatever descriptive text you want. There are two types of
comments entry in JavaScript as:
x // Working with JavaScript. (Single-line comment)
x /* JavaScript programming supports the control statements like:
if, while and for */ (Multiline comment)
10. Explain about the number data type in JavaScript ?
Ans. There are two numeric types in JavaScript: integers and floating-point numbers. The rules for specifying
both types are almost identical. Integers may be specified in base 10 (decimal), base 8 (octal) or base 16
(hexadecimal) formats. Any of the three forms can also start with a + or sign.
11. How can you store string data in JavaScript? Explain with example.
Ans. A string is any grouping of characters that is surrounded by either double quotation marks () or single
quotation marks (). Strings are used anytime you want to use text in a program. For example,
"Class-XI"
"Multimedia & Web Technology"
12. Write the general rules for declaring variables in JavaScript.
Ans. The general rules are:
x The variable name cannot be a reserved word
x The first character in the name must be an alphabetic letter or an underscore(_)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.32 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

x Characters subsequent to the first character in the variable name can be alphabetic letters, numbers
or underscores.
x Variables are case sensitive.
13. Which escape sequences represent the newline character and tab in JavaScript?
Ans. The escape sequences are : \n and \t
14. What is a logical expression?
Ans. A logical (or Boolean) expression is an expression that when evaluated returns a result of either true or
false.
15. What are the types of numeric values in JavaScrpt?
Ans. JavaScript has two kinds of numeric valuesintegers and floating point.
16. What is escape sequence?
Ans. Combination of characters is preceded by a code-extension character (also called the escape character).
The code-extension character indicates that the succeeding characters are interpreted differently. Escape
sequences are normally used to control printed or displayed output. The characters interpreted with a
backslash (\) are called escape sequences or escape characters.
17. What are operators? Name them.
Ans. Operators are special symbols that perform a particular function on operands. There are five general
types of operators: arithmetical, logical, comparison, assignment and bitwise operators.
18. Name two specific purposes for the + operator.
Ans. The + operator can be used for arithmetic addition and for string concatenation.
19. Explain about conditional operator with its syntax.
Ans. The conditional operator ? is JavaScripts only ternary operator. A ternary operator requires three
operands instead of the single and double operands of unary and binary operators. The conditional
operator is used to replace if-else logic situations. The format of the conditional operator is:
conditional_expression ? expression1 : expression2;
20. What are expressions?
Ans. Expressions are combinations of operators and operands used to perform a calculation. For example,
var SI; // Simple interest
// Evaluated expression SI.
SI = (principal * rate * interest) / 100
21. What is a literal?
Ans. A literal is a sequence of characters used in a program to represent a constant value. For example, A is
a literal that represents the value A, of type char, and 17L is a literal that represents the number 17 as a
value of type long. A literal is a way of writing a value, and should not be confused with the value itself.
22. What is string literal?
Ans. A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be
delimited by quotes of the same type; that is, either both single quotes or double quotes.
23. Explain an assignment statement giving an example. What are assignment statements used for?
Ansn. An assignment statement computes a value and stores that value in a variable. Examples include:
x = 17; // Assign a constant value to the variable x.
newRow = row; // Copy the value from the variable row into the variable newRow.
ans = 17*x + 42; // Compute the value of the expression 17*x + 42 and store that value in ans.
An assignment statement is used to change the value of a variable as the program is running. Since the
value assigned to the variable can be another variable or an expression, assignment statements can be
used to copy data from one place to another in a computer, and to do complex computations.
24. State the difference between = and ==.
Ans. The = (assignment operator) is to assign the value of the variables, whereas == (relational operator)
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.33

is to compare two values. For example,


int x = 100; // Simple assignment
int y = 102;
if (x==y) // Compares two operands
25. Write a JavaScript statement to accomplish each of the following tasks:
(a) Declare variables sum and a to be of type int.
(b) Assign 1 to variable a.
(c) Assign 0 to variable sum.
(d) Add variable a to variable sum and assign the result to variable sum.
(e) Print The sum is: followed by the value of variable sum.
Ans. (a) var sum, a; (b) a = 1;
(c) sum = 0; (d) sum += a; or sum = sum + a;
(e) document.write("The sum is: " + sum);
26. What are relational operators? Give examples.
Ans. The operators that are used to do comparisons are called relational operators. For example, >, >=, <, <=,
etc.
27. What is the difference between / and % operator?
Ans. The / operator is used to find the quotient and the % operator produces remainder after dividing two
numbers with each other. For example, 5/2 produces 2 (quotient) and 5%2 produces 1 (reminder).
28. What is the use and syntax of a ternary operator?
Ans. The conditional operator (?) is a ternary operator, because it uses three operands. This operator is used
to check a condition and produce a logical result, either True or False. The syntax is:
condition ? expression1 : expression2;
29. Give one point of difference between unary and binary operators.
Ans. Unary Operators: A type of operators that work with one operand. For example, -,++,-- are the unary
operators. The operators are used with one operand as follows:
-a;
N++;
--x;
Binary operators: A type of operators that work with two operands are known as binary operators.
+,-,*,/,% these are binary operators.
30. Give the meaning of each of the following JavaScript operators:
(a) ++ (b) && (c) !=
Ans. (a) The operator ++ is used to add 1 to the value of a variable. For example, "count++" has the same
effect as "count = count + 1".
(b) The operator && represents the word and. It can be used to combine two Boolean values, as in "(x
> 0 && y > 0)", which means, "x is greater than 0 and y is greater than 0."
(c) The operation != means "is not equal to", as in "if (x != 0)", meaning "if x is not equal to zero".
31. If a = 5, b = 9, calculate the value of:
a+= a++ ++b + a;
Ans. The value is 6.
32. What will be the output of the following statement?
document.write ("1" + 3);
Ans. It will print 13.
33. What is the output of the following?
document.write("four :" + 4 + 2 + "<br>");
document.write("four :" + (2 + 2));
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.34 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Ans. The output is as follows:


four :42
four :4
34. If a = 5, b = 9, calculate the value of:
a+= a++ ++b + a;
Ans. The value is 6.
35. What will be the output of the following program?
var num = parseInt(100.2);
var perc = num;
document.write(" " + perc);
Ans. The output is: 100
36. What are the values of x and y when the following statements are executed?
var a = 63, b = 36;
var x = (a > b ? true : false);
var y = (a < b ? a : b);
Ans. The value of x = true.
The value of y = 36.
37. What will be the result stored in x after evaluating the following expression?
var x = 4; x += (x++) + (++x) + x;
Ans. The result of x = 20.
38. What is the output of the following code in JavaScript? Give reason.
(a) 10+20+"30"
(b) "10"+20+30
Ans. (a) 3030 because 10+20 will be 30. If there is numeric value before and after +, it is treated as binary +
(arithmetic operator).
(b) The output is 102030 because after a string all the + will be treated as string concatenation operator
(not binary +).
39. Find the output of the following:
var v = 1, a = 1, b = 2, c, d;
c = ++b;
c = ++b;
d = a++;
c++;
document.write((v == 1 ? "A" : "B") + "<br>");
v++;
document.write((v == 1 ? "A" : "B") + "<br>");
document.write("a = " + a + "<br>");
document.write("b = " + b + "<br>");
document.write("c = " + c + "<br>");
document.write("d = " + d);
Ans. The output is: (outputa.html)
A
B
a=2
b=4
c=5
d=1
40. Write four different JavaScript statements that each add 1 to integer variable num. Assume that the
initial value of num is 0.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.35

Ans. Four different JavaScript statements are:


(a) num = num + 1;
(b) num += 1;
(c) ++num;
(d) num++;
41. Write a statement for each of the following:
(a) Store a number 275 as a String
(b) Convert the String to a numeric value
(c) Add it to the existing total of 1000 to update the total.
Ans. (a) var num = "275";
(b) var num = parseInt(x);
(c) var total = 1000 + Nnum;
42. What are the values of x and y when the following statements are executed?
var a=63, b = 36;
var x = a > b ? true : false;
var y = a < b ? a : b;
Ans. The value of x = true.
The value of y = 36.
43. What will be the result stored in x after evaluating the following expression?
var x=4; x+=(x++)+(++x)+x;
Ans. The result of x = 20.
44. Explain the following command:
document.write ("Hello World .")
Ans. The write() method of document object prints a string called Hello World..
45. What is a unary operator? Write two unary operators.
Ans. The operator which needs only one operand is called unary operator. The ++ (increment ) and
(decrement) operators.
46. What will be displayed in the following line of a web browser?
document.write("Live\nIn Peace\tand harmony");
Ans. The output is:
Live In Peace and harmony
47. Write the statements for the each situation described below:
(i) Assign a value 2 to the variable A.
(ii) Assign the value represented by variable N to the variable N1.
(iii) Print the string "February" on the string.
(iv) Assign the value represented by the formula A2 + B2 + C to the variable X.
(v) Increase the value of the variable count by 2.
(vi) Assign the value 3 to the variable C1, C2, C3.
(vii) Print the value C1, C2, C3 in single line.
(viii) Print the value C1, C2, C3 in three separate lines.
(ix) Print the value of C1, C2, C3 in one line with some space between them.
(x) Print the statement Hello! World in the following format :
Hello!
World.
Ans. (i) var A = 2; (ii) var N = 100;
var N1 = N;
(iii) document.write("February"); (iv) var X = A^2 + B^2 + C;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.36 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

(v) count = count + 2; (vi) var C1 = C2 = C3 = 3;


(vii) document.write(C1 + " " + C2 + " " + C3);
(viii) document.write(C1 + "<br> " + C2 + "<br> " + C3);
(ix) document.write(C1 + "\t\t " + C2 + "\t\t" + C3);
(ix) document.write("Hello!" + "<br>" + "World.");
48. Write JavaScript statements to accomplish each of the following:
(a) Assign the sum of a and b to c and increment the value of a by 1 after calculation. Use only one
statement.
(b) Decrease the variable a by 1, then subtract it from the variable num. Use only one statement.
(c) Calculate the remainder after q is divided by divisor and assign the result to q. Write this statement
in two different ways.
Ans. (a) c = a++ + b; (b) sum = a;
(c) q %= divisor;
q = q % divisor;
49. What will be the output of the following program :
var x = 2, y = parseFloat(5.00);
document.write("The value of x is " + x+10*y + "<br>");
document.write("The value of y is " + x+10/y);
Ans. The output is:
The value of x is 250
The value of y is 22
50. Evaluate the following expressions, if the values of the variables are a = 2, b = 3 and c = 9.
(a) a = (b++) * (c) (b) a = (++b) % c
Ans. (a) The value of the expression is: 24
(b) The value of the expression is: 5
51. Write the results of the following JavaScript statements:
var c, d = true, e = false;
c = d & e;
document.write("Value of c: "+ c + "<br>");
d &= e;
document.write("\nValue of d: "+ d + "<br>");
e = d;
document.write("\nValue of e: "+ e + "<br>");
c ^= e;
document.write("\nValue of c: " +c);
Ans. The results are:
Value of c: 0
Value of d: 0
Value of e: 0
Value of c: 0
52. What will be the output of the following code segment?
var a = 5, b = 10, c = 9, d = 8;
document.write(" " + ((a++) + (++c) - (--b) + (d--)));
document.write(" " + a>b ? c>d ? ++d : 35 : --b);
Ans. The output is line: document.write(" " + ((a++) + (++c) - (--b) + (d--)));
is 14.
The output is line: document.write(" " + a>b ? c>d ? ++d : 35 : --b);
is 8.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.37

53. Rewrite the following in Ternary operator


if (income <= 10000)
tax = 0;
else
tax =12;
Ans. The statement is:
tax = income <= 10000 ? 0 : 12;
54. Differentiate between confirm() and alert() methods.
Ans. The confirm() method of window object brings up a dialog box with Yes or No buttons and a user-
specified message.
The alert() method brings up an alert dialog box. alert(.) is the standard function for bringing up an
alert dialog box on the screen.
55. Write a JavaScript code to enter the price of a pencil and quantity of pencils and calculate total amount
as price*quantity. Display the amount and tax as 10% in browser window.
Ans. The JavaScript code is: (price.html)
<HTML>
<HEAD>
<TITLE>Price calculation</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var price = parseFloat(prompt('Enter price')); // Price of pencil
var qty = parseInt(prompt('Enter quantity')); // Quantity of pencil
var tot = price * qty; // Total price
var tax = tot * 10/100; // Tax amount
document.write("Total price: " + tot + "<br>");
document.write("Tax: " +tax);
</script>
</BODY>
</HTML>

REVIEW QUESTIONS
1. What are variables?
2. Describe the five categories of the JavaScript.
3. What is the use of SRC?
4. What attribute can the JavaScript <SCRIPT> tag accept?
5. What is the difference between single-line and multiline comments?
6. How many data types are available in the JavaScript?
7. What is the use of bitwise operator?
8. What are keywords?
9. What are the rules to be followed while naming the identifier?
10. Classify the following into valid and invalid identifier:
(i) Mybook (ii) Break (iii) _DK (iv) My.book
11. What are integer variables?
12. What are character variables?
13. What are float-point variables?
14. How will statements get terminated in JavaScript?
15. Write a statement to declare three integers and store them in the variables x, y and z.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.38 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

16. Answer the following:


(a) Assign the value of the variable number1 to the variable total.
(b) Assign the sum of the two variables loop_count and petrol_cost to the variable sum.
(c) Assign the character W to the char variable letter.
(d) Assign the result of dividing the integer variable sum by 3 into the float variable costing. Use type-
casting to ensure that the remainder is also held by the float variable.
(e) Divide the variables total by the value 10 and leave the result in the variable discount.
17. Answer the following using JavaScript statement:
(a) to print out the value of the integer variable sum.
(b) to print out the character variable letter.
(c) to print a float variable into the variable discount_rate.
18. Which of the following are invalid names and why?
(i) PaidInterest (ii) s-num (iii) percent (iv) 123
(v) dit km (vi) class (vii) main
19. What value will be stored in different variables when the following JavaScript statements are executed?
var i = 10;
var j = i + 5;
var k= i + j / 5;
var l = k + 1;
var m = l + 1 i;
var n = k + m * l;
document.write(i + " " + "<br>" + k + " " + "<br>" + l + " " + "<br>" + m + " " + "<br>" +
n);
20. Is the line given below a valid comment?
// This is a /* valid*/ comment
21. Correct the error, if any, in the following statements:
(i) var 3* 5; (ii) l*b = area; (iii) l = ab + c*d; (iv) A = P * R * N/100;
(v) area = 3.14 * R**R;
22. What will be the output of the following statements:
var a= 10;
var b= 5;
var c= 7;
document.write(a + " " + b + " " + c + "<br>");
document.write(a + "\t" + b + "\t" + c + "<br>");
document.write(a + "\n" + b + "\n" + c);
23. In each of the following cases, show how the comment can be placed in the JavaScript program:
(i) Add the program-heading Sum of the odd and even numbers.
(ii) Add the comment average value to the statement:
x = sum/n;
(iii) Add the comment begin of main with the main() statement.
24. Give the output of the following program segment:
var i = 100, j = 9;
document.write(i/j);
25. What is the purpose of comments and indentation in a program?
26. What will be the output of the following program?
var x=2;
var y=5;
document.write("The value of x is " + x + 10 * y);
document.write("The value of y is "+ x + 10 / y);
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.39

JavaScript F unctions
Functions
2
2.1 INTRODUCTION

The basic statements, expressions and operators that were discussed in previous chapter is what computer
scientists usually call primitives. Primitives are the building blocks from which more complex elements of a
program are constructed. Functions and objects represent the highest level of organization within the JavaScript
language.

2.2 FUNCTIONS

A function is a block of code that will be executed when "someone" calls it. In JavaScript, we can define our own
functions, called user-defined functions, or we can use built-in functions already defined in the JavaScript
language. We have already seen examples of built-in functions, such as:
x window.alert( )
x document.write( )
x parseInt( )
Below, we will show how to define our own user-defined functions. Functions are the central working units
of JavaScript.

 'HILQLQJ )XQFWLRQ

A function definition is just a regular variable definition where the value given to the variable happens to be a
function. A function is a block of code that has a name. Whenever that name is used the function is called,
which means that the code within that function is executed. Functions may also be called with values, known
as parameters, which may be used inside the body of the function. Functions serve two purposes:
x A function is an organizational tool, in the sense that it permits you to perform the same operation
without simply copying the same code.
x The second purpose of JavaScript functions is to link actions on a Web page with JavaScript code.
Mouse clicks, button presses, text selection and other user actions can call JavaScript functions by
including suitable tags in the HTML source for the page.
JavaScript provides several ways of defining them:
x Function Declaration
x Function Expression

3.39
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.40 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

x Function as a result of a new Function call


N ote
A function is written as a code block (inside curly { } braces),
preceded by the function keyword. The basic syntax to create a function JavaScript is case sensitive.
is a Function Declaration. The syntax is: The function keyword must be
written in lowercase letters, and
function function_name (arg1, arg2, ....) the function must be called with
{
the same capitals as used in the
some statements/code;
return somevalue;
function name.
}

From the above syntax,


x The function_name is given immediately after the function keyword.
x All function names should be unique and also should not conflict with any of the statement names
which JavaScript itself uses (known as the reserved words). For example, you cannot have a function
named while and you should not have two functions both named diplay_name.
x The arg1, arg2, .... is a comma-separated list of the values that are passed into the function. These
are referred to as functions parameters or arguments.
x This list may be empty, indicating that the function does not use any argument (often called a void
function).
x The functions body (statements) is the set of statements that make up the function.
x The return statement is option, but a function can return a value.
The code inside the function will be executed when "someone" calls the function. The function can be
called directly when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by
JavaScript code.
JavaScript user-defined functions should be defined in the HEAD section of an HTML document. The
reason for placing JavaScript functions in the HEAD section is the function must be defined and loaded into
memory before the function can be called by JavaScript code or an event handler.
Below, we define a function named print_message() in the HEAD section of the webpage. The function
contains one statement of code, to display a message box. The function is called later in a SCRIPT element in
the BODY section of the webpage.
Example Using the JavaScript code write the HTML code to demonstrate the user-defined function.
Solution Write the following code in Notepad editor and save as jfun01.html.
<html>
<title>Simple function demo</title>
<head>
<SCRIPT type="text/javascript">
// Called function
function print_message() // Define function print_message()
{
alert("Function to avoid repetition of code");
}
</script>
</head>
<body>
<script language = "JavaScript">
print_message(); // Call function print_message()
</script>
</body>
</html>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.41

In the above program the function print_message() is invoked from JavaScript. Then the control passes
to print_message() function, and the body of the function gets executed. Simultaneously the execution
control returned back to JavaScript to execute the remaining statements.

Figure 2.1 A simple function output.

Here from the function declaration, the JavaScript, which invokes the function print_message(), is called
the calling function and the function print_message() is the called function.
Example Write a JavaScript function to display the temperature value in an alert window. The code
should enter the temperature value in an HTML text box.
Solution Write the following code in Notepad editor and save as jfun02.html.
<html>
<head>
<title>Temperature in Fahrenheit</title>
</head>
<SCRIPT type="text/javascript">
function show_temp()
{
var Tval=frm.txt.value;
alert("The temperature in Fahrenheit is " + Tval + " degrees F.")
}
</script>
<FORM name="frm">
Enter Number in Degrees Fahrenheit:
<input type=text size="20" name="txt">
<input type="button" value='Temperature' OnClick="show_temp()">
</FORM>
</html>

Here, a FORM is used to hold a text entry box labeled txt and a push button labeled show_temp. When
the user clicks on this button, the associated JavaScript function show_temp() is invoked.
The statement,
var Tval=frm.txt.value;

inside the function show_temp() sets the variable and allows access to the text entry box txt. alert()
abd displays the temperature value by using concatenated strings operator +.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.42 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

x After typing, save the file with the name ...\Unit 3\Chapter 2\jfun02.html and browse in IE.
x In IE when you enter the details and press the Temperature button, the screen will look as shown
in Figure 2.2.

Figure 2.2 Function to display temperature.

2.2.1 Function Returning Value

A JavaScript function can return a value using return statement. The value returned can be a valid JavaScript
type. A return statement determines the value the function returns. When control comes across such a
statement, it immediately jumps out of the current function and gives the returned value to the code that called
the function. The syntax is:
return (return value);

When using the return statement, the function will stop executing, and return the specified value.

2.2.2 Function Using Arguments/Parameters


Like other programming languages, a JavaScript function can also handle arguments in its function. The
parameters to a function behave like regular variables, but their initial values are given by the caller of the
function, not the code in the function itself. When you call a function, you can pass along some values to it,
these values are called parameters or arguments.
Parameters are the variables we specify when we define the function. When the function is later called
somewhere else in the code, arguments are the values passed as parameters. You can specify as many parameters
as you like, separated by commas (,). The parameters then serve as variables that can be used inside the
function.
JavaScript passes values by reference, meaning that when you pass a value to a function, you are really
just passing a value pointer to the function. (A value pointer is just an address, similar to a house address on
an envelope that gives information about how to find the house.) If the function modifies that value, the value
is changed for the entire script, not just the scope of the function. For example,
<script language = "JavaScript">
function welcome(myName) // In the function declaration, we specify the parameter myName
{
alert( "Welcome " + myName + " to my website!" );
}
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.43

</script>
<script language = "JavaScript">
// When the function is called, "Navya Singhal" is the argument passed to the function
welcome( "Navya Singhal" ); // Function argument
</script>

The function above will display the message box "Welcome Navya Singhal to my website!" when the
function is called in the webpage.

 )RUPDO 9DULDEOHV3DUDPHWHUV

The variables (or parameters) which accept the actual variables inside the function are called formal variables.
Each function definition contains an argument list called the formal argument list. Items in the list are optional,
so the actual list may be empty or it may contain any combination of data types such as inteter, float and
character. For example,
// Formal arguments in function declaration
<SCRIPT type="text/javascript">
function welcome(myName)
{
alert( "Welcome " + myName + " to my website!" );
}
</script>

Here, myName is a formal arguments.


Let us consider another example,
function maxTwo(a, b) {
if (a > b)
return a;
else
return b;
}
In the above function, a and b are formal parameters. They are called formal because actual parameter
values are supplied to the function by the calling program, and formal parameters use the copy of those actual
parameters.

 $FWXDO 9DULDEOHV3DUDPHWHUV

The variables which are associated with function name during function call are called actual variables. When
the program calls the function, an argument list is also passed to the function. This list is called the actual
argument list. For example,
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function calc_Avg(num1, num2, num3) // Formal parameters
{
var local_avg; // Holds average for these numbers
local_avg = (num1 + num2 + num3) / 3;
return (local_avg);
}
// Call the function, passing the numbers, and accept return value
var avg = calc_Avg(100, 235, 400); // Actual parameters
....
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.44 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

....
</script>

Here, 100, 235, and 400 are the actual arguments, which are passed into the calc_Avg() function.
Example Write a JavaScript function to find the average of three numbers. The three numbers should
be treated as parameter to the function. Also, function should return the average and all
details.
Solution Write the following code in Notepad editor and save as jfun01.html.
<HTML>
<HEAD>
<TITLE>JavaScript Function return Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function calc_Avg(num1, num2, num3) // Formal parameters
{
var local_avg; // Holds average for these numbers
local_avg = (num1 + num2 + num3) / 3;
return (local_avg);
}
var num1 = 100, num2 = 235, num3 = 400;
var avg; // Will hold the return value
// Call the function, passing the numbers, and accept return value
avg = calc_Avg(num1, num2, num3); // Actual parameters
document.write("The first number is : " + num1 + "<br>");
document.write("The second number is : " + num2 + "<br>");
document.write("The third number is : " + num3 + "<br>");
document.write("The average is : " + avg );
</script>
</BODY>
</HTML>
Open the jfun02.html file in IE, and see the output window as shown in Figure 2.3.

Figue 2.3 Average of three numbers.

The calc_Avg() function above takes three numbers as parameters, and returns the average of the three
numbers. On Line,
avg = calc_Avg(num1, num2, num3);
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.45

when the calc_Avg() function is called, the value 245 is returned and then stored in the variable avg.
The above declaration is called function expression. When the JavaScript parser sees a function in the
main code flow, it assumes Function Declaration. When a function comes as a part of a statement, it is a
Function Expression.
You can also use the value returned by the calc_Avg() function without storing it as a variable. For
instance, we could call the function and use the return value in the document.write() line:
document.write("The average is : " + cal_Avg(num1, num2, num3);

Example A web page for an organization is given below:

Write a JavaScript function called Fullname() to concatenate two names and also display in
third textbox.
Solution Write the following code in Notepad editor and save as jfun03.html.
<html>
<head>
<title>Employees Payroll</title>
<SCRIPT type="text/javascript">
function Fullname()
{
var nName = frm.txt1.value + " " + frm.txt2.value;
frm.txt3.value = nName;
}
</script>
</head>
<body>
<h2>Real Value System - Employees Payroll</h2>
<form name="frm">
<TABLE cellPadding=2 width="60%" border=1 color="BLUE">
<tr>
<td>Enter first name</td>
<td><input type=text name="txt1" size="20"></td> </tr>
<tr>
<td>Enter last name</td>
<td><input type=text name="txt2" size="20"></td> </tr>
<tr align="center">
<td COLSPAN="2"><input type="button" value="Proceed"
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.46 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

onclick="Fullname()"></td></tr>
<tr> <td>Full name:</td>
<td><input type=text name="txt3" size="40" READONLY>
</td><td></td>
</table>
</form>
</body>
</html>

2.3 SCOPE AND LIFETIME OF VARIABLES


The scope of a variable means how the different parts of the program can access that variable. When scope of
a variable is used in a method, the variable affects only that method.
The scope of a variable is that region of the program within which it can be used. The lifetime of a variable
is the period during which it can be accessed. JavaScript has five kinds of variables: loop scopes, local
variables, static variables, instance variables and class variables.

/RRS 6FRSHV

In the previous chapter, we declared different variables inside loops. Any variables created inside a loop are
treated as local scope or local variables to the loop. This means that once you exit the loop, the variable can no
longer be accessed. This includes any variables created in the loop signature. Let us see following two
examples:
Example 1:

for (i = 0; i <= 10; i++)


{
document.write("\nloop scope variable " + i + "<br>");
}

Example 2:

var i;
for (i = 0; i <= 10; i++)
{
document.write(("\nloop scope variable " + i + "<br>");
}

In Example 1, i can only be used inside the for loop. In Example 2, you are free to use i inside the loop as
well as outside the loop because it was declared outside the loop (it has been declared as method scope).

/RFDO 6FRSHV

The variables which are declared inside a function/method are called local variables. You may use a local
variable completely within a function definition. Its scope is then limited to the function itself, i.e., it can be used
only within the declaring method. The variable is said to be accessible or visible within the function only and
has a local scope.
For example,
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function calc_Avg(num1, num2, num3)
{
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.47

var local_avg; // Holds average for these numbers


local_avg = (num1 + num2 + num3) / 3;
return (local_avg);
}
var num1 = 100, num2 = 235, num3 = 400;
var avg; // Will hold the return value
// Call the function, passing the numbers, and accept return value
avg = calc_Avg(num1, num2, num3);
document.write("The first number is : " + num1 + "<br>");
document.write("The second number is : " + num2 + "<br>");
document.write("The third number is : " + num3 + "<br>");
document.write("The average is : " + local_avg);
</script>

Here in line,
document.write("The average is : " + local_avg);

will produce an arror, because local_avg is a local variable to the function.


You can have local variables with the same name in different functions, because local variables are only
recognized by the function in which they are declared. Following are some of the features of local variables:
x They can be used only in those statements that are inside the same block in which local variables are
declared. That is, the local variables are not known outside of their own code block. For example,
fun1() {
var a = 5; // a is a local variable and block scope
}
fun2() {
var a = 10; // a is a local variable and block scope
}

Here, the integer variable a is declared twice, once in fun1() and once in fun2(), but the a in fun1() has
no effect on function fun2(). This is because a is known only to the code within the block in which it is
declared.
Local variables are deleted from memory as soon as the function is completed
x We can also declare local variables inside any code block that is nested inside another code block.
For example, consider the following function:
void fun() {
var age = prompt("Enter your age")
if (age == 18) {
document.write("Your age is accurate for voting");
}
}

Here, the local variable guess is created at the entry of the function fun() and so its scope remains until the
terminating curly brace of the function fun() is encountered. However, the local variable age is created upon
entry into the if code block and destroyed upon the exit from the if block. That is, age is known only within the
if block and cannot be referenced elsewhere within the outer block (i.e., of the fun()).
We can initialize the local variable to some value. Now, this value will be assigned to the variable each time
we will enter the block of code in which it was declared, no matter if the value is later modified in the block.
If you try to access the local variable outside the method, the compiler would flag it as an error. However,
the same variable name can be declared within several different methods without there being a conflict.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.48 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

*OREDO 6FRSHV N ote

A global scope variable is visible to all functions/methods and is To declare JavaScript global
declared outside the method, and all scripts and functions on the web variables inside function, you
page can access it. For example, need to use window object.
When you declare a variable
var i; // i is a global variable outside the function, it is added
There can be situations where a local variable with the same name in the window object internally.
is used in a function. Then the local variable hides the global variable, You can access it through
i.e., the function will give preference to the local variable as compared window object also. For
to the global variable. example:
Global variables, variables declared outside of a function, are
deleted when you close the page. The following example, describes var Num = 10;
both global and local variables in JavaScript program: function a(){
//accessing global variable
<SCRIPT type="text/javascript">
// Difference between Global and Local Variables alert(window.value);
// Declare the global variables }
var global_one = 32;
var global_two;
function test {
// This function has a local variable a global value is copied into it
// the local is then passed into a function as a parameter
var local_var; // Local variable
local_var = global_one; // Copy global
// into local
func_two(local_var);
}
function func_two(number) {
// create a local variable and copy a parameter into it
var local_var = number;
}
// copying a local variable into a global
// like this is not allowed
global_two = local_var
</script>

2.4 JAVASCRIPT BUILT-IN FUNCTIONS


JavaScript has several "top-level" built-in functions. These functions perform themselvesf with other JavaScript
statements. JavaScript function is a name, which is pre-written in the interpreter. Table 2.1 shows some of them.
Table 2.1 JavaScript built-in functions.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Function Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
eval(string) Evaluates codestring as JavaScript code, returning anything that
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
JavaScript returns.
123456789012345678901234567890121234567890123456789012345
escape(string)
123456789012345678901234567890121234567890123456789012345
Returns the conversion of charstring into a form that displays in
123456789012345678901234567890121234567890123456789012345
the browser without HTML markup.
123456789012345678901234567890121234567890123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.49
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
unescape(string)
123456789012345678901234567890121234567890123456789012345
This is just reverse of escape function.
123456789012345678901234567890121234567890123456789012345
IsNan(numValue) Returns true if numvalue is not a number, otherwise returns false
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
used with parseFloat and parseInt function.
123456789012345678901234567890121234567890123456789012345
parseInt(numString)
123456789012345678901234567890121234567890123456789012345
Converts a string into an integer.
123456789012345678901234567890121234567890123456789012345
parseFloat(numString, radix) Converts a string into a floating-point number.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
round(number) To get rounded value of a number.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
ceil(number) To get the next higher integer.
123456789012345678901234567890121234567890123456789012345
floor(number)
123456789012345678901234567890121234567890123456789012345
To get just next highest lower integer.
123456789012345678901234567890121234567890123456789012345
pow(number) To get the power of an integer.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
max(number) To get the highest integer from a set of number.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
sqrt(number) To get get square root of any number.

eval(). This function evaluates a string as a JavaScript statement or expression, and either executes
it or returns the resulting value. The syntax is:
eval(string)

A string representing a JavaScript expression, statement, or sequence of statements. The expression


can include variables and properties of existing objects.
For example,
eval(new String("2 + 2")); // returns a String object containing "2 + 2"
eval("2 + 2"); // returns 4
var x = 2;
var y = 4;
var x = 2
var y = 39
var z = "42"
document.write(eval("x + y + 1"))
document.write(eval(z))

escape(). This function encodes the string passed to it so that it can be used across any network,
say, for example, in query strings. The syntax is:
escape(string)

string is a String object or literal to be encoded.


For example,
document.write(escape("testing escape function!!"));

which prints:
testing%20escape%20function%21%21

escape() function leaves digits,latin letters and the characters + - * / . _ @ unchanged and replaces all
other characters with ASCII code of the original character preceded by % symbol.
unescape(). This method is used to decode the encoded strings and returns the ASCII string for the
specified value. The syntax is:
unescape(string)

string is a String object or literal to be encoded.


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.50 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

For each distinct set of characters in the argument string of the following form
x "%integer", where integer is a number between 0 and 255 (decimal)
x "hex", where hex is a number between 0x0 and 0xFF (hexadecimal)
For example,
unescape("%26") // returns "&"
unescape("ab%21%23" // returns "ab!#"

isNaN(). This function determines whether the value of a variable is a legal number or not. This
function is remembered as short form is Is Not a Number. This function returns true if the data is string
and returns false if the data is a number. Here is one simple example to check one string. The syntax is:
isNaN(numValue)

numValue is the value to be tested against NaN.


N ote
For example,
<SCRIPT type="text/javascript"> If you face problem to find the
document.write(isNaN(NaN)); // true result in IE, use some other
document.write("<br>"); browser.
document.write(isNaN(undefined)); // true
document.write(isNaN({})); // true
document.write(isNaN(true)); // false
document.write(isNaN(null)); // false
// number
document.write(isNaN(37)); // false
// String
document.write(isNaN("abcdefg")) // true: "abcdefg" is converted to a number.
// Parsing this as a number fails and returns NaN
document.write(isNaN("")); // false: the empty string is converted to 0 which is not NaN
document.write(isNaN("30")) // false
// dates
document.write(isNaN(new Date())); // false
document.write(isNaN(new Date().toString())); // true
</script>

The function is better use in if condition to check to display a message accordingly. For example,
var myString = prompt("Enter a number");
if (isNaN(myString)) {
alert("This is not a number ");
} else {
alert("This is a number ");
}

parseInt(). This function is used to convert strings to numbers. This function can only convert
strings which are in the form of numbers and it can't change any alphabet or strings. If there is no
number at the beginning of the string, "NaN" (not a number) is returned. The syntax is:
parseInt(numString, [radix])

Here, numString is string to convert into a number.


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.51

For example,
document.write(parseInt("124.56")); // return 124.
document.write(parseInt("abc34")); // Returns NaN.
document.write(parseInt("25.5abc")); // Returns 25.
document.write(parseInt("216.0PLL")); // Returns 216.

parseFloat(). This function is used to convert strings to float numbers. Using this function, we can
only convert string numbers to numeric data but we can't convert alphabetic characters. The syntax is:
parseFloat(numString)

Here, numString is string that contains a floating-point number to convert into a number. The parseFloat
function returns a numerical value equal to the number contained in numString. If no prefix of numString
can be successfully parsed into a floating-point number, NaN (not a number) is returned.
For example,
document.write(parseFloat("124.56")) // return 124.56.
document.write("<br>");
document.write(parseFloat("abc34")); // Returns NaN.
document.write(parseFloat("25.5abc")); // Returns 25.5.
document.write(parseFloat("216.0PLL")); // Returns 216.

round(). This function is used to round off any number with decimal place to an integer value by
using round function. If the decimal portion of the number is equal or greater than .5 then the next
higher integer is returned or if the number is less than 05 then the number is rounded to next lowest
integer. The syntax is:
Math.round(number)
For example,
document.write (Math.round(22.75)); // print 23
document.write("<br>");
document.write (Math.round(17.05)); // print 17
document.write (Math.round(-22.75)); // print -23
document.write (Math.round(-18.15)); // print -18
document.write (Math.round(21.65)); // print 22

We can format math number by using round function. Here is an example to format upto two decimal
places.
var Num = 11.257;
document.write (Math.round(Num * 100) / 100);

ceil(). This function is used ceil of a number to the smallest integer that is greater than or equal to
given number. So by using this we can get the next higher integer of a given number. The syntax is:
Math.ceil(number)

For example,
document.write (Math.ceil(24.314)); // output 25
document.write (Math.ceil(20.56)); // output 21
document.write (Math.ceil(-13.564)); // output -13

floor(). This function is used to get the floor of a number or the largest integer which is equal to or
lower than the given number. So by using floor we can get the floor value of an number.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.52 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

The syntax is:


Math.floor(number)

For example,
document.write (Math.floor(24.314)); // output 24
document.write (Math.floor(20.56)); // output 20
document.write (Math.floor(-13.564)); // output -14
pow(number). This function is used to get the power of an integer. The syntax is:

Math.pow(x,y)

For example,
document.write(Math.pow(5,5)); // output is 3125
document.write(Math.pow(0,0)); // output is 1
document.write(Math.pow(0,1)); // output is 0
document.write(Math.pow(1,0)); // output is 1
document.write(Math.pow(1,1)); // output is 1
document.write(Math.pow(2,2)); // output is 4
document.write(Math.pow(2,-2)); // output is 0.25
document.write(Math.pow(-2,2)); // output is 4

max(number). This function is used to get highest value from a set of numbers. The syntax is:
Math.max(x1,x2,x3,.xn)

For example,
document.write(Math.max(23,12,24,15,17,5)); // output is 24
document.write("<br>");
document.write(Math.max(-5,16,-22,12,-20)); // output is 16
document.write("<br>");
document.write(Math.max(-12,-23,-3)); // output is -3

sqrt(number). To get square root of any number. The syntax is:

Math.sqrt(x);
For example,
document.write(Math.sqrt(4)); // output is 2
document.write("<br>");
document.write(Math.sqrt(64)); // output is 8
document.write("<br>");
document.write(Math.sqrt(9)); // output is 3
document.write("<br>");
document.write(Math.sqrt(27)); // output is 5.196152422706632
document.write("<br>");
document.write(Math.sqrt(0.36)); // output is 0.6
document.write("<br>");
document.write(Math.sqrt(-64)); // output is Nan

'DWH DQG 7LPH )LQFWLRQV

The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times.
JavaScripts Date object follows the UNIX standard of storing date and time information internally as the
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.53

number of milliseconds since January 1, 1970. You can create a Date


N o te
object anytime you need to store a date, and use the Date object's
methods to work with the date. JavaScript dates are stored as
Before using any of the date and time method, you must create the the number of milliseconds since
Date object using new keyword. You can also optionally specify the midnight, January 1, 1970. This
date to store in the object when you create it. The Date object is date is called the epoch. Dates
predefined in JavaScript and will build this instance filling in the current before 1970 weren't allowed in
date and time from the clients system clock. The syntax is: early versions, but are now
represented by negative
VariableName = new Date(parameters)
numbers.
For example,
var Today = new Date(); // Date object for current date

You have several optional parameters that we may send to the Date object as follows :
x variableName = new Date().
x variableName = new Date("month day, year hour:minutes:seconds").
x variableName = new Date(year, month, day).
x variableName = new Date(year, month, day, hours, minutes, seconds).

For example,
var BDay = new Date("May 18, 2004 03:00:00"); // Setting a new date

Once you have created a Date object, you can then use the many Date methods to get or set the month,
day, year, hours, minutes or seconds of this instance. As with most object methods, you simply call a Date
method as follows:
variableName.methodname(parameters)

For example,
today.setHours(7);

There are two exceptions to this rule with the Date object: The UTC and parse methods are static
methods and are always called with just the generic Date object name. For example,
Date.UTC(parameters)
Date.parse(parameters)

Table 2.2 shows some usable date and functions.


123456789012345678901234567890121234567890123456789012345
Table 2.2 JavaScript built-in date and time functions.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Function Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
getDate() The day of the month as an integer from 1 to 31.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
getYear() The year, but this format differs from browser to browser.
123456789012345678901234567890121234567890123456789012345
getMonth()
123456789012345678901234567890121234567890123456789012345
The month is an integer between 0 and 11 where 0 is January and 11 is
123456789012345678901234567890121234567890123456789012345
December.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
getDay() The day of the week as an integer where 0 is Sunday and 1 is Monday.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
getTime() The current time in milliseconds where 0 is January 1, 1970, 00:00:00.
123456789012345678901234567890121234567890123456789012345
getHours()
123456789012345678901234567890121234567890123456789012345
The hour as an integer between 0 and 23.
123456789012345678901234567890121234567890123456789012345
getMinutes() The hour as an integer between 0 and 59.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.54 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
getSeconds() The seconds as an integer between 0 and 59.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
getTimeZoneoffset() Returns the difference between the local time and GMT (Greenwich Mean
123456789012345678901234567890121234567890123456789012345
Time).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
parse() Returns the number of milliseconds since January 1, 1970 00:00:00.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
setDate() Sets the numeric date of a Date object.
123456789012345678901234567890121234567890123456789012345
setHours()
123456789012345678901234567890121234567890123456789012345
Sets the hour of the given time.
123456789012345678901234567890121234567890123456789012345
setMinutes() Sets the minute of the given time object between 0 and 59.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
setMonth() Sets the month integer in the given Date object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
setSeconds() Sets the second of the given Date object.
123456789012345678901234567890121234567890123456789012345
setTime()
123456789012345678901234567890121234567890123456789012345
Sets the time value using an integer representing the number of seconds
123456789012345678901234567890121234567890123456789012345
since January 1, 1970.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
setYear() Sets the year of the current date.
123456789012345678901234567890121234567890123456789012345
toGMTString()
123456789012345678901234567890121234567890123456789012345
Converts the date to a string using the GMT.
123456789012345678901234567890121234567890123456789012345
toLocalString() Converts a date to a string using the locale conventions.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
UTC() UTC stands for Universal Time Coordinated and is equivalent to GMT.

In Table 6.3, two methods are shown. One is get method and the other is set method. The get method allows
you to retrieve information from the current Date object. This information can be seconds, minutes, hours,
days of the month, days of the week, months or years. For example,
today = new Date("September 27, 1997")
document.write("Birthday is on " + today.getdate())
N ote
Similarly, the set method allows you to add or change attributes
of the Date object. You can change the dates, months, years, hours, The getMonth() returns a
minutes, seconds of the Date object. All of these methods require number between 0 and 11; if
integers. Although you will probably use the get methods more often, you want to show the month to
these methods are handy when you want to quickly create a date and your site's visitors, to be user-
timeperhaps for displaying on a page with a modification date. For friendly you should add 1 to the
example, month after using getMonth().
today = new Date("September 27, 1997")
today.setDate(4);
document.write(today.getDate());

Create a JavaScript file and save as jfun04.html with following code:


<HTML>
<HEAD>
<TITLE>JavaScript Date and Time function test</TITLE>
</head>
<body>
<SCRIPT type="text/javascript">
function DateDisplay()
{
var CDate = new Date();
var BDay = new Date("May 18, 2004 03:00:00");
document.write("Current date: " + CDate + "<br>");
document.write("Birthday: " + BDay + "<br>");
document.write("Birth Day of the month: " + BDay.getDate() + "<br>");
document.write("Year: " + CDate.getYear() + "<br>");
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.55

document.write("Month: " + CDate.getMonth()+1 + "<br>");


document.write("Day: " + CDate.getDay() + "<br>");
document.write("Current time: " + CDate.getTime() + "<br>");
document.write("Hour: " + CDate.getHours() + "<br>");
document.write("Minutes: " + CDate.getMinutes() + "<br>");
document.write("Seconds: " + CDate.getSeconds() + "<br>");
}
DateDisplay();
</script>
</body>
</html>

Open the jfun04.html file in IE, and the see the output window as shown in Figure 2.4.

Figue 2.4 Date and time function result.

6WULQJ )LQFWLRQV

JavaScript contains some basic string manipulation functions which are useful for JavaScript query. As we
know, when we declare and manipulate strings in JavaScript, always write them with single quotes ' or double
quotes " around them. This tells the browser that it's dealing with a string.
For example,
var a = "Hello world!";
var b = 'I am a JavaScript hacker.'

Here, both a and b are two strings and declared in double quotes and single quotes. But be careful, don't mix
up the quotes.
The JavaScript String object is a wrapper for text values. In addition to storing text, the String object
includes a property and various methods to manipulate or gather information about text. The syntax of creating
String object using new keyword is given below:

var StringName=new String("string literal");

Here, new keyword is used to create instance of string.


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.56 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Table 2.3 shows some usable string functions.


123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Table 2.3 JavaScript built-in string functions.
123456789012345678901234567890121234567890123456789012345
Function Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
charAt() Returns the character at index.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
concat() Joins strings
123456789012345678901234567890121234567890123456789012345
indexOf()
123456789012345678901234567890121234567890123456789012345
Finds position of a substring.
123456789012345678901234567890121234567890123456789012345
lastIndexOf() Finds position of a substring.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
length() Returns the length of the string.
123456789012345678901234567890121234567890123456789012345
substr()
123456789012345678901234567890121234567890123456789012345
Extracts x characters of a String starting at Index
123456789012345678901234567890121234567890123456789012345
substring() Extracts a substring from index to ending Index
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
toLowerCase() Converts the string to lower case
123456789012345678901234567890121234567890123456789012345
toUpperCase()
123456789012345678901234567890121234567890123456789012345
Converts the string to upper case
123456789012345678901234567890121234567890123456789012345
toString() Returns the String Object as a String
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
valueOf() Return the primitive value of an object.

charAt(). This function returns the character at the x position within the string. The syntax is:

str.charAt(x);

Here str is a string and x is the position where a character will extract. For example,
var str = "Multimedia and Web Technology, Class - XI";
document.write("Character at 7th place: ", str.charAt(7)); // Returns d

concat(). This function combines one or more strings (arguments str1, str2, etc.) into the existing
one and returns the combined string. Original string is not modified. The syntax is:
str.concat(str1, str2, ...);

For example,
var str1 = "CBSE";
var str2 = " Multimedia";
str1 = str1.concat(str2, ' Class - XI');
document.write("New string is: ", str1);

Here, str1 is the original string which holds the string of str1, str2 and Class - XI. The final result
of str1 will be: CBSE Multimedia Class - XI.
indexOf(). This function searches and (if found) returns the index number of the searched character
or substring within the string. If not found, -1 is returned. Start is an optional argument specifying
the position within string to begin the search. Default is 0. The syntax is:
str.indexOf(char/substring)

Here char/substring is a character whose position will be searched in string str. For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Index of M is: ", str1.indexOf('M'));

which will produce Index of M is: 5.


lastIndexOf(). This function searches and (if found) returns the index number of the searched
character or substring within the string. Searches the string from end to beginning.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.57

If not found, -1 is returned. Start is an optional argument specifying the position within string to
begin the search. Default is string.length-1. The syntax is:
lastIndexOf(substr, [start])

Here substr is a string or a character whose position will be searched in string str. For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Last index of a is: ", str1.lastIndexOf('a'));

which will produce Last index of a is: 18.


length. This function returns the length of a string. The String object only has one property
lengthwhich is read only. You use the length property to return the length of a string only: You
cannot change it externally. The syntax is:
str.length
Here str is a string whose length will returned. For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Length of string " + str1 + " is " + + str1.length + <br>");
var ln = "Multimedia is a designer course".length;
which will produce the result as:
Length of string CBSE Multimedia Class - XI is 26
String length: 31
Here, the result of this code is 31, because the spaces between the words are also counted as a
character.
substr(). This function returns the characters in a string beginning at start and through the
specified number of characters, length. Length is optional, and if omitted, up to the end of the
string is assumed. The syntax is:
str.substr(from, to)

For example,
var str1 = "CBSE Multimedia Class - XI";
var nStr = str1.substr(0, 15);
document.write("Substring is: " + nStr);
which will produce the result as:
Substring is: CBSE Multimedia

substring(). This function returns the characters in a string between from and to indexes, NOT
including to itself. To is optional, and if omitted, up to the end of the string is assumed. The syntax
is:
str.substring(from, to)
For example,
var str1 = "CBSE Multimedia Class - XI";
var nStr = str1.substring(0);
document.write("Substring is: " + nStr);
which will produce the result as:
Substring is: CBSE Multimedia Class - XI
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.58 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

toLowerCase(). This method is used to generate a new string with lowercase letters. The method
returns a new string containing the converted string and the original string is unchanged. The syntax
is:
str.toLowerCase()
For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Lowercase string is: " + str1.toLowerCase() + "<br>");
document.write("Original string is: " + str1);

which will produce the result as:


Lowercase string is: cbse multimedia class - xi
Original string is: CBSE Multimedia Class - XI

toUpperCase(). This method is used to generate a new string with uppercase letters. Like
toLowerCase() method, toUpperCase() also returns a new string containing the converted string
and the original string is unchanged. The syntax is:
str.toLowerCase()
For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Uppercase string is: " + str1.toUpperCase() + "<br>");
document.write("Original string is: " + str1);
which will produce the result as:
Uppercase string is: CBSE MULTIMEDIA CLASS - XI
Original string is: CBSE Multimedia Class - XI
toString(). This method is used to convert a number to string. The syntax is:
str.toString()
For example,
<SCRIPT type="text/javascript">
var Num = 100;
document.write("Number is: " + Num + "<br>");
var Sum = Num + 10;
document.write("Sum is: " + Sum + "<br>");
var str1 = Num.toString(); // Converting number to string
document.write("Number with string is: " + str1 + "<br>");
var str2 = str1 + 100;
document.write("New string is: " + str2);
</script>
which will produce the result as:
Original string is: CBSE Multimedia Class - XI
Number is: 100
Sum is: 110
Number with string is: 100
New string is: 100100
From the above output, the list line displays,
New string is: 100100
because the line, var str2 = str1 + 100; concatenates str1 value 100 with another number 100.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.59

valueOf(). This method returns the primitive value of an object. These objects are:

x Null: The value null.


x Undefined: The value undefined.
x Number: All numbers, such as 0 and 3.14. Also NaN, and Infinity.
x Boolean: The values true and false.
x String: All strings, such as "master" and "".
The syntax is:
str.valueOf()

For example,
<SCRIPT type="text/javascript">
var str1 = "CBSE";
document.write("Value of str1: " + str1.valueOf() + "<br>");
var Num = 100;
document.write("Value of Num: " + Num.valueOf() + "<br>");
var Flag = true;
document.write("Value of Flag: " + Flag.valueOf() + "<br>");
</script>

which will produce the result as:


Number is: 100
Value of str1: CBSE
Value of Num: 100
Value of Flag: true

3RLQWVWR5HPHPEHU

1. A function is a block of code that will be executed when "someone" calls it.
2. A function which does not accept any values must have the name of the function followed by an
empty set of parentheses.
3. The parameters to a function behave like regular variables, but their initial values are given by
the caller of the function, not the code in the function itself.
4. A variable declared inside a function is local to that method and cannot be used outside it.
5. Variables that are declared inside an opening curly brace and a terminating curly brace are
termed as local variables.
6. A global variable is visible to all functions and is declared outside all functions.
7. The variables (or parameters), which accept the actual variables inside the function are called
formal variables.
8. The variables, which are associated with function name during function call, are called actual
variables.
9. Functions are invoked in a program by writing the name of the function followed by the arguments
of the method in parenthesis.
10. The argument of a method may be a constant, a variable or an expression.
11. Local variables, or variables declared within a function, are deleted when the function is completed.
12. Global variables, variables declared outside of a function, are deleted when you close the page.
13. In JavaScript, the lifetime of a variable starts when the variable is declared.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.60 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

SOLVED EXERCISES
1. What is a function?
Ans. A set of operations which is part of a program and can be executed independently is called a function.
2. What are the types of functions?
Ans. Functions are of two types. These are : user-defined and built-in.
3. What is a user-defined function?
Ans. This function which is written by the programmer according to its need is known as user-defined
function.
4. How many times can function be called?
Ans. Many times.
5. What are function arguments?
Ans. Arguments of a function is the data that the function receives when called from another function.
6. What is a local variable?
Ans. Variables that are declared inside an opening curly brace and a terminating curly brace are termed as local
variables.
7. What is a global variable?
Ans. Global variables are the variables that are known throughout the program and may be used by any part
of the program. They hold their value throughout the execution of the program.
8. What is formal variable?
Ans. Formal variables are listed of variables that will accept different types of values being supplied to the
function by the calling program. Formal parameters are declared after the function name and inside
parentheses.
9. What is an actual variable? How is it different from an actual argument list?
Ans. The variables which are associated with function name during function call are called actual variables.
When the program calls the function, an argument list is also passed to the function. This list is called
the actual argument list.
10. Explain the difference between an actual parameter and a formal parameter.
Ans. An actual parameter is the value or variable sent to a method when it is invoked. A formal parameter is the
corresponding variable in the definition of the method; it takes on the value of the actual parameter so
that it can be used inside the method.
11. Are objects passed by value or by reference?
Ans. JavaScript supports only pass by value. With objects, the object reference itself is passed by value and
so both the original reference and parameter copy refer to the same object.
12. What will be the output of the following two line code?
document.write(Math.round(2.3)+ "" + "<br>");
document.write(Math.pow(2, 3)+ "");
Ans. The output is:
2
8
13. What content do the following lines display in an web browser?
var Message = "A11 The Best";
document.write((Message.length - 6));
Ans. The content is: 6
14. Write an equivalent JavaScript statement for the given expression:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.61

Ans. The equivalent JavaScript statement is: var a = (0.05 2 * y * y) / (x y);


15. For each of the following, write a single statement that performs the indicated task.
(a) Append the string Str1 to the string Str2 using +=.
(b) Determine the length of the string in Str1.
Ans. (a) Str1 += Str2;
(b) Str1.length
16. Write a JavaScript statement or a set of JavaScript statements to accomplish the following:
Calculate the value of 2.5 raised to the power of 3 using the pow method.
Ans. The JavaScript statement is: document.write(""+ Math.pow(2.5, 3));
17. What will be the output of the following code segment?
document.write("Exploring".concat("Java"));
Ans. The output is: ExploringJava
18. What will be the value X1 after execution of the following code:
var x1="Spread", x2="PEACE";
x1 = x2.concat(x1);
Ans. The value of x1 is PEACESpread
19. What will be the output that the following lines will be displayed in an web browser.
var s = "Sun Micro Systems";
document.write(s.length + " ");
document.write(s.toLowerCase());
Ans. The output is: 17 sun micro systems
20. Give the output of the following program:
<SCRIPT type="text/javascript">
var i = 4, j;
j = 10;
square(i, j);
document.write(i);
document.write(j);
function square(i, j)
{
i = i * j;
j = j * j;
}
</script>
Ans. The output is (outputc.html): 410
21. Give the output of the following program:
<SCRIPT type="text/javascript">
function areaX(a)
{
return (a*a);
}
function areaY(l, b)
{
return (l*b);
}
var x, y;
x = areaX(4);
y = areaY(5, 6);
document.write("The area of a square is: " + x + "<br>");
document.write("The area of a rectangle is: " + y);
</script>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.62 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Ans. The output is (outputd.html): :


The area of a square is: 16
The area of a rectangle is: 30
22. Give the output of the following code:
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function display(text, str)
{
document.write("<"+text+">")
document.write(str)
document.write("</"+ text +">")
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
display("H1", "Welcome")
display("P", "Hello! How are you?")
</SCRIPT>
</BODY>
</HTML>
Ans. The output is given in the following figure: (jfun05.html)

23. Write a simple function to display your name with Hello <name>.
Ans. The function is:
<html>
<body>
<SCRIPT type="text/javascript">
function Hello(sName)
{
document.write("")
document.write("Hello " + sName)
}
Hello("Kumar")
</script>
</body>
</html>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.63

24. Create a JavaScript function to add two parameterized numbers. Note that the two numbers will be
received as parameter to function.
Ans. The function is:
<script type="text/JavaScript">
function sum(number1, number2) {
var sum = number1 + number2
return sum
}
var total = sum(100,9)
document.write("Total is: " + total)
</script>
25. Write a JavaScript function to convert the temperature value from Celsius to Fahrenheit. Assume
that the temperature value is 100.
Ans. Write the following code in Notepad editor and save as fun06.html.
<HTML>
<HEAD>
<TITLE>JavaScript Function</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function convert(c_temp) // Return var and parameter are both float
{
var f_temp;
f_temp = c_temp * (9.0 / 5.0) + 32.0;
return (f_temp);
}
var c_temp = 100;
var f_temp = convert(c_temp); // Convert the temperature
document.write("The Fahrenheit value is : " + f_temp);
</script>
</BODY>
</HTML>

REVIEW QUESTIONS
1. What is a user-defined function?
2. What role do the arguments play in a function?
3. How will you call a function?
4. Name the statement that sends back a value from a function.
5. How many values can be returned by a function?
6. When is the execution of the function terminated?
7. Summarise the rules that must be followed during function call.
8. Give the output of the following program:
<SCRIPT type="text/javascript">
function display()
{
document.write(" program.");
}
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.64 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

document.write("This is a JavaScript ");


display();
</script>
9. In the following function declaration, where does the value for number come from?
function add_to(number) {
10. Whats wrong with the following JavaScript?
<SCRIPT type="text/javascript">
<!--
document.write("Hi!")
-->
</SCRIPT>
11. Give the output of the following program:
<SCRIPT type="text/javascript">
var convert = "100 + 120";
var newVal = 0;
convert = eval(convert);
newVal = convert + 100;
document.write("The converted value is : " + convert + "<br>");
document.write("The new value is : " + newVal);
</script>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.65

Branching in JavaScript
3
3.1 INTRODUCTION
Conditional statements allow you to control the flow of execution of a script or one of its sections. The flow of
activity through the program code is called the flow of control. In computer programming, there are three main
types of control flows that occur. These are:

Sequential. The statements execute from top to bottom sequentially.


Conditional or selection. Out of two instructions, only one will be executed successfully depending
on the condition. Because the condition produces a result as either True or False.
Repetition or loop. The instruction(s) are repeated over a whole list whenever the condition is
True.
Figure 3.1 shows the three types of control flow is a computer program.
`

if condition if condition
Statement 1
`
is false is true
condition
conditional code
`
`

Statement 2 condition
if condition
`

else code conditional is true


`

code
`

Statement 3
if condition
is false

Figure 3.1 Three main types of flow in a computer program.

In this chapter, we will discuss about the conditional or brancking statements.

3.2 CONDITIONAL CONTROL


Conditional control statements are also called branching or selection statements which execute one group of
instructions depending on the outcome of a decision. VBScript supports two control statements: IF and
SELECT CASE. In this category, VBScript programming language provides following types of decision making
statements as given in Table 3.1.
3.65
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.66 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

123456789012345678901234567890121234567890123456789012345
Table 3.1 Decision making statements.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Statement Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
if statement An if statement consists of a Boolean expression followed by one or more
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
statements.
123456789012345678901234567890121234567890123456789012345
if...else statement
123456789012345678901234567890121234567890123456789012345
An if statement can be followed by an optional else statement, which executes
123456789012345678901234567890121234567890123456789012345
when the Boolean expression is false.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
nested if statement You can use one if or else if statement inside another if or else if statement(s).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
switch statement The switch statement is a multiway branching statement.

3.2.1 If Statement (Selection)


In JavaScript, the simplest statement you can use to make a decision is the if ... end If statement. This
statement is a fundamental control statement. The syntax is:
if (Condition)
JavaScript Statement(s)
End If

`
Here, if condition
is true
x Condition is a Boolean expression. condition
x The Condition includes any relational comparison
and must be enclosed within parentheses.
x If the Condition is true, then the statement is

`
executed. If the Condition is false , then the conditional code
if condition
statement is bypassed.
is false
x The statement(s) of the if, sometimes called the body
of the if statement, is usually indented a few spaces `
for readability.
`

Figure 3.2 illustrates the if condition.


Figure 3.2 if conditional flowchart.

For example, suppose you have declared a variable named MyPer and you want to print a message
Grade A when the value of MyPer is greater than and equal to 80. The JavaScript code for if ... endif
condition is:
var MyPer
MyPer = 91;
if (MyPer >= 80)
document.write("Grade A")
endif

For example, type the following JavaScript code in Notepad window:


<html>
<head>
<title>if endif example</title>
</head>
<body>
<script type="text/JavaScript">
var a, b;
a = 10;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.67

b = 20;
document.write("Value of a is " + a + "<br>");
document.write("Value of b is " + b + "<br>");
if (a < b)
document.write("A is less than B");
endif
</script>
</body>
</html>

Save the file with ...\Unit 3\Chapter 2\ifendif.html and preview it in the browser as shown in Figure
3.3.

Figure 3.3 if ... endif result in browser window.

Although the (simple) if statement is used to check one condition, it can lead to executing multiple
dependent statements. If that is the case, enclose the group of statements between an opening curly bracket
{ and a closing curly bracket }.
float MyPer = 91;
if ( MyPer >= 80 )
{
document.write("My roll no. is 100 <br>");
document.write("Grade A");
}

The above code of if condition has two statements which are enclosed within curly ({ }) braces. This is
called a block. If the value in MyPer is greater than or equal to 80, the line of code in the block executes next.
Otherwise, JavaScript skips the entire block and continues with the program.
The if statement executes a number of operators. These are listed in Table 3.2.
123456789012345678901234567
123456789012345678901234567
Table 3.2 JavaScript equality and relational operators.
123456789012345678901234567
123456789012345678901234567
Operator Meaning
123456789012345678901234567
123456789012345678901234567
== equal to
123456789012345678901234567
123456789012345678901234567
!= not equal to
123456789012345678901234567
< less than
123456789012345678901234567
123456789012345678901234567
<= less than or equal to
123456789012345678901234567
123456789012345678901234567
> greater than
123456789012345678901234567
>= greater than or equal to

The condition includes any relational comparison and must be enclosed within parentheses. If the value of
the condition is non-zero, then the body of if gets executed. The block of one or more JavaScript statements
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.68 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

can be any legal JavaScript statement, such as an assignment or the document.write(" " + var) statement,
enclosed within braces or any operation. Some of valid if statements are:
x if (a > 0)
document.write(" " + a + " is a positive number");
x if (a) // Same as : if (a != 0)
document.write(" " + a + " is a non-zero number ");
x if (guess == num)
document.write("You guessed the right number ");
x if (a <= b)
document.write(" " + a + " is greater than " + b);
x if ((a < b) && (b > c))
document.write(" " + a + " < " + b + " < " + c);
x if ((a % b == 0) && (b != 0))
document.write(" " + (b + " is a divisor of " + a);
x if ((ch >= 0) && (ch <= 9)) // if ch is in between ASCII 0 and 9
document.write(" " + ch);

Example Write the JavaScript code for a web application to using HTML code to know whether you
are a minor or not. The application should enter your age and display the message:
"You are a minor. Your age not more than 18."

If age is less than 18.


Solution The code is (ifage.html):
<HTML>
<HEAD>
<TITLE>JavaScript if condition Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Using if conditional statement
var myAge = prompt("Enter your age ?");
if (myAge <= 18)
{
alert("You are a minor. Your age not more than 18.");
}
document.write("Thanks!");
</script>
</BODY>
</HTML>

Example Write the JavaScript code to compare two numbers and print the numbers with their
comparison result.
Solution The code is (ifendif.html):
<html>
<head>
<title>if endif example</title>
</head>
<body>
<script type="text/JavaScript">
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.69

var a, b;
a = 10;
b = 20;
document.write("Value of a is " + a + "<br>");
document.write("Value of b is " + b + "<br>");
if (a < b)
document.write("a is less than b");
endif
</script>
</body>
</html>

3.2.2 if-else Statement


The if...else statement can be extended to have statements that are executed when the condition is false. The
if...else statement executes the first set of statements if the condition is true, otherwise the second set of
statements is executed. The syntax is:
if (Condition) {

`
Statements;
} if condition
else { condition
is true
Statements;
}

The flow of control with an if...else statement looks if condition

`
like Figure 3.4; one of two paths of action is taken, is false
conditional code
depending on the condition.
`

If the Condition is true, the entire block of statements else code


following the if is performed. If the Condition is false,
the entire block of statements following the else is `
performed.
`

Figure 3.4 if ... else selection structure.


For example, suppose you have declared a floating-point variable named MyPer and you want to print a
message Grade A when the value of MyPer is greater than and equal to 80, otherwise print a message You
have a different grade. The JavaScript code for if condition is:
var MyPer = 91;
if ( MyPer >= 80 )
{
document.write("My roll no. is 100 <br>");
document.write("Grade A");
}
else
document.write("You have a different grade");

Some of the valid if-else statements are:


x if (a > b)
document.write(" " + a + " is greater than " + b);
else
document.write(" " + b + " is greater than " + a);
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.70 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

x if ((ch >= 'a') && (ch <= 'z'))


document.write(" " + ch + " is a lowercase letter");
else
document.write(" " + ch + " is not a lowercase letter");
x if ((ch >= 'a') && (ch <= 'z')) ((ch >= 'A') && (ch <= 'Z'))
document.write(" " + ch + " is an alphabet");
else
document.write(" " + ch + " is not an alphabet");
x if ((sex == 'M') || (sex == 'm'))
document.write("You are a male");
else
document.write("You are a female");
x if ((divisor != 0) && (num % divisor))
document.write(" " + num + " is not divisible by " + divisor);
else
document.write(" " + num + " is divisible by " + divisor);
For example, type the following JavaScript code in Notepad window:
<html>
<body>
<SCRIPT type="text/javascript">
function greeting()
{
var CDate = new Date();
CHour = CDate.getHours() // Current hour of System
if (CHour < 10)
document.write("Good morning!")
else
document.write("Have a nice day!")
endIf
}
</script>
</head>
<body onload="greeting()">
</body>
</html>

Save the file with ...\Unit 3\Chapter 3\chour.html and see the preview of the page in a browser.
Example Simran Kaushik developed web application using JavaScript to convert temperature from
Fahrenheit to Celsius and vice versa. The resulted web page is shown below:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.71

To satisfy the page, enter the degree to the Textbox and select option from combobox
(Celsius or Fahrenheit) and then calculate the temperature from Fahrenheit to Celsius and
vice versa using JavaScript code.
Solution Write the following code in Notepad editor and save as convert.html.
<html>
<head>
<title>Temperature in Fahrenheit</title>
</head>
<script type="text/javascript">
function Convert_Temp()
{
var opt = frm.myoption.value;
if(opt == "Fahrenheit")
{
var val = frm.txt.value;
if (isNaN(val))
{
alert("Not a Number");
}
else {
var tf=parseInt(val);
var tc= (tf - 32) * (5/9);
var res1 = Math.round(tf * 100)/100;
frm.txt1.value = res1+" C";
}
}
else
{
var val=frm.txt.value;
if (isNaN(val))
{
alert("Not a Number");
}
else {
var tc=parseInt(val);
var tf=(tc * (9/5)) + 32;
var res1 = Math.round(tf * 100)/100;
frm.txt1.value=res1+" F";
}
}
}
</script>
<form name="frm">
<TABLE cellPadding=2 width="70%" border=1 color="BLUE">
<tr>
<td>Enter the degree</td>
<td><input type=text name="txt" size="12"></td>
<td><select name="myoption">
<option name="Faren" value="Fahrenheit">Farenheit</option>
<option name="Cels" value="Celsius">Celsius</option>
</select></td>
<td><input type="button" value="Calculate" onclick="Convert_Temp()">
</td></tr>
<tr><td>Equal Value</td>
<td><input type=text name="txt1" size="12" READONLY>
</td><td></td>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.72 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

</table>
</form>
</html>

3.2.3 Nested if

Nested if/else structures test for multiple causes by placing if/else selection structure inside if/else selection
structure. The if/else selection structure uses the condition till three levels. This is very useful to test various
conditions using single if...else if statement. The syntax is:
If (Condition-1) {
Statements which will be executed if Condition-1 is true
}
else if (Condition-2) {
Statements which will be executed if Condition-2 is true
}
.
.
else if (Condition-n) {
Statements which will be executed if Condition-n is true
}
else {
Statements which will be executed if none of the conditions is true
}

As you can see in this if else if ladder, conditions are evaluated from top. First Condition-1 will be
evaluated and if this is true, the code inside the if block will be executed. If Condition-1 is false, Condition-
2 will be evaluated. If Condition-2 is true, the code inside that else if block will be executed. If Condition-
2 is false, Condition-3 will be evaluated. This will go on like this. If none of the conditions are true, the code
inside the else block will be executed.
Some of the valid nested if statements are:
x <script language = "JavaScript">
var average = 88;
if (average > 80)
document.write("Grade is A");
else if (average > 70)
document.write("Grade is B");
else if (average > 60)
document.write("Grade is C");
else if (average > 50)
document.write("Grade is D");
else if (average > 40)
document.write("Grade is E");
else
document.write("Grade is F");

x if (Temperature > 35)


document.write("It is too hot today")
else if (Temperature > 25 && Temperature <= 35):
document.write("It is warm today")
else
document.write("It is cooler today")
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.73

You can add as many else if clauses as you need to provide alternative choices. For example, type the
following JavaScript code in Notepad window:
<html>
<head>
<title>Nested if example</title>
<SCRIPT type="text/javascript">
function greeting()
{
var CDate = new Date();
CHour = CDate.getHours() // Current hour of System
if (CHour < 10) {
document.write("Just started...!")
}
else if (CHour < 11) {
document.write("Hungry!")
}
else if (CHour < 12) {
document.write("Ah, lunch-time!")
}
else if (CHour < 16) {
document.write("It is very hot!")
}
else {
document.write("It time to go home")
}
}
</script>
</head>
<body onload="greeting()">
</body>
</html>

Save the file with ...\Unit 3\Chapter 3\nestif.html and preview it in the browser as shown in Figure
3.5.

Figure 3.5 Nested if result in browser window.


Example Write a JavaScript program to find the greatest among three numbers. Display the greater
number with appropriate message. For example, if you have three numbers like this:
var num1 = 340;
var num2 = 420;
var num3 = 611;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.74 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

The web browser will display the following screen:

Solution Write the following code in Notepad editor and save as greatest.html.
<HTML>
<HEAD>
<TITLE>JavaScript Nested if-else condition Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Print greatest among three numbers
var num1 = 340;
var num2 = 420;
var num3 = 611;
if ((num1 > num2) && (num1 > num3))
{
document.write("The bigger value is : " + num1);
}
else
if ((num2 > num1) && (num2 > num3))
{
document.write("The bigger value is : " + num2);
}
else
document.write("The bigger value is : " + num3);
</script>
</BODY>
</HTML>

3.2.4 The switch...case Statement

The statement is a multiway branch statement. It provides an easy way to dispatch execution to different
parts of your code based on the value of an expression. The syntax for the switch statement is:
switch (expression)
{
case (value1):
// Java statements;
break;
case (value2):
// Java statements;
break;
:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.75

case (value3):
// Java statements;
break;
:
default:
// Java statements;
}

Here,
x The expression must be of integer, or character type and each of the values specified in the case
statements must be of a type compatible with the expression.
x The value1, value2, value3, etc. can be any other int or char constant.
x If the expression matches the first case, value1, the statements, that are usually under value1, execute.
If the expression matches the second case, value2, the statements that are usually under value2
execute. If none of the case expressions matches that of the switch expression, the default case
block executes.
x A break statement in switch causes control to skip all the statements after it and jumps to the next
statement just after the switch block.
x There is no need to use break statement in default case, because default is the last case and so
the switch has to terminate after it.
x In a switch structure when the default clause is listed last, the break statement is not required.
x The default line is optional.
The examples of switch statements are:
x var grade = prompt("Enter your grade").toUpperCase();
switch (grade)
{
case 'A' : document.write("Secure more than 80%");
break;
case 'B' : document.write("Secure more than 70% and less than 80");
break;
case 'C' : document.write("Secure more than 60% and less than 70");
break;
case 'D' : document.write("Secure more than 50% and less than 60");
break;
default : document.write("Secure more than 50% and less than 60");
}

x var opt = prompt("Enter valur for opt").toUpperCase();


switch (opt)
{
case 'R' : document.write("Rainy season");
break;
case 'S' : document.write("Summer season");
break;
case 'W' : document.write("Winter season");
break;
case 'P' : document.write("Spring season");
break;
case 'A' : document.write("Autumn season");
}
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.76 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

For example, to check for vowel characters, spaces and consonants, the switch structure is:
var ch = prompt("Enter your choice");
var vowels, spaces, consonants;
switch (ch)
{
case 'A' :
case 'a' :
case 'E' :
case 'e' :
case 'I' :
case 'i' :
case 'O' :
case 'o' :
case 'U' :
case 'u' : vowels++;
break;
case ' ' :
spaces++;
break;
default : consonants++;
break;
}

The switch statement can be used to combine cases and executed as one. To do this, you can type two or
more cases together.
In the above example, if the value of letter is either A, a, E, e, I, i, O, o, U or u then number of
vowels is incremented. If the value of letter is , then number of spaces is incremented. If none of these is true
then the default condition is executed, that is, the number of consonants is incremented.
<script type="text/javascript">
d=weekday(date)
Select Case d
Case 1
document.write("Sleepy Sunday")
Case 2
document.write("Monday again!")
Case 3
document.write("Just Tuesday!")
Case 4
document.write("Wednesday!")
Case 5
document.write("Thursday...")
Case 6
document.write("Finally Friday!")
Case else
document.write("Super Saturday!!!!")
End Select
</script>
</body>
</html>

Example Write the JavaScript code to enter the month number and display respective month name
and days.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.77

Solution Write the following code in Notepad editor and save as days.html.
<HTML>
<HEAD>
<title>switch...case example</title>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Variable hold the month number.
var mon = parseInt(prompt("Enter month no. (1-12): "));
var day = 0; // Month days
var cmonth;
switch (mon) {
case 1: day = 31;
cmonth = "January";
break;
case 2: day = 28;
cmonth = "February";
break;
case 3: day = 31;
cmonth = "March";
break;
case 4: day = 30;
cmonth = "April";
break;
case 5: day = 31;
cmonth = "May";
break;
case 6: day = 30;
cmonth = "June";
break;
case 7: day = 31;
cmonth = "July";
break;
case 8: day = 31;
cmonth = "August";
break;
case 9: day = 30;
cmonth = "September";
break;
case 10: day = 31;
cmonth = "October";
break;
case 11: day = 30;
cmonth = "November";
break;
case 12: day = 31;
cmonth = "December";
break;
default: cmonth = "Invalid input";
}
document.write("Your choice is: " + mon + " Month: " + cmonth + " and " + day + "
days" );
</script>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.78 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Save the file with ...\Unit 3\Chapter 3\days.html and preview it in the browser. If you enter the
month no. as 7, then it will display the details of month no. 7 as shown in Figure 3.6.

Figure 3.6 switch ... case result in browser window.

3RLQWVWR5HPHPEHU

1. An if statement allows a program to choose whether or not to execute a statement.


2. An if-else statement allows a program to do one thing if a condition is true and a different thing
if the condition is false.
3. If you omit the curly brackets in if condition, only the statement that immediately follows the
condition would be executed.
4. A switch statement can be implemented as a series of if-then statement.
5. An empty statement indicates that no action is to be repeated while some condition remains
true.
6. The switch statement handles a series of decisions in which a particular variable or expression
is tested for values it may assume and different actions are taken.
7. In most programs, it is necessary to include a break statement after the statements for each
case.
8. Several cases can execute the same statements by listing the case labels together before the
statements.
9. The switch structure can only test for constant integral expressions.

SOLVED EXERCISES
1. What is a Boolean variable?
Ans. A variable is referred to as Boolean if it can hold a value that is either true or false.
2. What is a block?
Ans. A block is the simplest type of structured statement. Its purpose is simply to group a sequence of
statements into a single statement. The format of a block is:
{
statements
}
That is, it consists of a sequence of statements enclosed between a pair of braces, { and }.
3. What is an if statement? Give its syntax.
Ans. An if statement tells the computer to take one of the two alternative courses of action, depending on
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.79

whether the value of a given Boolean-valued expression is true or false. It is an example of a branching
or decision statement. if statement has the form:
if (Boolean-expression)
statement;
else
statement;
4. How can the switch statement be replaced with a series of if-else statements?
Ans. A switch statement can always be rewritten as a series of if-else statements by creating an if condition
for each case value in the switch. The statements associated with each case value are executed in the
appropriate if statement. It is very difficult to rewrite a switch statement that does not use a break
statement at the end of each case.
5 What is the purpose of default clause in a switch statement?
Ans. Default clause is used to handle the case when no match of any case in the switch statement is found.
6. What is the purpose of break statement in a loop?
Ans. Break statement is used to terminate the loop.
7. What is the purpose of break keyword while using Switch Case Statement ? Illustrate with the help of
an example.
Ans.. A break statement in switch causes control to skip all the statements after it and jump to the next
statement just after the switch block. For example:
switch (opt)
{
case 1: document.write("I am in case 1");
break;
case 2: document.write("I am in case 2");
break;
case 3: document.write("I am in case 3");
break;
default:
document.write("\nInvalid option selected");
}
8. The following is a segment of program.
var x = 1, y = 1;
if (n > 0) {
x = x + 1;
y = y 1;
}
What will be the value of x and y, if n assumes a value
(i) 1
(ii) 0?
Ans. (i) If n = 1, then x = 2 and y = 0
(ii) if n =0, then x = 1 and y = 1
9. Find the error in each of the following code segments and explain how to correct it.
switch (ctr) {
case 1:
document.write("The number is 1");
case 2:
document.write("The number is 2");
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.80 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

break;
default:
document.write("The number is not 1 or 2");
break;
}
Ans. Error: Missing break statement in the statements for the first case.
Correction: Add a break statement at the end of the statements for the first case. Note that this is not
necessarily an error if you want the statement of case 2: to execute every time the case1: statement
executes.
10. Give the output of the following code fragment:
when (i) opn = b (ii) opn = x (iii) opn = a
switch (opn) {
case 'a':
document.write("Platform Independent");
break;
case 'b':
document.write("Object Oriented");
case 'c':
document.write("Robust and Secure");
break;
default:
document.write("Wrong Input");
}
Ans. The output is:
(i) Object Oriented
Robust and Secure
(ii) Wrong Input
(iii) Platform Independent.
11. What will be the corresponding output of the following code segment if the Num value is 30.
switch(Num) {
case 10: document.write("Ten only"); break;
case 20: document.write("Twenty only");
case 30: document.write("Thirty only");
case 40: document.write("Forty only"); break;
default: document.write("Not enough money"); break;
}
Ans. The output is: ThirtyonlyForty only.
12. Write JavaScript statements to accomplish the following:
Test if the value of variable ctr is greater than 10. If it is, display Ctr is greater than 10.
Ans. The statement is:
if (ctr > 10)
document.write("Ctr is greater than 10");
13. Convert the following code segment using switch-case construct:
var num = parseInt(prompt('Enter any number'));
var txtRes;
if (num>=2 && num<=5)
txtRes = "Prime";
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.81

else if(num==6 || num==8 || num==10)


txtRes = "Even";
else
txtRes = "Not Valid";
Ans. The switch-case construct is:
int num = Integer.parseInt(txtNum.getText());
switch(num) {
case 2:
case 3:
case 4:
case 5:
txtRes = "Prime";
break;
case 6:
case 8:
case 10:
txtRes = "Even";
break;
default:
txtRes = "Not Valid";
}
14. While working in JavaScript, Ms Kanta Surbhi wants to display cleared or Re-attempt required
message depending on the marks entered. Help her to choose more appropriate statement out of if
statement and Switch statement.
Ans. if statement.
15. Rewrite the following program code using a Switch statement.
if (code == 1)
Day = "Monday";
else if (code == 2)
Day = "Tuesday";
else if (code == 3)
Day = "Wednesday";
else if (code == 4)
Day = "Thursday";
else
Day = "No Match";
Ans. The code using a Switch statement is:
var code = parseInt(prompt('Enter code'));
var Day;
switch (code) {
case 1:
Day = "Monday"; break;
case 2:
Day = "Tuesday"; break;
case 3:
Day = "Wednesday"; break;
case 4:
Day = "Thursday"; break;
default:
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.82 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Day = "No Match";


}
16. Rewrite the following program code using an if statement.
var C = parseInt(prompt('Enter choice'));
switch (C) {
case 0 : Amount=Bill; break;
case 1 : Amount=0.9*Bill; break;
case 2 : Amount=0.8*Bill; break ;
default : Amount=Bill;
}
Ans. Code using if statement is:
var C = parseInt(prompt('Enter choice'));
if (C == 0)
Amount=Bill ;
else
if (C == 1)
Amount=0.9*Bill ;
else
if (C == 2)
Amount=0.8*Bill ;
else
Amount=Bill ;
17. Rewrite the following program code using switch statement:
if (d == 1)
day = "Monday";
else if (d == 2)
day = "Tuesday";
else if (d == 3)
day = "Wednesday";
else day = "-";
Ans. The switch statement is:
switch (d) {
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
default:
day = "-";
}
18. Write the output of the following program:
<SCRIPT type="text/javascript">
function Execute(B)
{
var C = 100;
var TEMP = B + C;
B += TEMP;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.83

if(C != 200)
{
document.write(TEMP + " " + B + " " + C);
}
}
var M = 90;
Execute(M);
document.write(" " + M + "<br>");
M = 10;
Execute(M);
document.write(" " + M);
</script>
Ans. The output is (outpute.html):
190 280 100 90
110 120 100 10
19. Give the output of the following program:
<SCRIPT type="text/javascript">
function max(x, y)
{
if (x > y)
return(x);
else
return(y);
}
var A = 10, B = 13;
var fx = 0, sx = 0;
document.write("A = " + A + ", " + "B = " + B + "<br>");
fx = max(B, A)
document.write("Maximum is: " + fx);
</script>
Ans. The output is (outputf.html):
A = 10, B = 13
Maximum is: 13
20. Point the errors in the following code and write the correct script.
<SCRIPT type="text/javascript">
var A = 10;
var B = 6;
switch (A%B)
{
case 0;
document.write("The input is :")
break;
case 1:
document.write("The color is :")
break;
else
document.write("You didnt choose")
}
</SCRIPT>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.84 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Ans. The errors are:


<SCRIPT type="text/javascript">
var A = 10;
var B = 6;
switch (A%B)
{
case 0; // Error 1
document.write("The input is :")
break;
case 1:
document.write("The color is :")
break;
else // Error 2
document.write("You didnt choose")
}
</SCRIPT>
Where,
x Error 1. The case clause does not support semicolon, it should be colon (:).
x Error 2. else clause is not allowed with switch case construct, it should be default:.
The correct program is (outputg.html):
<SCRIPT type="text/javascript">
var A = 10;
var B = 6;
var c = A % B;
document.write(c)
switch (A%B)
{
case 0: // Correction 1
document.write("The input is :")
break;
case 1:
document.write("The color is :")
break;
case 4:
document.write("The color is :")
break;
default: // Correction 2
document.write("You didnt choose")
}
</SCRIPT>
21. Write a JavaScript program to enter a number and check whether it is positive, negative or zero.
Ans. The JavaScript program is (checknum.html):
<HTML>
<HEAD>
<TITLE>Number check</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var num = prompt("Enter number")
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.85

num = parseInt(num)
if (num > 0) {
alert(num + " is positive")
} else if (num < 0) {
alert(num + " is negative")
} else {
alert(num + " is zero")
}
</script>
</BODY>
</HTML>

REVIEW QUESTIONS
1. What is the difference between selection and repetition?
2. What is a block statement? How are block statements used in JavaScript programs?
3. What is the purpose of if statement? Describe the different forms of if statement.
4. Describe switch statement. What is the difference between if and switch statements?
5. What is the purpose of default clause in a switch statement?
6. Write the statements for the following situations:
(a) X is greater than equal to Y.
(b) X is not equal to Y.
(c) X is equal to Y.
(d) X is less than Y and X is less than Z.
(e) Either X is greater than Y or X is less than Z.
(f ) If X has a value greater than 20 then increment the value of the J by 1 otherwise decrement the value
by 2.
7. Using the JavaScript statement, answer the following :
(a) If statement to compare the value of an integer called sum against the value 65 and if it is less, print
the text string Sorry, try again.
(b) If total is equal to the variable good_guess, print the value of total, else print the value of good_guess
using if statement.
(c) If sum is equal to 10 and total is less than 20, print the text string incorrect. using if statement.
(d) If flag is 1 or letter is not an X, then assign the value 0 to exit_flag, else set exit_flag to 1.
if ((flag == 1) || (letter != X) )
exit_flag = 0;
else
exit_flag = 1;
8. Identify and correct the errors in each of the following. [Note: There may be more than one error in each
piece of code.]
If (yourAge >= 65);
document.write("Your age is greater than or equal to 65");
else
document.write("Your age is less than 65)";
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.86 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

9. Find the error for the following: [Note: There may be more than one error. The following code should
print whether integer nVal is odd or even:
switch (nVal %2) {
case 0:
document.write("Even integer");
case 1:
document.write("Odd integer");
}
10. What will be the output of the following program segment?
(a) var a = 3;
a = a + 1;
if (a > 5)
document.write("" + a.toString());
else
document.write("" + a.toString() + 5);
(b) What will be the corresponding outputs of the following code fragment if the input is:
(i) a (ii) c (iii) d (iv) h (v) b
var ch = prompt('Enter choice');
switch (ch)
{
case 'a' : document.write("It is a. <br>");
case 'b' : document.write("It is b. <br>");
case 'c' : document.write("It is c. <br>");
break;
case 'd' : document.write("It is d. <br>");
break;
default : document.write("Not a b c d. <br>");
}
11. Write equivalent switch statement for the following:
(a) if (code == 's')
document.write("season is summer ");
else
if (codee == 'r')
document.write("season is rainy");
else
if (code == 'w')
document.write("season is winter ");
else
document.write("wrong code");
(b) if (a == 1)
x++;
else
if (a == 2)
y++;
else
if (a == 3)
z++;
else
w++;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.87

12. Find the output of the following code:


(a) a = 1, b = 5; (b) int a = 3, b = 1;
b++; if (a > 0 || b < 5)
if (b == 5) if (a > 2)
document.write("value is five "); document.write("a > 2");
else else
document.write("value is not five"); document.write("a < 2");
(c) var a = 0; (d) char yesNo = 'N';
if (a == 1) { switch(yesNo) {
document.write("one"); case 'n': case 'N':
} else if (a == 2) { document.write("No selected");
document.write("two"); break;
} else if (a == 3) { case 'y': case 'Y':
document.write("three"); document.write("Yes selected");
} else { break;
document.write("invalid"); }
}
13. What is wrong with the following code fragment? Using braces and correct indentation, rewrite it so that
it produces correct output.
if (total == MAX)
if (total < sum)
document.write("total equals MAX and total is" + "less than sum");
else
document.write("total is not equal to MAX" );
14. Rewrite the following switch statement using if-else statements:
switch (number) {
case 1: document.write("digits"); break;
case 10: document.write("tens"); break;
case 100: document.write("hundreds"); break;
case 1000: document.write("thousands"); break;
case 10000: document.write("ten thousands"); break;
default: document.write("error");
}
15. An electronic shop has announced the following seasonal discounts on the purchase of certain items:

Purchase Amount (in `) Discount (%) on Laptop Discount (%) on Desktop PC

0 25,000 0.0 5.0


25,001 57,000 5.0 7.5
57,001 1,00,000 7.5 10.0
More than 1,00,000 10.0 15.0

Write a JavaScript program based on the above criteria, to input amount of purchase and the type of
purchase (Laptop or Desktop) by a customer. Compute and print the net amount to be paid by a
customer along with his name and address.
(Hint: discount = (discount rate / 100) * amount of purchase Net amount = amount of purchase
discount).
16. Write a JavaScript program that asks the user to enter two integers, obtains the numbers from the user
and displays the larger number followed by the words is larger in an alert message dialog. If the
numbers are equal, print the message These numbers are equal.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.88 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

17. Write a JavaScript program that reads an integer and determines and prints whether it is odd or even
(Hint. Use the modulus operator. As even number is a multiple of 2. Any multiple of 2 leaves a reminder
of zero when divided by 2.)
18. Write a JavaScript program that takes the number of seconds as input. The program converts this value
to the corresponding number of hours, minutes, and seconds and displays these values.
19. Write a JavaScript program that accepts the length and width of a rectangle as inputs. The program
should calculate the rectangles area and perimeter, and display the values rounded to the nearest length
of a foot.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.89

Looing in JavaScript
4
4.1 INTRODUCTION

Looping is also called as repetition structure. A repetition structure allows the programmer to perform an action
that to be repeated until the given condition is true. Figure 4.1 is the general form of a loop statement in most of
the programming languages.
JavaScript supports three types of looping statements:
x A while loop, in which the loop-controlling Boolean
expression is the first statement in the loop.
x A do-while loop, in which the loop-controlling `
Boolean expression is the last statement in the loop.
x A for loop, which is usually used as a concise format
in which to execute loops.
conditional code
In JavaScript, the above three loops are specifically `
`

designed to perform repetitive tasks with one set of code. Loops


save a lot of time. A loop is a structure that allows repeated
execution of a block of statements. Within a looping structure, condition
if condition
a condition called Boolean expression is evaluated. If it is true, is true
a block of statements called the loop body executes and the
Boolean expression is evaluated again. As long as the expression
`

is true, the statements in the loop body continue to execute. if condition


When the Boolean evaluation is false, the loop ends. is false

Figure 4.1 General form of a loop structure.

4.2 THE while LOOP


A while loop statement in JavaScript programming language repeatedly executes a target statement as long as
a given condition is true. The format of the while statement is:
while (Condition)
{
program statements;
}

3.89
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.90 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Here, while (Condition) {


statement(s)
x A while loop consists of the keyword while. }

`
x It contains a Condition called Boolean expression within
parentheses.
x The program statements are called the body of the loop, ` condition
if condition
which can be a single statement or a block of statements is false
surrounded by curly brackets.

`
if condition
Figure 4.2 shows the execution style of a while loop. is true

`
The while loop is also called the entry-controlled loop because
in this loop the condition is checked first and if that condition is true, conditional code
then the block of statement in the loop body will be executed.

`
Figure 4.2 while loop structure.

Example Write the JavaScript code to enter a number in a text box and display all the numbers for 1
to till that number using while loop.
Solution Write the following code in Notepad editor and save as number.html.
<HTML>
<html>
<head>
<title>Displaying natural numbers</title>
</head>
<SCRIPT type="text/javascript">
function Display_Numbers()
{
var number = frm.txt.value;
var ctr = 1;
document.write("Numbers are...<br>");
while( ctr <= number ) {
document.write(ctr + "<br>");
ctr++;
}
}
</script>
<form name="frm">
Enter a number: </td>
<input type=text name="txt" size="12"></td>
<input type="button" value="Display" onclick="Display_Numbers()">
</form>
</html>

Open the number.html file in IE, and see the output window as shown in Figure 4.3 on the next page.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.91

Figure 4.3 Natural numbers using while loop.

The while loop can accept expressions and not just conditions. The following are all legal expressions:
x while (x = x + 1)
x while (n)
x while (count += i)
For these types of expressions, when the result of x = x + 1, n or count += i, evaluates to 0, then only the
while condition will fail and the loop will exit. Some other examples of while loop are:
var num = 5;
while (num != 0)
{
document.write(num + "<br>");
num--;
}
This loop prints a num starting from 5 and going down to 1, until the num becomes 0 which is the
terminating condition of the loop.
while (i++ < n);
this loop counts i up to n.
var num = 5;
while (num)
{
document.write(num + "<br>");
num;
}
Here, the while (num) is same as saying while (num != 0).
Let us study a sample logic to find the factorial of a number using while loop (fact.html):
// Factorial function
function factorial(N)
{
var num = 1;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.92 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

var fact = 1;
while (num <= N)
{
fact = fact * num;
num++;
}
return (fact);
}
N = 10;
document.write("The factorial of 10 is " + factorial(N));

From the above factorial logic, the counter num increases till N and multiply with fact for finding the
factorial of N. When the above steps are executed it will find the factorial as:
The factorial of 10 is 3628800.0

4.3 THE do-while LOOP


This loop is similar to the while loop, except that with do-while, the relational test occurs at the bottom of the
loop. This ensures that the dowhile condition executes a Statement first. After the first execution of the
Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep
executing the Statement as long as the Condition is true. Once the
Condition becomes false, the looping (the execution of the Statement) do {
would stop. Thus, this loop is also called an exit-controlled loop. statement(s)
If the Statement is a short one, e.g., of one line, simply write it ` } while (Condition)
after the do keyword. Like if and while statements, the Condition
`

being checked must be included between parentheses. The whole


dowhile statement must end with a semicolon. Statements
The format of the do-while loop is:
`

do if condition
{ is true
condition
program statements;
} while (Condition);

This process is shown in Figure 4.4. if condition


is false
`

Figure 4.4 do-while loop structure.


Example Write the JavaScript code to display all the numbers in reverse order of its assignment. For
example, if you assign a number as N = 10, then it will print:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Solution Write the following code in Notepad editor and save as rnum.html.
<HTML>
<HEAD>
<TITLE>JavaScript do-while loop</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
N = 10
document.write("The reverse numbers are ");
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.93

do {
document.write(N + " ");
N--;
}while (N >= 1);
</script>
</BODY>
</HTML>

Open the rnum.html file in IE, and the see the output window as shown in Figure 4.5.

Figure 4.5 Reverse numbers do-while loop.


Some other examples of do-while loop are:
x var num = 5;
do {
// perform input/output operation
num;
} while (num != 0);
this loop performs operations num starting from 5 and going down to 1, until the num becomes 0
which is the terminating condition of the loop.
x do {
....
} while (i++ < n);
this loop counts i up to n.
x var num = 5;
do {
// perform input/output operation
num;
} while (num);

Here, the while (num) is same as saying while (num != 0).

4.4 THE for LOOP


A for loop is a special loop that is used when a definite number of loop
iterations is required. It is a counter controlled loop. The syntax of the N ote
for loop is as follows:
A for statement is usually used
for (<initialization>; <loop condition>; <expression>) when a loop will be executed a
<loop statements to be executed> set number of times.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.94 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

At its regular structure, it is divided into three parts:


x The starting/initializing value for the loop control variable.
` initialization
x The test condition that controls loop entry.
x

`
The expression that alters or updates the loop control variable.
Each part is separated with a semicolon (;). Figure 4.6 shows the execution
condition False
style of for loop. evaluated
For example:

Declaring and True

`
initializing loop Checking Incrementing loop
control variable condition control variable initialization

`
`
`

increment
for ( ctr = 1 ; ctr <= 10 ; ctr = ctr + 1 )

`
document.write(ctr + " ");
Figure 4.6 for loop
execution style.

From the above example, when you execute the for statement, you will see 10 natural numbers in jTextArea1
as given below:

1 2 3 4 5 6 7 8 9 10

The first part of the for statement is:

for (ctr = 1 ;

which initializes the value of ctr to 1. The for loop continues whilst the condition ctr <= 10 is evaluated as
true. As the variable ctr has just been initialized to 1, this condition is true and so the program statement:
document.write(ctr + " ");

is executed, which prints the value ctr to the screen, followed by a space character. Next, the remaining
statement of the for is executed:
ctr = ctr + 1;

which adds one to the current value of ctr. Control now passes back the conditional test:

ctr <= 10;

which evaluates as true and so the program statement:

document.write(ctr + " ");

is executed. ctr is incremented again, the condition is re-evaluated and this continues until ctr reaches a value
of 11. When this occurs, the conditional test:
ctr <= 10;

Eventually, when ctr is not less than or equal to 10, the for loop ends, and the program continues with any
statements that follow the for loop.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.95

As a final example, lets say that we want to use a for loop that prints out just the even numbers between
2 and 20, that is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. There are several ways to do this. Just to show how even a very
simple problem can be solved in many ways, here are four different solutions given below:
1. // There are 10 numbers to print.
// Use a for loop to count 1, 2, ..., 10. The numbers we want to print are:
// 2*1, 2*2, ... 2*10.
for (N = 1; N <= 10; N++)
{
document.write( 2*N + " " );
}

2. // Use a for loop that counts 2, 4, ..., 20 directly by adding 2 to N each


// time through the loop.
for (N = 2; N <= 20; N = N + 2)
{
document.write( N + " " );
}
3. // Count all the numbers 2, 3, 4, ..., 19, 20, but only print out the numbers that are even.
for (N = 2; N <= 20; N++)
{
if ( N % 2 == 0 ) // is N even?
document.write( N + " ");
}

4. // Irritate the professor with a solution that follows the letter of this silly
// assignment while making fun of it.
for (N = 1; N <= 1; N++)
{
document.write("2 4 6 8 10 12 14 16 18 20");
}

Example Write the JavaScript code using function to find the sum of first 10 natural numbers.
Solution Write the following code in Notepad editor and save as nsum.html.
<HTML>
<HEAD>
<TITLE>Sum of natural numbers</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var answer;
// Function to find the sum of natural numbers
function sum_number()
{
var result = 0; // hold the result
var N = 10, ctr;

for (ctr = 1; ctr <= N; ctr++)


{
result += ctr; // add the integer into the sum
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.96 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

} // end of the for loop


return (result); // returning a value from function
}
answer = sum_number(); // returned result in answer
document.write("Sum of first 10 number is : " + answer);
</script>
</BODY>
</HTML>

Open the nsum.html file in IE, and the see the output window as shown in Figure 4.7

Figue 4.7 sum of 10 natural numbers.


Example Write a JavaScript program to print the mathematical table 20.
Solution Write the following code in Notepad editor and save as mtable.html.
<HTML>
<HEAD>
<TITLE>Mathematical Table</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var num = 20;
var tab = 0;
document.write("The mathematical table of " + num + "<br>");
document.write("" + "<br>");
for (var count = 1; count <= 10; count++)
{
tab = num * count;
document.write(num + " * " + count + " = " + tab);
document.write("<br>"); // Print a break to separate lines
}
</script>
</BODY>
</HTML>

Open the mtable.html file in IE, and the see the output window as shown in Figure 4.8 on the next page.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.97

Figue 4.8 Mathematical table of a number.

4.5 THE LOOP CONTROL STATEMENTS

JavaScript provides three branching statements break, continue and return. In this section we will learn break,
continue and uses of label with break and continue. The return statement will be discussed in the next chapter.

7KHEUHDN6WDWHPHQW

The break statement in JavaScript is used to break the loop and transfer control to the line immediately
outside of loop. In JavaScript, the break statement has three uses:
x First, as you have seen, it terminates a statement sequence in a switch statement.
x Second, it can be used to exit a loop.
x Third, it can be used as a civilized form of goto.
Instead of exiting an entire program, we can use the break statement to exit the current loop. The format
of break is:
break;

However, break typically appears in the body of a while or do-while loop so that we can leave the loop
early.
Example Write a JavaScript program to test the break statement while finding your school name for
five times.
Solution Write the following code in Notepad editor and save as break.html.
<HTML>
<HEAD>
<TITLE>JavaScript break loop Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Printing your school name five time
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.98 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

var x = 1;
while (true)
{
document.write("CBSE Schools<br>");
if (x >= 5)
{
document.write("Loop breaked");
break;
}
x++;
}
</script>
</BODY>
</HTML>

Open the break.html file in IE, and the see the output window as shown in Figure 4.9.

Figure 4.9 break statement output using JavaScript.

From the above example, the while loop will execute and print the school name five time. But each time, the
variable x is checked till less than 5. When the variables value will be more than 5, then the while loop will be
terminated.
Example Write a JavaScript program to test the break statement while finding the sum of odd numbers
till the sum reaches 50.
Solution Write the following code in Notepad editor and save as break1.html.
<HTML>
<HTML>
<HEAD>
<TITLE>JavaScript break loop Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Printing sum of odd numbers using break statement
var x = 1;
var xoddsum = 0;
var xtmp = 0;
var lastx = 0;
while (true)
{
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.99

xtmp = xoddsum + x;
if (xtmp > 50)
break;
xoddsum += x;
x += 2;
}
lastx = x;
document.write("The sum of odd numbers before " + lastx + " is: " + xoddsum);
</script>
</BODY>
</HTML>

Open the break1.html file in IE, and the see the output window as shown in Figure 4.10.

Figure 4.10 break statement using JavaScript.


From the above JavaScript code,

x The test clause of this while is true, which you might well suspect is always true.
x This means that there is no way for this loop to terminate unless it is forced to do so by a break
statement.
x In statement xtmp = xoddsum + x, a temporary sum is formed in the variable xtmp.
x This sum is tested against the limit 50 in statement if (xtem > 50).
x If xtmp exceeds it then the break statement is executed and the loop terminates.
x If the test fails (xtmp is still less than 50) then the real sum is formed in statement xoddsum += x;
x Next, x is incremented by 2.
x Similarly, it keeps adding up numbers, odd numbers in fact, until the sum is less than 50.
x When the next sum would have exceeded 50, the if test succeeds, the break is executed and the flow of
control of the program reaches the first statement after the entire while block, i.e., lastx = x;
x This statement saves the last value of x in a different variable lastx.
x You can easily determine for yourself that the value of lastx must be 15. Since 1 + 3 + + 13, while
1 + 3 + + 13 = 50 exactly, while 1 + 3 + + 15 = 64 > 50.

 7KH FRQWLQXH 6WDWHPHQW

The continue statement is used to escape current execution (iteration) and transfer control back to the start
of the loop. However, instead of jumping out of the loop altogether, it jumps back to the beginning of the loop
and continues with the next iteration. The format of continue is:
continue;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.100 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Let us see Figure 4.11 for continue statement in a while loop.

for(i=0; i<10; i++)


`

{
Statements that
document.write("" + i + " "); comes under continue
if (i % 2 == 0)
continue;
document.write("" + i + " ");
`

.... These statements


are skipped
.... `
}

Figure 4.11 Continue statement execution style in JavaScript.


The following code demonstrates the continue statement. The continue statement does not break you
out of the loop entirely; it just skips the rest of body of the loop for that iteration, as demonstrated in the
following:
for (var count = 1; count <= 10; count++)
{
if (count == 5)
continue;
document.write(count);
document.write("<br>"); // Print a break to separate lines
}

This is similar to the previous break statement. The numbers 1 through 4 print out first. The continue
statement executes on the fifth time through the loop because count is equal to 5, which causes the number 5
not to be printed. Unlike the break statement, however, the for loop continues and the numbers 6 through 10
print.
Example Write a JavaScript program to demonstrate the continue statement for above example.
Solution Write the following code in Notepad editor and save as continue.html.
<HTML>
<HEAD>
<TITLE>JavaScript continue statement</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Printing number using continue statement
for (var count = 1; count <= 10; count++)
{
if (count == 5)
{
document.write("Continue without 5<br>");
continue;
}
document.write(count);
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.101

document.write("<br>"); // Print a break to separate lines


}
</script>
</BODY>
</HTML>

Open the continue.html file in IE, and the see the output window as shown in Figure 4.12.

Figure 4.12 continue statement using JavaScript.

4.6 ARRAYS

An array is a way to hold more than one value at a time. It's like a list of items. An array variable does not actually
store the arrayit is a reference variable that points to an array object. It12345678901234567890
can be defined as one-dimensional or
multi-dimensional arrays. 12345678901234567890
12345678901234567890
What is an array?
12345678901234567890
 2QH'LPHQVLRQDO $UUD\ 12345678901234567890
12345678901234567890
An array is a collection of
12345678901234567890
homogeneous data elements
12345678901234567890
A one-dimensional array is a list of variables that are of the same type
12345678901234567890
described by a single name, and
12345678901234567890
and are referenced through a common name. An individual variable in each element in an array is
the array is called an array element. Arrays provide a convenient method 12345678901234567890
12345678901234567890
referred by the array name with
12345678901234567890
the subscript or index enclosed
to handle groups of related data. Let us see Figure 4.13 to explore more
about array: 12345678901234567890
12345678901234567890
in square brackets [ ] .
Num - Name
12345678901234567890
Indexes
of the array

Num[0]
123456789012
4
123456789012
123456789012
Array objects Num[1] 12
123456789012
with index
123456789012
123456789012
position Num[2] 2

Num[3] 34

Num[4] 17

Figure 4.13 An array Num with values.


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.102 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Here, the numbers are called index values or subscripts to the array. The term subscript is used because
as a mathematical sequence, the array would be written with subscripts: a0, a1, a2, .... These numbers locate the
elements position within the array, thereby giving direct access into the array.
As we know that every array object holds space in memory. Like int, float, char, the linear list elements also
hold space in the memory. They take space as memory address according to their individual data values. Let us
consider our previous example of array Num. Each index position creates a different location in memory with
same individual object of array Num.
For example if Num[0] holds a position at memory address 4022, then Num[1] will hold at 4024, Num[2]
will hold at 4026, and so on as shown in Figure 4.14.

Indexes Num - Name Value of Address of


of the list Num[0] Num[0]

123456789012 Num[0]
`
4 4022
123456789012
123456789012
12345678
12345678
Array objects Num[1]
123456789012 12345678
`
12 4024
Memory
123456789012
with index 12345678
123456789012 Num[2]
` 12345678
address
123456789012
position 2 4026

Num[3]
`
34 4028

Num[4]
`
17 4030

Figure 4.14 Memory address for array Num.


The number that is used to refer to an individual element (i.e., 0, 1, 2, 3, 4) of an array is known as its array
index. This index number allows each element to be addressed uniquely. Array index starts at 0 and counts up
to the position of the last element of the array.

 'HFODUDWLRQ RI DQ DUUD\

To declare a one-dimensional array, use the general form:


var array_name = [item1, item2, ...];

where, array_name is the name of the array and [item1, item2, ...] are the array elements. For example,
var mAr1 = [21, 63, 75, 43, 19] // an array with 5 elements
var mAr2 = [5] // an array with 1 element

You can also create an array using JavaScript constructur Array(). The Array() constructor syntax has
three different forms:
x If you call the constructor with two or more arguments, the arguments initialize the array elements.
x If you only supply one argument to the Array constructor, the argument initializes the length of the
new array; the new arrays elements are not initialized.
x Finally, if you call the constructor without arguments, the new arrays length is set to zero, and its
elements are not initialized.
Here are examples:
var myAr1 = new Array(21, 63, 75, 43, 19) // an array with 5 elements
var myAr2 = new Array(100) // an empty array of length 100
var myAr3 = new Array() // an empty array of length 0
var Num = new Array(5) // an empty array of length 5
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.103

The new keyword is the way of telling JavaScript that the function
N ote
to the right of it is an object constructor and JavaScript treats it
accordingly. The subscript of the array
Let us look at the last array declaration Num which creates an begins with zero and ends with
array of 5 elements. Also, according to Figure 4.15, the Num array tells size-1. The rules for naming an
the interpreter that array are same as for other
variables but the size of the
x Num is the name of the array.
array will always be positive
x It is one-dimensional (linear). integer constant or an
x The number of elements in the array is 5, i.e. its size is 5. But it expression that evaluates a
can add or delete elements dynamically. positive integer constant at
x Array Num allocates a contiguous address in memory block. compilation time.

Num (5) Num.length


The array object contains five
0 Num[0]
The statement var integers, which are referred to as
Num = new 0 Num[1] Num[0], Num[1], and so on. It
Array(5) creates an 0 Num[2] also contains Num.length, which
array that can hold five gives the number of items in the
0 Num[3] array. Num.length cannot be
elements, and sets
Num to refer to it. 0 Num[4] changed.

Figure 4.15 Array Num in memory.

 $FFHVVLQJ HOHPHQWV RI DQ DUUD\

If the array declaration statement is:


var Num = new Array(5) // an empty array of length 5

the valid range of subscript is 0 to 4, i.e. lower bound is 0 and upper bound is the value one less than is specified
by the dimension specified in the declaration statement.
To access an element of an array, the subscripted variables are used which are formed by affixing each
subscript in brackets to the name of an array.
The first element of array named Num is accessed as Num[0], third as Num[2], ... , and the last element as
Num[4]. In general, the ith element is num[i1].

 ,QLWLDOL]LQJ HOHPHQWV RI DQ DUUD\

To initialize values to the various positions in an array, you do it in the normal way:
Num[0] = 4;

Here, a value of 4 is being assigned to position 0 in the array called Num. Again, the square brackets [ ] are
used to refer to each position. If you want to assign a value of 12 to array position 1, the code would be this:
Num[1] = 12;

Look at the following declaration statements:


var stud_age = [13, 15, 14, 13, 15];
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.104 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

The values stored in array stud_age is: stud_age Name

stud_age[0] = 13 1234567890
of the array
1234567890
stud_age[0]1234567890
stud_age[1] = 15 13
stud_age[2] = 14 1234567890
stud_age[3] = 13
1234567890
stud_age[1]1234567890
15
stud_age[4] = 15 1234567890
stud_age[2]1234567890
initializes 5 different ages into stud_age array as shown in Figure
1234567890
14
1234567890
stud_age[3]1234567890
4.16.
1234567890
13
1234567890
stud_age[4]1234567890
15

Figure 4.16 Diagrammatical representation of an array num.

x Look at the following declaration statement:


var Arr = [18, 0, 11, 14, 17, 22, 14, 10, 19, 25]
initializes elements
Arr[0] to 18,
Arr[1] to 0,
Arr[2] to 11,
Arr[3] to 14,
Arr[4] to 17,
Arr[5] to 22,
Arr[6] to 14,
Arr[7] to 10,
Arr[8] to 19, and FriendName - Name
Arr[9] to 25,
1234567890
of the array
1234567890
which declares total 10 integer spaces in array Arr and
stored 10 different values.
1234567890
FriendNames[0]1234567890
Mr. Vikash
1234567890
FriendNames[1]1234567890
Let us look at another array declaration to store five friends
names. You would create it in the following manner:
1234567890
Ms. Sangeeta
1234567890
FriendNames[2]1234567890
FriendNames = new Array(5); 1234567890
Mr. Sudhir
1234567890
FriendNames[3]1234567890
FriendNames is the name of the array and subscript range (5)
is the length of the array. Figure 4.17 shows the diagrammatic
1234567890
Ms. Sneha
1234567890
FriendNames[4]1234567890
Mr. Ranvir
representation of an array.

Figure 4.17 Diagrammatical representation of an array FriendNames.


Now, if you want to assign values to the different elements of the array, list the number of elements that
you want to access in brackets ([and]) following the names of the array, as shown in the following code:
FriendNames[0] = "Mr. Vikash"
FriendNames[1] = "Ms. Sangeeta"
FriendNames[2] = "Mr. Sudhir"
FriendNames[3] = "Ms. Sneha"
FriendNames[4] = "Mr. Ranvhir"

Example Write a JavaScript to assign five friends names and print them on the screen using array.
Solution Write the following code in Notepad editor and save as array01.html.
<HTML>
<HEAD>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.105

<TITLE>JavaScript Array</TITLE>
</HEAD> N o te
<BODY>
<SCRIPT type="text/javascript"> When you use a loop for
// Print five names using array processing elements of an
var FriendNames = new Array(5); array, loop counters value must
FriendNames[0] = "Mr. Vikash" be 1 less than the size of the
FriendNames[1] = "Ms. Sangeeta"
FriendNames[2] = "Mr. Sudhir"
array. All array subscripts begin
FriendNames[3] = "Ms. Sneha" with 0, not position 1.
FriendNames[4] = "Mr. Ranvhir"
document.write("The names are : <br>");
document.write("<hr>");
for(var count = 0; count < 5; count++)
document.write(FriendNames[count] + "<br>");
</script>
</BODY>
</HTML>
Open the array01.html file in IE, and see the output window as shown in Figure 4.18.

Figure 4.18 Print array values in JavaScript.


Array elements are processed according to their length. JavaScript supports a length property sets or
returns the number of elements in an array. For example,
var FriendNames = new Array(5); // An array
var Alength = FriendNames.length // Find the length of array

and the previous for loop can be written as:


for(var count = 0; count < Alength; count++)
document.write(FriendNames[count] + "<br>");

JavaScript has some usable methods which help to process array elements. These are:

concat(). This method is used to joins two or more arrays, and returns a copy of the joined arrays.
The syntax is:
array1.concat([item1[, item2[, . . . [, itemN]]]])

For example
<SCRIPT type="text/javascript">
var Week1 = ["Sunday", "Monday", "Tuesday"];
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.106 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

var Week2 = ["Wednesday", "Thursday", "Friday", "Saturday"];


var WeekDays = Week1.concat(Week2);
var Wlength = WeekDays.length
document.write("Week days are: <br>");
for(var count = 0; count < Wlength; count++)
document.write(WeekDays[count] + "<br>");
</script>

which will produce the result as:


Week days are:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

join(). This method joins the elements of an array into a string, and returns the string. The elements
will be separated by a specified separator. The default separator is comma (,). The syntax is:
arrayObj.join([separator])

For example
<script language = "JavaScript">
var Weeks = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
var WeekDays = Weeks.join()
document.write("Week days are: " + WeekDays);
var NWeekDays = Weeks.join("-") // Using seperator
document.write("<br>");
document.write("Week days are: " + NWeekDays);
</script>

which will produce the result as:


Week days are: Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
Week days are: Sunday-Monday-Tuesday-Wednesday-Thursday-Friday-Saturday

sort(). This method is used to sort the items of an array in its own place. No new array is created. The
sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). The
syntax is:
arrayObj.sort()

For example
<SCRIPT type="text/javascript">
var Weeks = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
Weeks.sort();
document.write("Week days are: " + Weeks);
document.write("<br>");
var EMarks = new Array(45.6, 67.6, 87.5, 34.5, 73.5, 77.6);
EMarks.sort();
document.write("Marks: " + EMarks);
</script>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.107

which will produce the result as:


Week days are: Friday,Monday,Saturday,Sunday,Thursday,Tuesday,Wednesday
Marks: 34.5,45.6,67.6,73.5,77.6,87.5

reverse(). This method is used to reverses the order of the elements in an array in its own place. No
new array is created. The syntax is:
arrayObj.reverse()

For example
<SCRIPT type="text/javascript">
var Weeks = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
Weeks.reverse();
document.write("Week days are: " + Weeks);
document.write("<br>");
var EMarks = new Array(45.6, 67.6, 87.5, 34.5, 73.5, 77.6);
EMarks.reverse();
document.write("Marks: " + EMarks);
</script>

which will produce the result as:


Week days are: Saturday,Friday,Thursday,Wednesday,Tuesday,Monday,Sunday
Marks: 77.6,73.5,34.5,87.5,67.6,45.6

Example Write a program to print the values of an initialized array of 10 elements.


Solution Write the following code in Notepad editor and save as array02.html.
<HTML>
<HEAD>
<TITLE>Displaying array values with its index</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var Num = new Array(8, 0, 11, -14, 17, 22, 14, 10, 19, 25);
for (i = 0; i < 10; i++) {
document.write( "The element at " + i + " position is : " + Num[i] + "<br>");
}
</script>
</BODY>
</HTML>

When you open the array02.html file in a browser, you will see array num is initialized with 10 elements
and its positional values are printed as shown below:
The element at 0 position is : 8
The element at 1 position is : 0
The element at 2 position is : 11
The element at 3 position is : -14
The element at 4 position is : 17
The element at 5 position is : 22
The element at 6 position is : 14
The element at 7 position is : 10
The element at 8 position is : 19
The element at 9 position is : 25
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.108 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Example Write a program to find the average of 6 students English marks in an initialized array
EMarks.
Solution Write the following code in Notepad editor and save as array03.html.
<HTML>
<HEAD>
<TITLE>Average of students marks</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var s_name = "DAV Model School"
var EMarks = new Array(45.6, 67.6, 87.5, 34.5, 73.5, 77.6);
var average = 0;
// Calculate the total of scores
for(ctr = 0; ctr < 6; ctr++)
average = average + EMarks[ctr];
// calculate the average
average = average / 6;
document.write("At " + s_name + ". Your class average is : " + average);
</script>
</BODY>
</HTML>

When you will execute the program, you will see the school name and class average as shown below:
At DAV Model School. Your class average is : 64.38333333333333

6RUWLQJDQ$UUD\ZLWKRXWXVLQJVRUW PHWKRG

A solution to the sorting problem is the bubble sort algorithm, which re-arranges the values by iterating over
the list multiple times, causing larger values to bubble to the top or end of the list.
The basic idea underlying the bubble sort is to pass through the file sequentially several times. If Num is
an array, each pass consists of comparing each element in the file with its successor (Num[i] with Num[i +
1]) and interchanging (swap) the two elements if they are not in proper order.
Consider Figure 4.19:

10 51 2 18 4 31 13 5 23 64 29

0 1 2 3 4 5 6 7 8 9 10
Figure 4.19 Unsorted values in an array (Num).

If you want the array in ascending order sequence, the following comparisons are made on the first pass:
Num[0] with Num[1] (i.e., 10 with 51) no interchange
Num[1] with Num[2] (i.e., 51 with 2) interchange
Num[2] with Num[3] (i.e., 51 with 18) interchange
Num[3] with Num[4] (i.e., 51 with 4) interchange
Num[4] with Num[5] (i.e., 51 with 31) interchange
Num[5] with Num[6] (i.e., 51 with 13) interchange
Num[6] with Num[7] (i.e., 51 with 5) interchange
Num[7] with Num[8] (i.e., 51 with 23) interchange
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.109

Num[8] with Num[9] (i.e., 51 with 64) no interchange


Num[9] with Num[10] (i.e., 64 with 29) interchange

Figure 4.20 illustrates the swaps performed during the first pass of the algorithm when applied to an array
(Num) containing 11 integer values.

Figure 4.20 After first interchange which places 64 in its correct position.

In Figure 4.20, black boxes represent values being compared; arrows indicate exchanges. Notice that after
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.110 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

this first pass, the largest element (in this case 64) is in its proper position within the array. In general, Num[n-
i+1] will be in its proper position after iteration i. The method is called the bubble sort because each number
slowly bubbles up to its proper position.
The efficiency of the bubble sort algorithm only depends on the number of keys in the array and is
independent of the specific values and the initial arrangement of those values.
To determine the efficiency:
x You must determine the total number of iterations performed by the inner loop for a sequence containing
n values.
x The outer loop is executed n 1 times since the algorithm makes n 1 passes over the sequence.
x The number of iterations for the inner loop is not fixed, but depends on the current iteration of the outer
loop.
x On the first pass over the sequence, the inner loop executes n 1 times; on the second pass, n 2
times; on the third, n 3 times, and so on until it executes once on the last pass.
x The total number of iterations for the inner loop will be the sum of the first n 1 integers.

After the second pass the array will place the second largest element in its position as shown in Figure
4.21 as:

Figure 4.21 After second interchange which places 51 in its correct position.
Notice that 51 has now found its way to the second highest position. Since each iteration places a new
element into its proper position, a sequence of n elements requires no more than n 1 iterations. After completion
of the outer loop execution (i.e., n 1 times), the final sorted list of ascending order list will be stored in the array
as shown in Figure 4.22.

Figure 4.22 After n 1 iterations, the final sorted array.

 $OJRULWKP RI EXEEOH VRUW

Steps: 1. Enter the boundaries for an array, N.


2. I = 1.
3. Enter the array element, Num[I].
4. If I <= N then 6 else 5.
5. I = I + 1 Repeat step 3.
6. I = 1.
7. If I < N then step 8 else step 16.
8. J = I + 1.
9. If J <= N then step 10 else step 15.
10. If Num[J] > Num[J+1] then step 11 else step 14.
11. temp = Num[J].
12. Num[J] = Num[J+1].
13. Num[J+1] = temp
14. J = J + 1 : Repeat Step 9.
15. I = I + 1 : Repeat Step 7.
16. Print the array.
17. END.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.111

Example Write a program to accept or assign any number of numbers into an array, and arrange all
the elements in ascending order using bubble sort method.
Solution Write the following code in Notepad editor and save as array04.html.
<HTML>
<HEAD>
<TITLE>Sorting array elements</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Sorting elements
var num = new Array(10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29);
var i, j, temp;
N = num.length;
document.write("The array initialized values are : ");
for (i = 0; i < N; i++)
document.write(num[i] + " ");
document.write("<br>");
for (i = 0; i < N; i++)
for (j = 0 ; j < N-1; j++)
if (num[j] > num[j+1]) {
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
document.write("The sorted values are : ");
for (i = 0; i < N; i++)
document.write(num[i] + " ");
</script>
</BODY>
</HTML>
When you will open the array04.html file in a browser like IE, you will see bubble sort elements as
shown in Figure 4.23.

Figure 4.23 Sorted array elements using JavaScript.


Example Write a program to find the maximum and minimum element in an array of 10 numbers.
Solution Write the following code in Notepad editor and save as array05.html.
<HTML>
<HEAD>
<TITLE>Minimum and maximum in an array</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var num = new Array(100, 20, 450, 143, 321, 241, 325, 76, 150, 120);
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.112 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

len = num.length;
var max = num[0]; // Initialize the default value to max and min
var min = num[0];
for (var i = 0; i < len; i++)
{
if (num[i] > max) max = num[i];
if (num[i] < min) min = num[i];
}
document.write("The array elements are : ");
for (i = 0; i < len; i++)
document.write(num[i] + " ");
document.write("<hr>");
document.write("The maximum value in the list is : " + max + "<br>");
document.write("The minimum value in the list is : " + min);
</script>
</BODY>
</HTML>

When you will open the array05.html file in a browser like IE, you will see the maximum and minimum
value as shown in Figure 4.24.

Figure 4.24 Maximum and minimum elements in an array.

 3DVVLQJ $UUD\ WR )XQFWLRQ

JavaScript automatically passes arrays to methods using simulated call-by-reference. The called methods can
modify the element values in the callers, the original arrays. The values of the name of the array are the address
of the first element of the array. Because the starting address of the array is passed, the called method knows
precisely where the array is stored. Therefore, when the called method modifies array elements in its method
body, it is modifying the actual elements of the array in their original memory locations.
To pass an array argument to a method, specify the name of the array without any brackets. For example,
if an array hourlyTemp has been declared as:
var hourlyTemp = new Array();

the method call statement:


modifyArray(hourlyTemp, 24);

passes array hourlyTemp and its size to method modifyArray(). For example, the method header for method
modifyArray() might be written as:

function modifyArray(ArrayName, arraySize)


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.113

indicating that modifyArray() accepts to receive an array of integers in parameter b and the number of array
elements in parameter arraySize.
Example Write a program to pass an initialized array and an individual array element into a method
and multiply each array element by 4 and display it.
Solution Write the following code in Notepad editor and save as array06.html.
<HTML>
<HEAD>
<TITLE>JavaScript Array</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to pass the array by reference
function modifyArray(NewArray, N)
{
document.write("The modified array elements are : ");
for (i = 0; i < N; i++)
document.write(Num[i] * 4 + " ");
}
var Num = new Array(20, 18, 13, 24, 9, 25);
xlen = Num.length;
document.write("The original array elements are : ");
for (i = 0; i < xlen; i++)
document.write(Num[i] + " ");
document.write("<hr>");
modifyArray(Num, xlen)

</script>
</BODY>
</HTML>

When you will open the array06.html file in a browser like IE, you will see pass-by-reference techniques
of array elements to a method output as shown in Figure 4.25.

Figure 4.25 Result of an array with pass by reference.


The above program passes an array Num into modifyArray() function as pass by reference. That is the
parameter Num and xlen are passed into the modifyArray() function with reference to NewArray and N
respectively. Inside the method the array elements are multiplied by 4 and printed.
Example Write a program to find the second maximum and the second minimum number in an array
of 10 numbers.
Solution Write the following code in Notepad editor and save as array07.html.
<HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.114 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<HEAD>
<TITLE>Second maximum and minimum in an array</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to find second largest element
function SecondLargest(Num, N) {
var m, m2;
if (Num[0] > Num[1]) {
m = Num[0];
m2 = Num[1];
} else {
m = Num[1];
m2 = Num[0];
}
for (x = 2; x < N; x++) {
if (Num[x] > m2) {
if (Num[x] > m) {
m2 = m;
m = Num[x];
} else
m2 = Num[x];
}
}
document.write("The second largest element is: " + m2);
}
// Function to find second smallest element
function SecondSmallest(Num, N) {
var m, m2;
var m, m2;
if (Num[0] < Num[1]) {
m = Num[0];
m2 = Num[1];
} else {
m = Num[1];
m2 = Num[0];
}
for (x = 2; x < N; x++) {
if (Num[x] < m2) {
if (Num[x] < m) {
m2 = m;
m = Num[x];
} else
m2 = Num[x];
}
}
document.write("The second smallest element is: " + m2);
}
var Num = new Array(100, 20, 450, 143, 321, 241, 325, 76, 150, 120);
Num.sort();
len = Num.length;
document.write("Original array elements are : ");
for (i = 0; i < len; i++)
document.write(Num[i] + " ");
document.write("<hr>");
SecondLargest(Num, len);
document.write("<hr>");
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.115

SecondSmallest(Num, len);
</script>
</BODY>
</HTML>

When you will open the array07.html file in a browser like IE, you will see the second maximum and
minimum values as shown in Figure 4.26.

Figure 4.26 Second maximum and minimum elements in an array.

3RLQWVWR5HPHPEHU

1. A repetition structure specifies that an action is to be repeated while some condition remains
true.
2. The format for the while repetition structure is:
while (condition)
Statements;
3. A do statement executes its loop body at least once.
4. The do-while repetition structure tests the loop-continuation condition at the end of the loop,
so the body of the loop will be executed at least once. The format for the do-while structure is:
do
statement
while (condition);
5. A for statement is usually used when a loop is executed a set number of times.
6. The for repetition structure handles all the details of counter-controlled repetition. The general
format of the for structure is:
for (expession1; expression2; expression3)
statement
where expression1 initialized the loops control variable, expression2 is the loop-continuation
condition and expression3 increments or decrements the control variable.
7. A break statement is necessary at the end of each case alternative in a switch statement to
jump to the end of the switch.
8. The break statement, when executed in one of the repetition structures (for, while and do-
while), causes immediate exit from the structure.
9. The continue statement, when executed in one of the repetition structures (for, while and do-
while), skips any remaining statements in the body of the structure and proceeds with the test
for the next iteration of the loop.
10. An array is a variable containing several homogeneous data types.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.116 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

11. Array elements can be accessed by using a subscript or index.


12. The individual data items in the array are called subscripted variables or elements.
13. All elements of the array are stored contiguously in the computer memory.
14. The name of the array is a constant value that represents the address of the first element in
the array.
15. By default the array elements are initialized as binary zero.
16. The index of the array should be a positive integer number.

SOLVED EXERCISES
1. What is the use of while statement?
Ans. A while statement allows a program to execute a statement many times.
2. What is body of the loop?
Ans. The set of statements repeating again and again is called the body of the loop.
3. What is a for statement?
Ans. The for statement encloses one or more JavaScript statements that form the body of the loop. The
statements in the for loop repeat continuously a certain number of times.
4. What is the difference between the break and continue statements?
Ans. A break statement will terminate the execution of the body of the switch or loop. A continue statement
begins the next iteration of the loop in which it is contained.
5. Differentiate between selection statement and looping statements?
Ans. In selection statement, a particular statement is selected from the group of statements, while in the
looping statement, group of statements will be executed number of times.
6. What are the three expressions given in the for statement?
Ans. The three expressions given in the for loop are: initial value, final value and incremented / decremented
value.
7. How will you get out of a loop?
Ans. We can get out of the loop using the break statement.
8. What is the use of continue statement in JavaScript?
Ans. We use the continue statement when data in the body of the loop is bad, out of bounds or unexpected.
Instead of acting on the bad data, we might want to return to the top of the loop to get another data
value.
9. How does the while loop execution occur?
Ans. The while loop execution first examines the Condition. If the Condition is true, then it executes the
Statement. After executing the Statement, the Condition is checked again. As long as the Condition is
true, it will keep on executing the Statement.
10. Differentiate between while and do-while loop.
Ans. The differences are:
x A while loop checks that the condition is true before executing the loop and continues to execute
the loop until the condition becomes false whereas a do-while loop executes the loop first and then
checks the condition to see if it should execute again.
x A while loop is executed zero or more times whereas a do-while loop will always execute at least one
time.
11. State the difference between entry controlled loop and exit controlled loop.
Ans. In entry controlled loop, the test condition is checked first and if that condition is true then the block of
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.117

statement in the loop body will be executed, while in exit controlled loop the body of loop will be
executed first and at the end the test condition is checked, and if condition is satisfied then the body of
the loop will be executed again. For example:
while (Condition)
{
program statements;
}
is in entry controlled loop and
do
{
program statements;
} while (Condition);
is an exit controlled loop.
12. What is an array? How does it differ from ordinary variables?
Ans. An array is a collection of variables of the same type under one name. Arrays are defined in the same
manner as ordinary variables, except that each array name must be accompanied by a size specification
(i.e. the number of elements).
13. What is subscript?
Ans. The element number in [ ] is called subscript.
14. What is the other name for subscript?
Ans. Indices.
15. What is the purpose of subscript in an array?
Ans. The term subscript is used because as a mathematical sequence, an array would be written with
subscripts 0, 1, 2, 3. These numbers locate the elements position within the array, thereby giving direct
access to the array.
16. Which element is num[9] of the array num?
Ans. num[9] is the 10th element of the array num.
17. If an array Ar = [1, 9, 8, 5, 2];[ICSE 2008]
(i) What is Ar.length?
(ii) What is Ar[2]?
Ans. (i) The Ar.length() is 5.
(ii) The Ar[2] is 8.
18. Write an appropriate for or while loop for the situations described below:
(a) A loop is to be repeated 20 times.
(b) A loop is to be repeated 100 times, except the loop is to be terminated if the value of the variable P
becomes 50.
(c) A loop is to be processed till 200 starting from 100. Print all even numbers between the loop.
Ans. (a) for (i = 0; i< 200; i++)
(b) for (P = 0; i< 100; p++)
if (P == 50)
break; # Terminates the loop
(c) ctr = 100
while (ctr <= 200)
System.out.println (ctr);
ctr+=2;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.118 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

19. Write a JavaScript statement or a set of JavaScript statements to accomplish the following:
Sum of odd integers between 1 and 100 using a for structure. Assume the integer variable N and ctr
have been declared.
Ans. Sum = 0;
for (int ctr = 1; ctr <= 100; ctr += 2)
Sum += ctr;
20. Point the errors in the following JavaScript code and write correct script.
<SCRIPT type="text/javascript">
var sum=0;
while (c <10 step 2)
{
if c%3 == 0
sum = sum + c;
c++;
}
window.write(sum);
</SCRIPT>
Ans. The errors are:
<SCRIPT type="text/javascript">
var sum=0;
while (c <10 step 2) // Error 1, Error 2
{
if (c%3 == 0) // Error 3
sum = sum + c;
c++;
}
window.write(sum); // Error 4
</SCRIPT>
Where,
x Error 1. The while condition does not support the step clause. It must be a condition: while (c < 10)
x Error 2. The variable c must be declared and initialized.
x Error 3. The condition of if statement must be enclosed within parenthesis, i.e., if (c%3 == 0)
x Error 4. The JavaScript, to produce the output, write Document.Write instead of Window.Write.
The correct JavaScript code is (outputh.html):
<SCRIPT LANGUAGE = "JavaScript">
var sum=0;
var c = 0;
while (c <10)
{
if (c%3 == 0)
sum = sum + c;
c++;
}
document.write(sum);
</SCRIPT>
21. Give the output of the following code:
<SCRIPT type="text/javascript">
var Comment = " ";
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.119

var Remainder = 0;
var Exitno = 3;
var Check = 27;
for (count = 1; count <= 3; count++)
{
Remainder = Check % count;
if (Remainder == Exitno)
{
break;
}
Comment = Check + "divided by " + count + " leaves a remainder of " + Remainder;
document.write(Comment + "<br>");
}
</SCRIPT>
Ans. The output is (outputi.html):
27divided by 1 leaves a remainder of 0
27divided by 2 leaves a remainder of 1
27divided by 3 leaves a remainder of 0
22. Write the output of the following JavaScript program:
<SCRIPT type="text/javascript">
var a = 10, b = 8;
for (var i = 0; i <= a; i++)
document.write(i + " ");
for (var j = 0; j <= a; j++)
document.write(j + " ");
b = a;
++a;
b++;
document.write(a + "<br>" + b + "<br>" + b);
</script>
Ans. The output is (outputj.html):
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 11
11
11
23. Rewrite the below given program using JavaScript for ( ) loop:
<SCRIPT type="text/javascript">
var i, sum = 0, i = 1;
while (i <= 10)
{
sum = sum + i;
i++;
}
document.write(sum);
</script>
Ans. The code using for () loop is:
<SCRIPT type="text/javascript">
var i, sum = 0;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.120 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

for( i=1;i <= 10;i++)


{
sum = sum + i;
}
document.write(sum);
</script>
24. Point the errors in the following code and write the corrected script.
<SCRIPT type="text/javascript">
variable arr=new Array(3)
arr[0] = NULL
arr[1] = Gopal"
arr[2] = "Sharma"
document.write(arr[0]+<br>+arr[1]+arr[2])
</SCRIPT>
Ans. The errors are:
<SCRIPT type="text/javascript">
variable arr=new Array(3) // Error 1 : Syntax error
arr[0]= NULL // Error 2 : NULL is undefined
arr[1] = "Gopal"
arr[2] = "Sharma"
document.write(arr[0] + "<br>" + arr[1] + arr[2]) // Error 3 : syntax error;
Where,
x Error 1. The variable is declared with the keyword var not variable.
x Error 2. The assignment of NULL should be null.
x Error 3. The <br> should be placed in double quotation marks because two data values are
concatenated, it is treated as string.
The correct JavaScript code is (outputk.html):
<SCRIPT type="text/javascript">
var arr=new Array(3)
arr[0] = null
arr[1] = "Gopal"
arr[2] = "Sharma"
document.write(arr[0] + "<br>" + arr[1] + arr[2])
</SCRIPT>
25. Give the output of the following code segment:
<BODY>
<SCRIPT type="text/javascript">
var sum = new Array(6);
var Total = 0;
sum[0] = 0;
for (var icount = 1; icount < 4; icount++)
{
Total += icount;
sum[icount] = Total;
document.write(sum[icount] + "<br>")
}
document.write(Total);
</SCRIPT>
</BODY>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.121

Ans. The output is (outputl.html):


1
3
6
6
26. What will be the output of following JavaScript segment?
<SCRIPT type="text/javascript">
var i, j, k, x = 0;
for(i = 0; i < 5; ++i)
for(j = 0; j < i; ++j)
{
k = (i + j 1);
if ( k % 2 == 0)
x += k;
else
if (k % 3 == 0)
x += k 2;
document.write(x + " ");
}
document.write(x);
</script>
Ans. The output is (outputm.html): 0 0 2 4 5 9 10 14 14 20 20
27. Convert the following segment into equivalent for loop:
var i=0;
while (i<=20) {
document.write(" " + i.toString()+" ");
i++;
}
Ans. The equivalent for loop is:
var i;
for (i=0; i<=20; i++)
document.write(" " + i.toString()+" ");
28. Consider the following program code and tell how many times the loop will execute:
var x = 5, y = 50;
while (x <= y)
{
y = y / x;
x = x + 5;
}
Ans. The loop will execute 2 times.
29. Convert the following segment into an equivalent do loop:
var x, c;
for (x=10, c=20; c>=10; c=c-2)
x++;
Ans. The do loop is:
var x=10, c=20;
do {
x++;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.122 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

c=c-2;
} while (c>=10);
30. Given the output of the following code fragment:
var i;
for(i = 1, j = i + 10; i < 5; i++, j = i * 2) {
document.write("i= " + i + " j= " + j + "<br>");
}
Ans. The output is:
i = 1 j = 11
i=2j=4
i=3j=6
i=4j=8
31. Identify and correct the errors in each of the following:
while (ctr <= 5) {
table += ctr;
++ctr;
Ans. Error: Missing the closing right curly brace of the while body.
Correction: Add a closing right brace after the statement ++ctr;
32. Find the error in each of the following code segments and explain how to correct it.
a = 1;
while (a <= 10);
a++;
}
Ans. Error: The semicolon after the while header causes an infinite loop and there is a missing left brace.
Correction: Replace the semicolon by a { or remove both ; and the }.
33. Find the error in each of the following code segments and explain how to correct it.
for (x = .1; y != 1.0; y+= .1)
document.write(x);
Ans. Error: Using a floating-point number to control a for repetition structure may not work because floating-
point numbers are represented approximately by most compilers.
Correction: Use an integer and perform the proper calculation in order to get the value you desire.
for (x = 1; y != 10; y+= 1)
document.write(x);
34. What is wrong with the following while repetition structure?
while (x >= 0)
Sum += x;
Ans. The value of the variable x is never changed in the while structure. Therefore, if the loop-continuation
condition (x >= 0) is true, an infinite loop is created. To prevent the infinite loop, x must be decremented
so that it eventually becomes less than 0.
35. Find the error in each of the following code segments and explain how to correct it. The following code
should print the value from 1 to 10 in a web browser.
ctr = 1;
while (ctr < 10)
document.write(ctr++);
Ans. Error: Improper relational operator used in the while repetition-continuation condition.
Correction: Use <= rather than < or change 10 to 11.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.123

36. Analyse the following program segment and determine how many times the loop will be executed and
what will be the output of the program segment?
var p = 200;
while(true) {
if (p < 200)
break;
p = p - 20;
}
document.write(p);
Ans. The loop will execute 6 times and the output is: 180
37. Rewrite the following program segment using while instead of for statement.
var f=1, I;
for (i=1;i<=5;i++) {
f*=i;
document.write(f);
}
Ans. The code is:
var f=1, i;
i= 1;
while (i<=5) {
f*=i;
document.write(f);
i++;
}
38. Rewrite the following program segment using the if...else statement
comm = sale > 15000 ? sale * 5/100 : 0;
Ans. The if...else statement is:
if (sale > 15000)
comm = sale * 5/100;
else
comm = 0;
39. How many times will the following loop execute? What value will be returned?
var x = 2, y = 50;
do {
++x;
y -= x++;
} while (x <= 10);
return y;
Ans. The loop will execute 5 times. The returned value is 15.
40. What is the final value of ctr when the iteration process given below executes?
var ctr = 0, i, j;
for (i = 1; i <= 5; i++)
for (j = 1; j <= 5; j+=2)
++ctr;
Ans. The final value of ctr is 15.
41. What will be value of x after executing following JavaScript code.
var a=10, b=12, x=5, y=6;
while (a<=b) {
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.124 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

if (a%2==0)
x=x + y;
else
x=x-y;
a=a+1;
document.write(""+x);
}
Ans. The final value of x is 11.
42. Find the errors from the following code segment and rewrite the corrected code underlining the
correction made.
var a ,b;
c = a + b;
for(;i<=5;i++) {
Display c;
c=c+1
]
Ans. The underlined correct code is:
var a=0 , b=0, c, i=1;
c = a + b;
for(;i<=5;i++) {
document.write(""+c);
c=c+1;
}
43. Rewrite the following code using do-while loop.
var x;
for(x=0;x<10;x++) {
document.write(x);
}
Ans. The do-while code is:
var x=0;
do {
document.write(x);
x=x+1;
} while(x<10);
44. How many times does the following loop get executed?
var x = 5, y = 35;
while (x <= y) {
x += 8;
}
Ans. The loop will execute 4 times.
45. What will be the output of the the following code?
var num = 1;
do {
document.write("" + num.toString() + "<br>");
num = num + 2;
}while (num <= 10);
Ans. The output is:
1
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.125

3
5
7
9
46. Predict the value of prod of the following JavaScript construct:
var m=5, prod=1, i=1;
while(i<=5) {
prod=prod+prod*(m%2);
--m; ++i;
}
Ans. The output of prod is 8.
47. Write a JavaScript Program to print the following Pattern:
(i) (ii)
6 A
55 AAA
444 AA A AA
3333 A A AA A A A
22222 AAAAAAAAA
111111
Ans. (i) The code is (outputn.html):
for(i=6; i>=1;i--) {
for(j=6; j>=i; j--)
document.write(" "+i);
document.write("<br>");
}
(ii) The code is (outputo.html):
for(i=1; i<=5;i++) {
for(j=4; j>=i; j--)
document.write(" ");
for(k=1; k<=(2*i-1); k++)
document.write("A" + " ");
document.write("<br>");
}
48. What will be the value of A and B after execution of the following code:
var A = 100, B;
for(B = 10; B <= 12; B++) {
A+= B;
}
document.write("A: " + A + " B: " + B);
Ans. The values are: A: 133 B: 13
49. How many times does the following while loop get executed?
var K=5, L=36;
while (K<=L) {
K+=6;
}
Ans. The while loop will execute 6 times.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.126 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

50. What will be the values of variables P and Q after the execution of the following code?
var P, Q=0;
for (P=1; P<=4; P++) {
Q+=P;
Q ;
}
Ans. The value of variable P = 5 and variable Q = 6
51. How many times the following loop will execute the statements inside it? Which one of them is Entry
Control and which one is Exit Control?
Loop 1 1 Loop 2
var j=8, total=0; var j=8, total=0;
while (j > 1) do
{ {
total += j; total += j;
j -= 2; j -= 2;
} } while (j > 1);
Ans. Loop 1 will execute 4 time and Loop 2 will execute 4 times.
Loop 1 is the Entry Control loop and Loop 2 is the Exit Control loop.
52. What will be the output of the following code?
var Total = 0, End = 10;
for (Turn = 1; Turn <= End; Turn += 2)
Total++;
document.write("Total " + Total + "<br>");
document.write("Turn " + Turn + "<br>");
Ans. The output is:
Total 5
Turn 11
53. Rewrite the following program code using a while loop statement:
var Last = parseInt(prompt('Enter any number'));
for (C = 1; C <= Last; C++)
document.write(C + " ");
Ans. The while loop statements are:
var Last = parseInt(prompt('Enter any number'));
C = 1;
while (C <= Last) {
document.write(C + " ");
C++;
}
54. Observe the following code carefully and find which statement will never get executed in the code.
int Count=1; //Statement 1
do //Statement 2
{ //Statement 3
if (Count<15) //Statement 4
document.write("Jump"); //Statement 5
else //Statement 6
document.write("Stop"); //Statement 7
Count+=4; //Statement 8
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.127

} //Statement 9
while(Count<=15); //Statement 10
Ans. Statement 7
55. What will be the values of variables agg and agg1 after the execution of the following loops?
Loop 1: Loop 2:
var a=9, agg=9; var b=9, agg1=0;
while (a>10) do
{ {
agg+=a; agg1+=b;
a-=2; b-=2;
} } while (b>10);
Ans. The value of agg is 9 and agg1 is 9
56. What will be the output of the following code:
var G=1;
do
{
document.write(G++ + "<br>");
G=G+1;
}while(G<=5);
Ans. The output is:
1
3
5
57. What will be the values of x and y after execution of the following code:
var x, y=0;
for (x=1; x<=5; ++x)
y=x++;
--y;
Ans. The value of x = 7 and y = 4
58. Rewrite the following program code using a for loop:
var i = 1, sum = 0;
while (i<10)
{
sum += i;
i += 2;
}
Ans. The code using for loop is:
var i, sum = 0;
for (i = 1; i < 10; i+=2)
sum += i;
59. Write a JavaScript function to find the sum of odd numbers up to 10.
Ans. The function is as (sumodd.html):
<SCRIPT type="text/javascript">
function odd_sum()
{
var i;
var sum = 0;
for (i = 1; i <= 10; i++)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.128 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

if ((i%2) == 1)
sum = sum + i;
document.write("The sum of odd numbers upto 10 is " + sum);
}
odd_sum();
</script>
60. Write a JavaScript program to find the area of circle. The program should enter no. of time the value
of radius of a circle throug a prompt window. You can only exit when you press the Cancel button in the
prompt window.
Ans. The JavaScript program is (radius.html):
<HTML>
<HEAD>
<TITLE>Area of circle</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var rad, area;
rad = prompt("Enter radius")
while (rad != null) {
area = 3.14 * rad * rad
document.write("<P> radius = " + rad + ", area = " + area)
rad = prompt("Enter radius")
}
</script>
</BODY>
</HTML>
61. Write a JavaScript program to print the first 12 terms of Fibonacci series (i.e., sum of previous two
numbers is the next number), e.g.; 1 1 2 3 5 8 13
Ans. The JavaScript program is (fibn.html):
<SCRIPT type="text/javascript">
var i, j, k, l;
i = 0;
j = 1;
document.write("The Fibonacci series is.... <br> ");
document.write(i + " ")
document.write(j + " ")
for(l=0; l<10; l++)
{
k = i + j;
i = j;
j = k;
document.write( k + " ");
}
</script>
62. Write a JavaScript program to print the mathematical table from 1 to 3.
Ans. The JavaScript program is (mtable3.html):
<SCRIPT type="text/javascript">
var i, j, k, l;
i = 0;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.129

j = 1;
for (i=1; i<=3; i++)
for(j=1; j<=10; j++)
{
k = i * j;
document.write(i + "*" + j + "=" + k + "<br> ")
}
</script>
63. Write a JavaScript code to swap two numbers without using third variable.
Ans. The JavaScript code is (swap.html):
# This program swaps two numbers without using third variable
<HTML>
<HEAD>
<TITLE>Swapping two numbers</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// This program swaps two numbers without using third variable
var a = parseInt(prompt("Enter first number: "));
var b = parseInt(prompt("Enter second number: "));
a=a+b
b=a-b
a=a-b
document.write("After swapping a is > " + a + "<br>");
document.write("After swapping b is > " + b + "<br>");
</script>
</BODY>
</HTML>
64. Write a JavaScript with function having two value parameters X and Y with result type float to find
the sum of series given below.
1+ X1/2! + X2/3! + ..+ XN/(N+1)!
Ans. The function is (seriesxy.html):
<SCRIPT type="text/javascript">
function sum_series(X, N)
{
var sum = 1, temp = 1; // Initialize the series first value 1
for (var i = 2; i <= N+1; i++) // Starting series value is 2
{
temp = temp * (X/i); // (4/2!) and so on
sum += temp;
}
return (sum);
}
var X = 4;
var N = 5;
var result = sum_series(X, N);
document.write("The series value is : " + result);
</script>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.130 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

65. Write a program in JavaScript to print first 10 multiples of an integer N.


Ans. The function is (mult10.html):
<SCRIPT type="text/javascript">
function Miltiple10(N)
{
var i;
for (i = 1; i <= 10; i++)
document.write(" " + i*N);
}
Miltiple10(5);
</script>
6. Write a function in JavaScript to reverse a number and display it on your monitor.
Ans. The function is (reverse.html):
<SCRIPT type="text/javascript">
function reverse(N)
{
var R, N1 = 0;
while ( N >= 1)
{
R = N % 10;
N1 = N1*10 + R;
N = parseInt(N / 10);
}
document.write("The Reverse number is " + N1);
}
reverse(123);
</script>
67. Write a function to find the sum of series.
12 + 22 + 32 + 42 + 52 + 62 + .. up to 10 terms.
Ans. The function is (sseries.html):
<SCRIPT type="text/javascript">
function sum_series()
{
var i;
var sum = 0;
var k = 12;
for (i=1; i<=10; i++)
{
sum = sum + k;
k = k + 10;
}
document.write("Sum is " + k);
}
sum_series();
</script>
68. Write an HTML program using JavaScript to search a particular element of an array of 10 elements.
Ans. The program is (searchn.html):
<HTML>
<HEAD>
<TITLE>Minimum and maximum in an array</TITLE>
</HEAD>
<BODY>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.131

<SCRIPT type="text/javascript">
// Search an element
var flag = 0;
var pos;
var num = new Array(10);
num[0] = 100;
num[1] = 20;
num[2] = 450;
num[3] = 143;
num[4] = 321;
num[5] = 241;
num[6] = 325;
num[7] = 76;
num[8] = 150;
num[9] = 120;
document.write("The array elements are...<br>");
for (var i = 0; i <= 9; i++) {
document.write(num[i] + " ");
}
var s_num = parseInt(prompt("Enter search no."))
for (var i = 0; i <= 9; i++) {
if (num[i] == s_num )
{
flag = 1;
pos = i+1;
}
}
if ( flag == 1)
document.write("<br>The element is present at location: " + pos);
else
document.write("<br>The element is not present ");
</script>
</BODY>
</HTML>
69. Write a function to find the sum of series.
(1) + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) . upto N terms.
Ans. The function is (newseries.html):
<SCRIPT type="text/javascript">
function sumseries(n)
{
var i, sum = 0, sum1 = 0;
for(i = 1; i <= n; i++) {
sum = 0;
for(var j =0; j<=i; j++)
sum = sum + j;
sum1 = sum1 + sum;
}
return(sum1);
}
var n = 5;
var result = sumseries(n);
document.write("The value of the series is : " + result);
</script>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.132 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

70. Write a function to find the sum of series.


1 1 1 1 1
1 + 2 + 3 + 4 + 5 + 6 + ..... upto N terms
Ans. The function is (pseries.html):
<SCRIPT type="text/javascript">
// 1 + 1/2 + 1/3 + 1/4 +...+ 1/n
function sumseries(n)
{
var i = 1;
var term, sum=0;
while (i <= n)
{
term = 1/i;
sum = sum + term;
i++;
}
return(sum);
}
var n = 5;
var result = sumseries(n);
document.write("The value of the series is : " + result);
</script>
71. Write a function to find the sum of series.
1 1 1 1 1
2
+ 2 + 2+ 2+ 2+ ..... upto N terms
1 3 5 7 9
Ans. The function is (mseries.html):
<SCRIPT type="text/javascript">
// 1/1^2 + 1/3^2 + 1/5^2 + 1/7^2 +...+ 1/n^2
function sumsquare(n)
{
var i = 1;
var term, sum = 0;
while (i <= n)
{
term = 1 / (i*i);
sum = sum + term;
i = i + 2;
}
return(sum);
}
var n = 5;
var result = sumsquare(n);
document.write("The value of the series is : " + result);
</script>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.133

72. Write a JavaScript function with HTML program to find the square of numbers from 1 to 10 as shown
the following figure:

Ans. The function is (square.html):


<html>
<head>
<title>Squared Numbers</title>
<SCRIPT type="text/javascript">
<!--
function Num_square(){
document.write("<tr><th bgcolor='#CCCC99'>Number</th>
<th bgcolor='#CCCC99'>Square</th></tr>")
for (var i=1; i<=10; i++){
document.write("<tr> <td align = center>")
document.write(i)
document.write("</td><td align = center>")
document.write(i*i)
document.write("</td></tr>")
}
}
//-->
</script>
</head>
<body>
<table border="1" cellpadding="5" cellspacing="0" width = 50% BORDERCOLOR=LIME
bgcolor=YELLOW>
<script>
Num_square()
</script>
</table>
</body>
</html>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.134 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

REVIEW QUESTIONS
1. What is conditional statement?
2. Differentiate between while and do...while loop.
3. What is the purpose of for loop?
4. What is the role of control variable in for statement?
5. How break and continue statements work in repetitive statements?
6. Why is continue statement called a jumping statement?
7. Use of continue statement should be avoided in programming. Why?
8. What are the ways to create arrays in JavaScript? How are array cells indexed?
9. Find the output of the following code:
(a) var i = 1;
while (i < 5) {
document.write(i + " ");
i = i*2;
}
(b) var total = 0, sum = 0;
for (i=0; i<=10;i++)
sum = sum + 1;
document.write(total);
(c) var N = 1;
while (N <= 32) {
N = 2 * N;
document.write(N + " ");
}
(d) var x = 5, y = 1;
while (x > 0) {
x = x - 1;
y = y * x;
document.write(y + " ");
}
(e) var U = 10, V = 20;
for (I = 1; I <= 2; I++) {
document.write("[1]=" + U++ + " & " + V + 5 + "<br>");
document.write("[2]=" + ++V + " & " + U + 2);
}
10. What is the output of the following program segment?
(a) i = 0;
for (i = 1; i <= 20; i++) {
document.write(i + " ");
i = i + 2;
}
(b) i = 0, x = 0;
while (i < 10) {
if ((i % 2) == 0) {
x = x + i;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.135

document.write(x + " ");


}
i++;
}
11. Find the error, if any, in the following program:
var r; w = 90;
while (w>60) {
r = w 50;
switch(w) {
20 : document.write("Lower Range");
30 : document.write("Middle Range");
40 : document.write("Higher Range");
}
}
12. What is wrong with the following code fragment? What are the three distinct ways it could be changed
to remove the flow?
count = 50
while (count >= 0) {
document.write(count + " ");
count = count + 1;
}
13. What is the output of the following code?
index = 1;
do {
document.write(index + " ");
index++;
} while (index < 10);
14. What is the output of the following code?
index = 1;
do {
document.write(index + " ");
} while (index < 10);
15. Write the following code using a do loop:
var index = 1;
while (index < 10) {
document.write(index + " ");
index ++;
}
16. Write the following code using a for loop:
var index = 1;
while (index < 10) {
document.write(index + " ");
index ++;
}
17. What is the output of the following code?
var NUM=12345;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.136 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

var Rem=0, F=0, S=0, T;


do {
Rem = NUM%10;
if (Rem % 2 != 0)
F+=Rem;
else
S+=Rem;
NUM/=10;
}while (NUM>0);
T = F - S;
document.write(T);
18. What does the following program code display?
var a, b = 1, sum = 0;
while (b <= 10) {
a = b * b;
document.write(a + "<br>");
sum += a;
++b;
}
document.write("Total is" + sum);

19. Give the proper array declaration for the following:


(i) Declare an array Wages which can hold 25 values.
(ii) Declare an array Student which can hold 4 values.
(iii) Define an NArr empty array.
20. Write the value of individual array element:
(i) var c = [2, 7, 9, 6, 1, 4, 3, 8]
(ii) var p = new Array(1, 1, 3, 3, 5, 5, 7, 7)
21. Write a JavaScript program to perform the following tasks:
Read an array of 10 number.
Multiply each element of array by 5.
Display the new array.
22. Write a JavaScript program to print numbers from 1 to 10 and avoid a message C++ programming in for
statement.
23. Using Javascript, write a for loop that will print out all the multiples of 3 from 3 to 36, that is: 3 6 9 12 15
18 21 24 27 30 33 36.
24. Write a program to find the greatest common divisor of two numbers.
25. Write a for loop to find sum and average of n natural numbers, odd numbers and even numbers.
26. Write a JavaScript for loop to print out the values 1 to 10 on separate lines.
27. Write a JavaScript for loop which will produce the following output (hint: use two nested for loops).
1
22
333
4444
55555
28. Two separate arrays are declared one storing the country name and the other storing the capital. Write
a JavaScript program to extract the capital name when the user enters country name vice versa.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.137

29. Write a JavaScript for loop which sums all values between 10 and 100 into a variable called total. Assume
that total has NOT been initialized to zero.
30. Write a JavaScript that will read a sequence of positive real numbers entered by the user and will print the
same numbers in sorted order from the smallest to the largest. The user will input a zero to mark the end
of the input. Assume that at most 100 positive numbers will be entered.
31. Write a JavaScript code to find all the duplicate elements in an array and remove them.
32. Write a JavaScript for loop to print out the character set from A to Z.
33. Find the syntax error(s), if any, in the following JavaScript program :
<script language = "JavaScript">
var x y = 15;
x = 5;
for (i = 0; i < 10; ++i)
{
if (i = x)
break;
document.writ(y);
document.write(x y);
}
</script>
34. Give the output of the following JavaScript program segment:
<script language = "JavaScript">
var i, j;
for(i = 1; i <= 10; ++i)
{
for(j = 1; j <= i; ++j)
document.write(" ");
for(j = 9; j > 1; i)
{
for(j = 1; j <= i; ++j)
document.write("*");
document.write("\n");
}//for - j
}//for - i
</script>
35. Give the output for the following JavaScript program segment:
(a) for(var i = 10; i > 6; i = i2)
document.write(i + "<br>");
(b) for(var i = 5; i < 8; i )
document.write(i + "<br>");
(c) for(var i = 3, sum = 0; i < 11; i++)
sum++;
document.write(sum)
36. Find the output of the following JavaScript code:
(a) a = 1;
b = 5;
b++;
if(b == 5)
document.write("value is five");
else
document.write("value is not five");
(b) var i = 1;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.138 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

while(i < 5 )
{
document.write(i);
i = i*2;
}
(c) var total = 0, sum = 0;
for(var i = 0; i <= 10; i++)
sum = sum + i;
document.write(total);
37. What happens if you dont include an else statement with an if condition and if condition is false?
38. Consider the following JavaScript:
for (x=0; x<7; ++x)
{
y = x;
}
What will be the value of y when the loop is executed for the first time?
39. In the following JavaScript example, what is the final value of y?
for (x=0; x<5; x++)
{
if (x == 4)
continue;
y += x;
}
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.139

Objects in JavaScript
5
5.1 INTRODUCTION

We learnt about the JavaScript functions in our previous chapter, which are used to provide a uniform method
or organizing code. At its most basic level, object-oriented programming is a style of programming in which
related concepts are grouped together. If you have five data elements and three functions that manipulate
those elements, then you group those elements and functions together into a generic container known as an
object. Objects serve the same purpose for data. This is the common ground shared by all object-oriented
programming languages.
Upto this point, the only data items we have seen are simple variables declared with var. Each of these
typeless quantities can only hold a single value of some sort at a time. Objects provide the ability to hold
multiple values, so that a group of related data elements can be associated with one another.

5.2 WHAT IS AN OBJECT?


An object is a collection of properties, and a property is an association between a name and a value. A
property's value can be a function, in which case the property is known as a method.
What JavaScript calls an object is called a data structure (or class) in many other languages. As with
JavaScript functions, there are two aspects to JavaScript objects: creating them and using them. A JavaScript
object is made up of a set of component parts, which are called its properties or members. That is, JavaScript
refers to the items collected within an object as its properties.
You may also recall that JavaScript objects not only store data, they also store functions. It is useful to
keep functions that manipulate data items in a specific way with those data items themselves. These functions
are known as the methods of an object.
So, encapsulation is simply the process of wrapping up those functions and variables into different
packages called objects. The variables become known as properties of the object and the functions are then
known as methods. Properties and methods are the core elements from which objects are built. Objects are of
two types:
x User-defined Objects
x Built-in Objects
Before discussing about its types, let us discuss some basic concepts about methods and properties:

 0HWKRGV

A method is a function associated with an object, or, simply put, a method is a property of an object that is a
3.139
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.140 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

function. Methods are defined the way normal functions are defined, except that they have to be assigned as
the property of an object.
Let us say that you wanted to use an object that represented an automobile. There are several basic
functions that someone driving an automobile can perform: push the gas pedal, push the brake, steer the wheel
right and steer the wheel left. This functionality would be made available to the use of the object through its
methods:
x pushGas()
x pushBrake()
x steerRight()
x steerLeft()

Because these are methods and not functions, they could not be called by themselves. Instead, to call a
method you must prefix it with the name of the object with a simple dot-notation. For example,
myCar.steerRight()

Here, this statement calls the steerRight() method of myCar object, causing the car to turn right.

 3URSHUWLHV

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that
is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for
the attachment to objects. The properties of an object define the characteristics of the object. When methods
are called, those method usually act on some sort of data contained in the object. That data is called properties.
You access the properties of an object with a simple dot-notation:
objectName.propertyName
Or
objectName[propertyName]

Like all JavaScript variables, both the object name (which could be a normal variable) and property name
are case sensitive. You can define a property by assigning it a value. For example, let's create an object named
myCar and give it properties named make, model, and year as follows:
var myCar = new Object();
myCar.make = "Indian";
myCar.model = "HigherXLV";
myCar.year = 2016;

5.3 USER-DEFINED OBJECT

To define an object, it is better to write a function that contains all the properties and methods of that object.
You then set the properties inside the object with this statement, e.g., let us consider an employee object with
name, age and salary properties as given:
function employee(name, age, salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}

From the above example, we created a function that makes the objects. But the use of this with the
properties create a constructor. Notice the use of this to assign values to the object's properties based on the
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.141

values passed to the function. So, if you wanted to create an employee object with data, then create an object
variable using new keyword as:
var myEmployee = new employee("Sudhir Rana", 25, 35500);

This statement creates myEmployee and assigns it the specified values for its properties. Then the value
of myEmployee.name is the string "Sudhir Rana", myEmployee.age is the integer 25, and so on.
Then you could reference the object properties as follows:
empName = myEmployee.name;
empAge = myEmployee.age;
empSalary = myEmployee.salary;

You can create any number of car objects by calls to new. For example,
var Emp1 = new employee("Joyti Kalra", 28, 25700);
var Emp2 = new employee("Dinesh Singh", 30, 32800);

Otherwise, you can use a shorthand way to access this object. To do this, you use the with statement,
followed by the name of the object to be used by default when referencing properties and a block of statements
that use this object. For example,
with (myEmployee)
{
empName = name;
empAge = age;
empSalary = salary;
}

Now that the myEmployee object is being used in the with statement. JavaScript automatically assumes
the references to empName, empAge and empSalary properties to be properties of the myEmployee object.
Example Demonstrate the object to print the employee detail of above object myEmployee.
Solution Write the following code in Notepad editor and save as object01.html.
<HTML>
<HEAD>
<TITLE>JavaScript Object Example </TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Accessing element using object
function employee(name, age, salary)
{
this.name = name; // Properties
this.age = age;
this.salary = salary;
}
myEmployee = new employee("Sudhir Rana.", 25, 35500);
empName = myEmployee.name;
empAge = myEmployee.age;
empSalary = myEmployee.salary;
document.write("Employee name : " + empName + "<br>");
// You can write : myEmployee.name instead of empName
document.write("Employee age : " + empAge + "<br>");
document.write("Employee salary : " + empSalary);
</script>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.142 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

When you will open the object01.html file in a browser like IE, you will see the object properties result
as shown in Figure 5.1.

Figure 5.1 JavaScript object properties result.

Example Modify the above example for calculating a 10% of bonus using JavaScript object method.
Solution Write the following code in Notepad editor and save as object02.html.
<HTML>
<HEAD>
<TITLE>JavaScript Object Example </TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Accessing element using object
var num = new Array(10);
function employee(name, age, salary)
{
this.name = name; // Properties
this.age = age;
this.salary = salary;
this.bonus = cal_Bonus; // the cal_Salary method */
}
/*
This function is the cal_Bonus of an employee
*/
function cal_Bonus() // no argument
{
if (empSalary > 5000)
myEmployee.bonus = empSalary * (10/100);
return myEmployee.bonus;
}
myEmployee = new employee("Sudhir Rana.", 25, 35500);
empName = myEmployee.name;
empAge = myEmployee.age;
empSalary = myEmployee.salary;
document.write("Employee name : " + empName + "<br>");
// You can write : myEmployee.name instead of empName
document.write("Employee age : " + empAge + "<br>");
document.write("Employee salary : " + empSalary + "<br>");
document.write("Employee bonus : " + cal_Bonus());
</script>
</BODY>
</HTML>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.143

When you will open the object02.html file in a browser like IE, you will see the object properties result
as shown in Figure 5.2.

Figure 5.2 JavaScript object method result.

5.4 BUILT-IN OBJECTS

JavaScript has number of built-in objects. These built-in objects are available through both the client-side
JavaScript (inside the Netscape Navigator on your desktop) and through LiveWire (Netscapes server-side
application).
The JavaScript object model and its very interesting set of built-in objects, methods and functions
provide what we would expect from any modern programming language. They provide control structures,
encapsulation, functions, mathematical operations and so forth. Since JavaScript is designed to work with and
on the World Wide Web, there must also be a linkage between it and the contents of HTML pages. Built-in
objects include:
x The String Object
x The Window Object
x The Document Object
x The Location Object
x The History Object
x The Form Object
These objects are referred to as built-in because they really do not have anything to do with Web pages,
HTML, URLs, the current browser environment or anything visual.

5.4.1 The String Object


String objects are the most built-in of all the built-in JavaScript objects. This object is very useful because you
can use its methods to modify and add HTML modifications without changing the string itself. You do not even
use new when creating a string object. Any variable whose value is a string is actually a string object. One thing
to notice about this object is that you can string together any number or its methods to create multilayers of
HTML encoding. The syntax is:

object.'formatting_method'( )
For example,
"Multimedia and Web Technology".bold().blink()

would return:
<blink><b>"Multimedia and Web Technology"</b></blink>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.144 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Similarly, you call a strings method by the same dot notation you would in other objects. For example,
"Hello Friends!".italics()

this code returns "Hello Friends!", as displayed by your Web browser. Table 5.1 shows the properties and
methods of the string object.

123456789012345678901234567890121234567890123456789012345
Table 5.1 Properties and methods of the String object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description Example
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
length The number of characters in the string Hello.length()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
Example
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
anchor Converts string to an HTML anchor
123456789012345678901234567890121234567890123456789012345
big Encloses string <big>. . .</big>
hello.anchor(anchortext)
hello.big()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
blink Encloses string in <blink>. . .</blink> hello.blink()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
bold Encloses string in <b>. . .</b> hello.bold()
123456789012345678901234567890121234567890123456789012345
fixed Encloses string in <tt>. . .</tt> hello.fixed()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
fontcolor Encloses string in <font hello.fontcolor(green)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
fontsize
color=somecolor>. . .</font>
123456789012345678901234567890121234567890123456789012345
Enclose string in <font hello.fontsize(-1)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
size=somesize>. . . </font>
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
italics Encloses string in <i>. . . </i> hello.italics()
123456789012345678901234567890121234567890123456789012345
link Converts string into a hyperlink hello.link(linktext)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
small Encloses string in <small>. . .</small> hello.small()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
strike Encloses string in <strike>. . .</strike>
123456789012345678901234567890121234567890123456789012345
sub Encloses string in <sub>. . .</sub>
hello.strike()
hello.sub()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
sup Encloses string in <sup>. . .</sup> hello.sup()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
toLowerCase Converts uppercase to lowercase HELLO.toLowerCase
123456789012345678901234567890121234567890123456789012345
toUpperCase Converts lowercase to uppercase hello.toUpperCase

Example Demonstrate some of the properties and methods of string objects on the string "Multimedia
and Web Technology".
Solution Write the following code in Notepad editor and save as object03.html.
<HTML>
<HEAD>
<TITLE>JavaScript String Object Example </TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// JavaScript String object
var course = "Multimedia and Web Technology" // String
document.write("<center>"
+ "String Property and Methods".fontsize("5").fontcolor("red")
+ "</center>" + "<br>");
document.write("<hr size='4'>" + "<br>");
document.write("Original String: " + course + "<br>");
document.write("<hr size='4'>" + "<br>");
document.write("1. The length of " + " "+ course + " ' "+ " is : "
+ course.length + "<br>"); // length property
// anchor method
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.145

document.write("2. anchor : " + course.anchor("Click Me") + "<br>");


document.write("3. big() : " + course.big() + "<br>"); // big method
document.write("4. blink() : " + course.blink() + "<br>"); // blink method
document.write("5. bold() : " + course.bold() + "<br>"); // bold method
document.write("6. fixed() : " + course.fixed() + "<br>"); // fixed method
document.write("7. fontcolor() : " + course.fontcolor("green") + "<br>");
document.write("8. fontsize() : " + course.fontsize(5) + "<br>");
document.write("9. italics() : " + course.italics() + "<br>");
document.write("10. link() : " + course.link("Click Me") + "<br>"); // link method
document.write("11. small() : " + course.small() + "<br>"); // small method
document.write("12. strike() : " + course.strike() + "<br>"); // strike method
// sub and sup methods
document.write("13. sub() : " + "Water : " + "H" + "2".sub() + "O" + "<br>");
document.write("14. sup() : " + "y=mc" + "2".sup() + "<br>");
// toLowerCase method
document.write("15. toLowerCase() : " + course.toLowerCase() + "<br>");
// toUpperCase method
document.write("16. toUpperCase() : " + course.toUpperCase() + "<br>");
</script>
</BODY>
</HTML>

When you will open the object03.html file in a browser like IE, you will see the String object methods
result as shown in Figure 5.3.

Figure 5.3 Using JavaScript String Object methods.


123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.146 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

5.4.2 The Window Object


The window object is the top-level client-side object in
JavaScript. At the very foundation of the Dynamic HTML Location
Object Model is the window object. It contains all other
objects except the navigator object, which is not tied to Frames
any particular window. The window object contains
everything that is accessible to programs through the History
object model : the elements, frames, images, browser
window history and almost anything else that you might Window
need to access through the browser. Thus, the window Event
object is called a browser window.
The basic structure of the window object is shown in Document
Figure 5.4. You can see that the window object is the root
of the object model and that all other objects are contained
Screen
in the window object.

Navigator

Figure 5.4 Structure of the window object.


The window object as shown in Figure 5.5 is the top object in the JavaScript object hierarchy.

Window

History Document Frame Location

Link Form Anchor Image

Text Textarea Pathname Protocol

Password Button Port Hostname

Submit Reset

Radio Checkbox

Select Hidden

Figure 5.5 JavaScript browser and HTML objects.


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.147

From Figure 5.5,


x Every browser window that is currently open will have a corresponding window object.
x All the other objects are children of one of the window objects.
x In particular, every window is associated with a particular Web page and the HTML structure of this
page is reflected in the windows document object.
x Every window corresponds to some URL; that URL is reflected in the location object.
x Every window has a history of the previous pages that have been displayed in that window, which are
represented by the various properties of history object.
Thus, the primary browser objects, in rough order of significance, are as follows :
x window
x document
x location
x history
Table 5.2 shows the properties and methods of the window object.

123456789012345678901234567890121234567890123456789012345
Table 5.2 Properties and methods of the Window object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
defaultStatus The default message in the status bar.
123456789012345678901234567890121234567890123456789012345
document The current document contained in the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
frames An array that describes all of the frames in the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
frame A frame object.
123456789012345678901234567890121234567890123456789012345
length Reflects the number of frames in the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
name The name of the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
parent Synonymous with the name of the window. Contains the frameset tags.
123456789012345678901234567890121234567890123456789012345
self Synonymous with the name of the window and refers to the current window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
status Value appears in the windows status bar. Usually only lasts a moment
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
before overwritten by some other event.
123456789012345678901234567890121234567890123456789012345
top Synonymous with the name of the window and represents the topmost
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
window.
123456789012345678901234567890121234567890123456789012345
window Synonymous with the name of the window and refers to the current window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
location A string specifying the URL of the current document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
alert Brings up an alert dialog box (where you just click OK).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
close Closes the window.
123456789012345678901234567890121234567890123456789012345
confirm Brings up a dialog box with Yes or No button and a user-specified message.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
open Opens a new browser window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
prompt Brings up a window with user-specified text and an input box that allows
123456789012345678901234567890121234567890123456789012345
the user to type in information.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
setTimeout Sets a time in milliseconds for an event to occur.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
clearTimeout Resets value set by setTimeout.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.148 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

5.4.3 The Document Object


Every window is associated with a document object. The document object is an object of the window object.
The JavaScript Document object is the container for all HTML HEAD and BODY objects associated within the
HTML tags of an HTML document. The document object contains properties for every anchor, link and form
on that page, as well as all of the sub-elements of those elements. The document object is extremely useful
because it contains so much information about the current document and it can create HTML on-the-fly with its
write and writeln methods. Table 5.3 shows the properties and methods of document object.

123456789012345678901234567890121234567890123456789012345
Table 5.3 Properties and methods of the Document object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
alinkColor Reflects the ALINK attribute in the <body>tag.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
anchors An array listing all of the HTML anchors in the document <a name>.
123456789012345678901234567890121234567890123456789012345
anchor An anchor object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
bgColo Set the value of BGCOLOR attribute.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
cookie Set the value of Netscape cookie.
123456789012345678901234567890121234567890123456789012345
fgColor The value of TEXT attribute in <body> tag.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
forms An array listing all the forms in the document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
form A form object.
123456789012345678901234567890121234567890123456789012345
history An object containing the current browser history (links visited, number
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
of links visited and link URLs.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
lastModified The date on which the document was last modified.
123456789012345678901234567890121234567890123456789012345
linkColor Set the LINK attribute of the <body> tag.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
links An array of all HTML link in the document <a href>.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
link A link object.
123456789012345678901234567890121234567890123456789012345
location The URL of the document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
referrer The URL of the document that called the current document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
title Sets the title of the document.
123456789012345678901234567890121234567890123456789012345
vlinkColor Set the color listed in the VLINK attribute.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
clear Clears the window of all content.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
close After an open causes the string buffer to be written to the screen.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
open Begins a string to be written on the screen.
123456789012345678901234567890121234567890123456789012345
write Writes some expression to the current window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
writeln Same as write but adds a newline character at the end.

For example, to change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red"

5.4.4 The Location Object


The location object describes the URL of a document. It has properties representing the various components
of the URL, including its protocol part, its hostname part, its pathname part and its port number part, among
other properties. Table 5.4 shows some of the properties and methods.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.149

123456789012345678901234567890121234567890123456789012345
Table 5.4 Properties and methods of the Location object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
href Display the entire URL of the current page.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
protocol It retrieves the URL for IE Web page, the protocol is http:
123456789012345678901234567890121234567890123456789012345
host The hostname is the name of the host machine on which the current URL
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
is located.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
hostname The name of the host machine on which the current URL is located.
123456789012345678901234567890121234567890123456789012345
hash The hash property includes the section of the URL following the hash
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
character (#), if any.
123456789012345678901234567890121234567890123456789012345
search The search property includes the section of the URL following the question
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
mark character (?), if any.
123456789012345678901234567890121234567890123456789012345
port If a specific port is specified in the URL, its value is located in the port
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
property.
123456789012345678901234567890121234567890123456789012345
pathname This contains the path to the specified location on the host. For the IE
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
example, this is ie.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
reload It simply causes the current page to be reloaded.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
replace It causes the browser to replace the current document with the one at that
123456789012345678901234567890121234567890123456789012345
URL.

For example, the most common usage of Location is simply to use it to automatically navigate the user to
another page:
<HTML>
<HEAD>
<TITLE>JavaScript Location hostname</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
window.location="http://www.google.com"
document.write("Page hostname is " + window.location.hostname);
</script>
</BODY>
</HTML>

5.4.5 The History Object


The history object is used to refer to the history list of previously visited URLs or represents an array of URLs
visited by user. Table 5.5 shows some of the properties and methods.

123456789012345678901234567890121234567890123456789012345
Table 5.5 Properties and methods of the History object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
length It specifies how many URLs are contained in the current history object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
back() This method enables the browser to be moved backward in the history list
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
programmatically.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.150 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
forward() This method enables the browser to be moved forward in the history list
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
programmatically.
123456789012345678901234567890121234567890123456789012345
go(where) This method enables you to go to a specific place in the browser history
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
by passing an argument indicating where you want to go.

The history object is the window property, so it can be accessed by:


window.history
Or,
history

For example, the following shows different usages of history object over URL:
window.history.back(); // for previous page
window.history.forward(); // for next page
window.history.go(2); // for next 2nd page
window.history.go(-2); // for previous 2nd page

In addition, the window object is always the default object when script. Therefore, if you like you can leave
off the window object reference:
history.back();

Similarly, if you knew that you had been the part of the IE site and wanted to go back to where you were,
you would call the go() method in the following manner:
window.history.go("http://www.microsoft.com/ie");
or
history.go("http://www.microsoft.com/ie");

This would take you to the URL in the history list that contains "http://www.microsoft.com/ie".
To simulate the browser's back button, for example, you can use the History object:
<a href="javascript:history.go(-1)">Go back</a>

For example, to go to the previous URL entry in the history list. This does the same thing as the browser
back button. The following HTML code creates a back button:
<FORM>
<INPUT TYPE="button" VALUE="Go Back" onClick="history.back()">
</FORM>

5.4.6 The Form Object


The JavaScript Form Object is a property of the document object. This object is created every time JavaScript
encounters a <form>. . .</form> in our HTML documents. It contains all the information stored in your form
and can be used to submit information to a function or back to the server. Table 6.6 shows some of the
properties and methods.

123456789012345678901234567890121234567890123456789012345
Table 5.6 Properties and methods of the History object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
action Sets the HTML ACTION attribute of the <form> tag.
123456789012345678901234567890121234567890123456789012345
button A button object (<input type = button>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
checkbox A checkbox object (<input type = checkbox>).
123456789012345678901234567890121234567890123456789012345
elements An array listing all elements in a form.
123456789012345678901234567890121234567890123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.151
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
encoding The value of the ENCTYPE attribute.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
hidden A hidden object (<input type + =hidden>).
123456789012345678901234567890121234567890123456789012345
length The number of elements in the form.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
method The METHOD attribute of <form>.
123456789012345678901234567890121234567890123456789012345
password A password object (<input type + =password>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
radio A radio object (<input type = radio>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
reset A reset button object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
select A select object (<select> . . .<select>).
123456789012345678901234567890121234567890123456789012345
submit A submit button object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
target
text
The TARGET attribute of <form>.
123456789012345678901234567890121234567890123456789012345
A text object (<input type = text>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
textarea A textarea object (<textarea></textarea>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
submit() Submits the form to the location in the ACTION attribute.
123456789012345678901234567890121234567890123456789012345
reset() Used to reset the form elements to their default values.

Once you have created an object, you can address its properties and methods in the following ways:
x formName.propertyName.
x formName.methodName(parameters).
x forms[index].propertyName.
x forms[index].methodName(parameters).

Forms on the page are represented in JavaScript via the form object, and can be accessed in one of the 3
standard ways below:
document.yourformname //where yourformname is the name of your form.
document.form.yourformname
document.forms["yourformname"]

JavaScript places each form it finds in a page in an array called forms. You can access each form by either
its index in this array (with the first form at 0, the next at 1 and so on) or by its name. For example,
<form name = "thisform">
<input type = text name = "input" value = "Hello!">
</form>

By doing this you create an object called thisform which also exists as:
Document.forms[0];

You can access individual fields in a form where you can either read that field directly or send a new value
to that fieldwhich might dynamically change on the screen. To access information about this form, you can
use the following:
x formName.actionFrom the ACTION argument.
x formName.elementsTo get to the input fields.
x formName.encodingFrom the ENCTYPE argument.
x formName.methodFrom the METHOD argument.
x formName.targetFrom the TARGET argument.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.152 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

For example,
<SCRIPT type="text/javascript">
<form name = "thisForm"
action = "hello.html"
ENCTYPE = "text/ascii"
Method = "GET">
</form>
<!- - hide this code
document.form[0].method = "POST"
document.write(document.thisForm.method)
- ->
</script>

The above JavaScript will return the following:


POST

3RLQWVWR5HPHPEHU

1. JavaScript object is an entity having state and behavior (properties and method).
2. A method is a function associated with an object.
3. The JavaScript Window Object is the highest level JavaScript object which corresponds to the
web browser window.
4. The JavaScript Document object is the container for all HTML HEAD and BODY objects
associated within the HTML tags of an HTML document.
5. The location object holds information about the current URL of the browser.
6. The history object is used to refer to the history list of previously visited URLs or represents an
array of URLs visited by user.
7. The JavaScript Form Object is a property of the document object.

SOLVED EXERCISES
1. What is an object?
Ans. A JavaScript object is made up of a set of component parts, which are called its properties or members.
That is, JavaScript refers to the items collected within an object as its properties.
2. How an instance object is created in JavaScript? Write its syntax.
Ans. An instance object is created by using new keyword. The syntax is:
var objectname=new Object();
3. What is window object?
Ans. The window object represents a window in browser. An object of window is created automatically by the
browser. Window is the object of browser, it is not the object of JavaScript.
4. How many types of objects are present in JavaScript?
Ans. Two types of objects are present in JavaScript :
x User-defined objects
x Built-in Objects
5. What is method?
Ans. A method is just a function that is contained inside of an object.
6. What are properties?
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.153

Ans. When methods are called, those methods usually act on some sort of data contained in the object. That
data is called properties.
7. Name three methods of window object?
Ans. The three methods are alert(), confirm() and prompt().
8. What is JavaScript history object?
Ans. The JavaScript history object represents an array of URLs visited by the user. By using this object, you
can load previous, or forward any particular page. There are three methods of history object:
x history.back()
x history.forward()
x history.go(number): number may be positive for forward, negative for backward.
9. Define a user-defined object Customer with name, age, address and salary.
Ans. The object is:
function Customer(name, age, address, salary) {
this.name = name;
this.age = age;
this.address = address;
this.salary = salary;
}
10. Define a user-defined object Emp with EmpID, Ename, Esalary and assign the instance attributes as
A101, Amit Sinha, 25700, respectively. Also print the details of Emp object.
Ans. The object is as:
<script language="JavaScript">
var Emp = new object();
Emp.EmpID = "A101";
Emp.Ename = "Amit Sinha";
Emp.Esalary = 25700;
}
11. What is the following line called?
NewEmp = new Emp("A101", "Simral Kaushik", 26000);
Ans. NewEmp is declared as constructor object.
12. List some built-in objects in JavaScript.
Ans. Built-in objects are:
x The String Objects
x The Window Object
x The Document Object
x The Location Object
x The History Object
x The Form Object
13. What is the use of string object?
Ans. This object is very useful because you can use its methods to modify and add HTML modifications
without changing the string itself.
14. Which property of the Windows Object is used for frame handling?
Ans. frames property.
15. Explain the significance of any two predefined objects of JavaScript.
Ans. Let us consider the two predefined objects : history and document.
Location object. This object is a list that contains the locations of all the URLs that you have visited.
You can move backward and forward through the history list with history.back and history.forward. You
can also move around in the list in a relative fashion with history.go().
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.154 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Document object. This object encapsulates all JavaScript objects that correspond to the HTML
elements. It is the parent of forms, links and anchors. These objects occur as arrays and are accessed as
document.Forms[xx], document.Links[xx] and document.anchors[xx], where xx is an array index.
The document object also has several other useful properties such as background color, text color and
link colors.
16. Create a JavaScript to find the area and diameter of a circle using two different methods called CArea()
and CDiameter(). Using user-defined object methods and properties find the area and diameter of the
circle.
Ans. The code is (circle.html):
<HTML>
<HEAD>
<TITLE>Area and diameter of a circle</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function CArea(){
var area = this.radius*this.radius*3.14
return area
}
function CDiameter(){
var diameter = this.radius*2
return diameter
}
//the below creates a new object, and gives it the two methods defined earlier
function circle(r){
this.radius = r //property that stores the radius
this.area = CArea
this.diameter = CDiameter
}
var C = new circle(20)
document.write("Radius of circle: " + C.radius + "<br>")
document.write("Area of circle: " + C.area() + "<br>")
document.write("Diameter of circle: " + C.diameter() + "<br>")
</script>
</BODY>
</HTML>

REVIEW QUESTIONS
1. What is window object?
2. Explain about the document object.
3. Differentiate between location object and form object.
4. Explain any five form objects in JavaScript.
5. Which method you will use to reload a current page in JavaScript?
6. What do you call the type of JavaScript command that document.write represents?
7. What method can be used to determine the length of a variable string?
8. If document is an object, what is write in document.write?
9. What string method would you use to create a link to a new HTML document?
10. Create a new object function called player that creates the properties name, hits, strikeouts, at bats and
home runs.
11. Add a method to the above player object definition that computes the batters batting average (hits/
at bats).
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.155

Working with Control Objects


6
6.1 INTRODUCTION

JavaScript has number of control objects like button, reset, submit, checkbox, radio, select, password, text and
textarea. These control objects are used in JavaScript to handle different inputs and events. Before discussing
about the controls, let us start the general concepts of event and event handler.

6.2 EVENT

HTML forms have gradually changed that model to increase the level of interaction. A form can have a variety
of ways of accepting input, including text fields, buttons, checkboxes and multiple choice selections. One of
the primary goals of JavaScript is to localize most of its processes and perform the form validation within the
users browser. It would not be possible to actually submit an order locally, but it will be possible to make sure
that the form is properly filled out locally and thereby avoid forcing the user to redo the form. JavaScript
realizes this goal through event handlers.
Most of the time, you will be building scripts that do such things as store information, display data in a
certain format, perform some calculations or respond to user actions called events. Event handlers are JavaScript
statements (usually functions) that are called whenever something happens. Essentially, functions are stored
chunks of code that are executed at some intervaleither immediately, when the document is loaded or in
response to some triggered event. JavaScript functions can be called when a form is submitted or they can be
called whenever the user does anything to the form. When JavaScript encounters an event, it passes it to an
event handler. Event handlers are tags that point to the specific functions to be executed. All event handlers
begin with on.... Table 6.1 shows events and event handlers in JavaScript.

123456789012345678901234567890121234567890123456789012345
Table 6.1 Events and even handlers in JavaScript.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Event Event Handler To Trigger Event
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
blur onBlur In a form element, user clicks (tabs) away from element.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
click onClick In a form element or link, user clicks element.
123456789012345678901234567890121234567890123456789012345
change onChange In a form text, text area or select object, user change value.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
focus onFocus In a form element, user clicks (tabs) to element.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
load onLoad It happens when page is loaded.
123456789012345678901234567890121234567890123456789012345
mouseover onMouseOver It happens when mouse is passed over links or anchors.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
select onSelect In a form, user selects input field.
123456789012345678901234567890121234567890123456789012345
submit onSubmit In a form, user submits a form (clicks the Submit button).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
unload onUnload It happens when user leaves the page.
3.155
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.156 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

6.3 EVENT HANDLER

In the previous section, we learnt about the events and event handlers. The event handler is a command that
is used to specify actions in response to an event. Let us look at an example of how you might add an even
handler to your existing HTML code. The syntax is:
<TAG eventHandler = "JavaScript code">

Here,
x the TAG is some HTML tag.
x eventHandler is any of the event handlers as shown in Table 6.1.
x the JavaScript code can be any valid JavaScript code but is usually a call to a function that you
loaded earlier in the document.
For example,
<A HREF= "#" onClick = "alert('Yes! It works!');">Click here for a message!</A>

From the above code, when you click the link, a dialog box displays the text, followed by an OK button for
you to click to return to the page. Also,
x No URL is found in the HREF attribute. When you click on the link, not only is the onClick activated
but the browser attempts to go to the location specified in the HREF. In this case, you are using this link
for its onClick event handler and not its hypertext reference. An alternative would be to type:
<a href = "javascript:alert('Yes! It works!');">Click here</a>

x onClick has mixed case. Although HTML is not case sensitive, JavaScript is. This is important to
remember when you are creating functions and variables.
x alert(.) is the standard function for bringing up an alert dialog box on the screen. Notice how this
function and all JavaScript functions, behave similarly to Java in that they use parentheses to contain
their arguments. In this case, the argument is the string 'Yes! It works!'
x The JavaScript code in quotation marks"alert('Yes! It works!');"ends in a semicolon.
Above all JavaScript event handler does not work independently, it must use some HTML object like
button, checkbox, radio button, submit, etc. These HTML objects are called control objects.

6.4 BUTTON OBJECT

The button object is a new type of INPUT tag that allows you to create general purpose buttons in a form. You
can use these buttons to activate any function or to open a new URL or perform any other action that
JavaScript can initiate. The button object syntax is:

<INPUT
TYPE = "button"
NAME = "nameInside"
VALUE = "nameOnButton"
[onclick = "handlerText"]>

This is an extremely useful object and you will probably find yourself using this often to create buttons to
run scripts, open new windows or even cause the browser to leave your Web site altogether. You must use this
inside a set of <FORM>. . . </FORM> tags.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.157

You access a buttons properties and methods in the following ways:


x buttonName.propertyName.
x buttonName.methodName(parameters).
x formName.elements[index[.propertyName.
x formName.elements[index].methodName(parameters).

RQ&OLFN (YHQW

The onClick event handler is activated by a click on a form element. This can mean a radio or check button, but
also submit, reset, or a user-defined button. For example,
<script>
function Hello()
{
alert("I am a JavaScript programmer!")
}
</script>
<form>
<input type="button" name="test" value="Click me" onclick="inform()">
</form>

From the above script, the function hello() is invoked when the user clicks the button.
Example Write a JavaScript code to demonstrate event handler for an alert message.
Solution Write the following code in Notepad editor and save as event01.html.
<HTML>
<HEAD>
<TITLE>JavaScript Event Handler</TITLE>
<SCRIPT type="text/javascript">
<!-- hide me from other browsers
function dontclickme()
{
alert("Please don't click me");
}
// end hiding from other browsers -->
</SCRIPT>
</HEAD>
</BODY>
<FORM METHOD = "POST" ACTION = "mailto:gbsahoo@yahoo.com">
<INPUT TYPE = "button" NAME = "mycheck" VALUE = "Click Me" onClick = "dontclickme()">
</FORM>
</BODY>
</HTML>

Open the event01.html file in a browser like IE, you will see the event handler result as shown in Figure
6.1 on the next page.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.158 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Figure 6.1 Event handler in JavaScript.


From the above code,
x Notice that the onClick event handler for the button is declared using HTML attribute onClick =
"dontclickme()", which tells JavaScript that when this button is pressed the function dontclickme
should be called.
x The name of the event handler in the HTML statement that created the button matched the name of a
JavaScript function in the SCRIPT block. Now try the following experiment. Change the handler
declaration from as:
onClick = "dontclickme()"
to
onClick = "noclickme()"

and then read that file into your browser. You will notice that the initial appearance of the HTML page
is exactly as before. No errors have been reported.
x If you attempt to click the button labeled "Click", your browser reports and error and the alert dialog
box appear as shown in Figure 6.1. This is dynamic binding at work.
From above event handler declaration looks exactly like ordinary HTML attributes. Each attribute name
begins with the word on and is followed by the event name (Table 6.1), so that onClick is the attribute that
would be used to declare an event handler for the click event. The full declaration of an event handler looks
like :
onEvent = "javascriptcode"

The value of the attribute is a set of JavaScript code. The code may be included literally (known as inline
JavaScript) or it may reference a JavaScript function. We can completely remove the dontclickme() function of
previous example Event01.html and write the button statement as:
<INPUT TYPE = "button" NAME = "mycheck" VALUE = "Click"
onClick = "alert('Please dont click me');">

Example Write a JavaScript code with function using a button form element.
Solution Write the following code in Notepad editor and save as event02.html.
<HTML>
<HEAD>
<TITLE>JavaScript button object</TITLE>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.159

<SCRIPT type="text/javascript">
<!-- hide me from other browsers
function hello()
{
alert("Yes! You pushed the button");
}
// end hiding from other browsers -->
</SCRIPT>
<FORM>
<h1>Click below for an alert!</h1>
<INPUT TYPE = "button" NAME = "alertbutton" VALUE = "Click Me!" onClick = "hello()">
</FORM>
</BODY>
</HTML>

Open the event02.html file in a browser like IE, you will see the button result as shown in Figure 6.2.

Figure 6.2 Using a button form element in JavaScript.

Let us see another example that adds the onclick event inside form radio buttons:
<input type="radio" name="C1" onclick="document.bgColor='lightblue'">Light Blue
<input type="radio" name="C1" onclick="document.bgColor='lightyellow'">Light Yellow
<input type="radio" name="C1" onclick="document.bgColor='lightgreen'">Light Green

The complete HTML code is (change.html):


<html>
<head>
<title>Coloring background page</title>
</head>
<body bgcolor="#FFFFFF">
<form method="POST">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr> <td width="33%">
<p><input type="radio" name="C1" onclick="document.bgColor='lightblue'">
Light Blue</p></td>
<td width="33%">
<p><input type="radio" name="C1" onclick="document.bgColor='lightyellow'">
Light Yellow</p></td>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.160 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<td width="34%">
<p><input type="radio" name="C1" onclick="document.bgColor='lightgreen'">
Light Green</p></td>
</tr>
</table>
</form>
</body>
</html>

Open the change.html file in a browser like IE, you will see the onClick event changes the background
color of page in three different colors shown in Figure 6.3.

Figure 6.3 onClick event with radio buttons.

6.5 CHECKBOX OBJECT

The checkbox object is created inside a form and appears as a small box with or without a mark (usually an x)
inside it. Think of a checkbox as an On/Off switch.
A user can flip this switch on or off by clicking his mouse inside this box. Clicking here can also trigger an
onClick event on your script. The syntax for checkbox object is:
<INPUT = "checkbox"
NAME = "checkboxName"
VALUE = "checkboxValue"
[CHECKED}
[onClick = "handlerText"]
textToDisplay

Accessing the properties of this object is very similar to accessing the properties of the button object. The
properties are:
x CHECKED indicates true or false to specify if the checkbox is checked.
x DEFAULT indicates whether or not the checkbox was marked checked upon page load.
x NAME indicates the name of the checkbox.
x VALUE indicates the value that is returned by the form if the checkbox is checked. This default is On.

Example Write a JavaScript code with function using a checkbok object in a form.
Solution Write the following code in Notepad editor and save as event03.html.
<HTML>
<HEAD>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.161

<TITLE>JavaScript checkbox object</TITLE>


<SCRIPT type="text/javascript">
<!--
function mystatus()
{
(document.theForm.theCheckbox.checked) ?
alert("The box is checked") :
alert("The box is not checked! Oh no!")
}
<!-- end script -->
</SCRIPT>
<FORM NAME = "theForm">
<h2>Click the checkbox button!</h2>
<INPUT TYPE = "checkbox" NAME = "theCheckbox" VALUE = "myValue" onClick =
"mystatus()">
</FORM>
</HTML>

Open the event03.html file in a browser like IE, you will see the checkbok click result as shown in Figure
6.4.

Figure 6.4 Using a checkbox object form element in JavaScript.


Example Write a JavaScript function which can be shared by several event handlers. Note that each
time the function will display different messages on the alert dialog box.
Solution Write the following code in Notepad editor and save as event04.html.
<HTML>
<HEAD>
<TITLE>JavaScript Function Shared by several Event Handlers</TITLE>
<SCRIPT type="text/javascript">
<!--
function donteventme(str) // generic diffident handler
{
alert("Please dont " + str + " me");
}
<!-- end script -->
</SCRIPT>
</HEAD>
</BODY>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.162 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<FORM METHOD = "POST" ACTION = "mailto:gbsahoo@yahoo.com">


<BR>No
<INPUT TYPE = "checkbox" NAME = "mycheck" VALUE = "Click" onClick =
"donteventme(click)">
<SELECT NAME = "myself" onChange = "donteventme('change')">
<OPTION> <SELECTED>Nope</OPTION>
<OPTION>Not Me</OPTION>
<OPTION>Not Way</OPTION>
</SELECT>
</FORM>
</BODY>
</HTML>
Open the event04.html file in a browser like IE, you will see the checkbok click result as shown in Figure
6.5.

Figure 6.5 Event handler checkbox object form element in JavaScript.

6.6 RADIO OBJECT

This object allows a user to make a choice of a single selection from many. Usually this is a list of related items
from which you wish the user to pick only one choice.
The radio object is very similar to the checkbox object, except that a series of radio objects with the same
NAME attribute toggle all of the radio buttons off except for the one that was picket. In other words, when you
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.163

click one radio button in a group of related buttons, all of them will be off except for the one you clicked. The
syntax is as:
<INPUT
TYPE = "radio"
NAME = "radioName"
[CHECKED]
[onClick = "handlerText"]>
textToDisplay

Accessing information from the radio object is slightly different than that from the checkbox object. Since
all of the radio buttons of a given group have the same NAME attribute, you access individual radio buttons by
adding an index value to the NAME. The format for doing this is as follows:
x radioName[index1].propertyName.
x radioName[index1].methodName.
x formname.elements[index2].propertyName.
x formname.elements[index2].methodName.

You can click a specific radio button in JavaScript by using the following:
radioName[index1].click

Example Write the code to demonstrate a radio button object.


Solution Write the following code in Notepad editor and save as event05.html.
<HTML>
<HEAD>
<TITLE>JavaScript Function for Radio Object</TITLE>
</HEAD>
</BODY>
<FORM NAME = "game">
<INPUT TYPE = "text" NAME = "output" SIZE=15>
<INPUT TYPE = "radio" NAME = "choice" VALUE = "rock"
onClick = "game.output.value = 'IDBI Bank' ">The IDBI
<INPUT TYPE = "radio" NAME = "choice" VALUE = "sissors"
onClick = "game.output.value = 'ICICI Bank'">The ICICI
<INPUT TYPE = "radio" NAME = "choice" VALUE = "paper"
onClick = "game.output.value = 'HDFC Bank'">The HDFC
</FORM>
</BODY>
</HTML>

Open the event05.html file in a browser like IE, you will see the radio button click result as shown in
Figure 6.6.

Figure 6.6 Event handler radio button object form element in JavaScript.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.164 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

6.7 MANIPULATING TEXT FIELDS

In JavaScript all the text fields are managed through the HTMLs INPUT tag. The text-based input fields is in an
HTML form and shows how you can use JavaScript to enhance these input fields usefulness to you as a script
writer and few of them are:
x The password Object
x The text Object
x The textarea Object

6.7.1 The Password Object


The password input field in a form is very useful for those times when you need to create a logon screen and
keep the password of that logon hidden form view or form being printed by some malicious user who sees the
login screen. Any time you want the information hidden from sight as a user types that information on the
screen, use the password input field. The syntax is:
<INPUT
TYPE = "password"
NAME = "passwordName"
SIZE = integer
[VALUE = "textValue"]

We can access the properties and methods of this object by using the following :
x passwordName.propertyName.
x passwordName.methodName(parameters).
x formname.elements[index].propertyname.
x formname.elements[index].methodname(parameters).

The password object uses the focus, blur and select event handlers as methods. Let us say you want to
check the validity of a password before a user actually sends it back to the server for a login. You can create a
function that checks the password and notifies the user if he entered an invalid password.

Example Write a checkpass() function to check the password on the form using JavaScript.
Solution Write the following code in Notepad editor and save as event06.html.
<HTML>
<HEAD>
<TITLE>JavaScript password object</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkPass(mypass)
{
if (notpass)
{
alert("You have entered an invalid password. Try again.");
mypass.focus();
mypass.select();
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
</BODY>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.165

<FORM onSubmit = "checkPass(this)">


Enter password
<INPUT TYPE = "password" NAME = "mypass">
</FORM>
</BODY>
</HTML>

Open the event06.html file in a browser like IE, you will see the password object result as shown in
Figure 6.7.

Figure 6.7 The password object form element in JavaScript.

6.7.2 The text Object

The text input field in an HTML document is your workhorse for inputting many types of information. Most
other types of input in forms are derivations of this kind of input.
The text input field is simply a small box of a set size that contains a cursor when you click it. It allows a user
using the form to type in information such as a name, a date or any other kind of information. If the text a user
types is too long for the box, it scrolls to the left to accommodate the additional text. In JavaScript, this field
serves a new and exciting purpose. Not only can a user using the form enter information into this field, but the
script itself can enter information as well. The syntax is:
<INPUT
TYPE = "text"
NAME = "textName"
VALUE = "textValue"
SIZE = integer
[onBlur = "handlerText"]
[onChange = "handlerText"]
[onFocus = "handlerText"]
[onSelect = "handlerText"]

For example,
<FORM>
<INPUT TYPE = "text" NAME = "todaysdate" value = " " SIZE = "5" onBlur = "getDate()"
onChange = "setDate()" onFocus = "alert('Set the date')"
onSelect = "alert('Really change?')">
</FORM>

The text object properties reflect the information you provide in the tag when you create the object. Table
6.2 shows text object properties, methods and event handlers.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.166 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

123456789012345678901234567890121234567890123456789012345
Table 6.2 Text objuect properties methods and event handlers.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Example Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
defaultValue myText.defaultValue The value of the input tag at page load time.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
name myText.name The NAME argument.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
value formName.elements[0].value The VALUE argument.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Example
123456789012345678901234567890121234567890123456789012345
Description

123456789012345678901234567890121234567890123456789012345
focus myText.focus() Equivalent to clicking this field.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
blur myText.blur()
123456789012345678901234567890121234567890123456789012345
Equivalent to clicking another field after
using this one.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
select myText.select()
123456789012345678901234567890121234567890123456789012345
Equivalent to dragging the mouse across
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
all the text in this fieldselecting it.

123456789012345678901234567890121234567890123456789012345
Eent Handler Example Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onBlur <input type = text Runs "alert()" when focus leaves this field.
123456789012345678901234567890121234567890123456789012345
onBlur = "alert('blur!')">
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onChange <input type = text
123456789012345678901234567890121234567890123456789012345
onChange = "alert('changed') ">
Runs "alert()" if the text has changed when
focus leaves this field.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onFocus <input type = text Runs "alert()" when user clicks in (or
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onFocus = "alert('start typing!')"> otherwise gives focus to) this field.
123456789012345678901234567890121234567890123456789012345
onSelect <input type = text Runs "alert()" once some text in this field is
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onSelect = "alert('text selected!')"> selected.

Example Write a JavaScript for text object event handler to demonstrate the text object. That is,
using event handler pass information to a text field.
Solution Write the following code in Notepad editor and save as event07.html.
<HTML>
<HEAD>
<TITLE>JavaScript text object</TITLE>
<SCRIPT type="text/javascript">
<!--
var num = 0;
function showLink(num)
{
if (num == 1) {
document.forms[0].elements[0].value = "one";
}
if (num == 2) {
document.forms[0].elements[0].value = "two";
}
if (num == 3) {
document.forms[0].elements[0].value = "three";
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.167

<INPUT TYPE = text size = 60>


</FORM>
<a href = "#" onMouseOver = "showLink(1)">one</a><br>
<a href = "#" onMouseOver = "showLink(2)">two</a><br>
<a href = "#" onMouseOver = "showLink(3)">three</a><br>
</BODY>
</HTML>

Open the event07.html file in a browser like IE, you will see the text object result as shown in Figure 6.8.

Figure 6.8 The text object form element in JavaScript.

6.7.3 The textarea Object

When you need a user to input more than just one line of text in a form you use the textarea input type. This is
the case if you are providing to the user an e-mail feedback form and want to allow space for the user to type in
a lengthy note. The syntax is:
<TEXTAREA
NAME = "textareaName"
ROWS = integer
COLS = integer
WRAP = on|off|physical|virtual
"onBlur = "handlerText"]
"onChange = "handlerText"]
"onFocus = "handlerText"]
"onSelect = "handlerText"]
TextToDisplay
</TEXTAREA>

A textarea object uses essentially the same attributes, methods and properties as does the text object. You
can use provide default text to display in this field by adding text between the TEXTAREA /TEXTAREA tags.
Example Write a JavaScript for textarea object event to check either a text contains a character f or
not using a checkF() function.
Solution Write the following code in Notepad editor and save as event08.html.
<HTML>
<HEAD>
<TITLE>JavaScript textarea object</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkF()
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.168 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

{
var inputstr = document.myform.mytarea.value;
var lowerstr = inputstr.toLowerCase();
if (lowerstr == " ")
{
return;
}
if (lowerstr.indexOf("f") >= 0)
{
alert("You have got an F in there!");
}
else
{
if (lowerstr.length <= 20)
{
alert("Nice try, but too brief");
}
else
{
alert("Congratulations!");
}
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<P>The novel <I>Madding Crowd</I> does not contain a single &quotf&quot.<BR>
Enter your new text given below :</P>
<HR>
<FORM NAME = "myform" METHOD = "POST" ACTION = "mailto:gbsahoo@yahoo.com">
<TEXTAREA NAME = "mytarea" ROWS = "4" COLUMNS = "80" onBlur = "checkF()">
</TEXTAREA>
</FORM>
<HR>
</BODY>
</HTML>

Open the event08.html file in a browser like IE, you will see the textarea object result as shown in Figure
6.9.

Figure 6.9 The textarea object element in JavaScript.


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.169

From the above code,


x If you type or click in the textarea nothing happens.
x When you leaves the textarea and click elsewhere, a blur event is generated and the handler function
checkF() invoked.
x This function gets the contents of the textarea into a local variable named inputstr and then uses one
of the string functions to convert it to lowercase.
x This saves a little time, as the functions would not have to test for the presence of both f and F.
x The new lowercase string lowerstr is tested against the empty string.
x If there is no text, the function returns without complaint.
Example Write a JavaScript program to demonstrate a form using radio object and checkbox object
for an insurance whether the payment options either cheque or cash. Note that the option
will be coded with radio object.
Solution Write the following code in Notepad editor and save as event09.html.
<HTML>
<HEAD>
<TITLE>Testing Condition</TITLE>
<SCRIPT type="text/javascript">
<!--
function insurance_ok()
{
var iscash = document.myform.payment[1].checked;
var isins = document.myform.insurance.checked;
var ok = null;
if (iscash == true && isins != true)
{
ok = confirm("Do you want insurance?");
if (ok == true)
{
document.myform.insurance.checked = true;
}
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME = "myform" METHOD = "POST" ACTION = "mailto:gbsahoo@yahoo.com">
<STRONG>Payment Options</STRONG><BR>
<HR>
<INPUT TYPE = "radio" NAME = "payment" VALUE = "1" CHECKED
onClick = "insurance_ok()"> Personal Cheque
<INPUT TYPE = "radio" NAME = "payment" VALUE = "2"
onClick = "insurance_ok()"> Cash
<HR>
<INPUT TYPE = "checkbox" NAME = "insurance" VALUE = "Ins"> Insurance?
</FORM>
<HR>
</BODY>
</HTML>

Open the event09.html file in a browser like IE, you will see the a test condition result as shown in Figure
6.10 on the next page.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.170 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Figure 6.10 A testing condition using radio and checkbox object.

6.8 VALIDATING AND SUBMITTING A FORM

As we have discussed number of objects in our previous sections, all these are used on the Web to display text
or select options on form. There are other two form-based objects, submit and reset, which are accompanied
with an example of a simple mail-in form that checks the input before it is sent back to you.

6.8.1 The Submit Object

The submit button was originally intended in HTML to be the final button a user would click to set a form back
to the server. It would submit information, set feedback or present a structured request for new information.
With JavaScript, you can now use this button to also send all of the information collected in a form to another
window on your browser or to the same window itself, which causes the contents of the window to change in
some way. An example of this is changing the background color of the window based on the users preference
on a form. The syntax is:
<INPUT
TYPE = "submit"
NAME = "submitName"
VALUE = "buttonText"
[onClick = "handlerText"]>

From the above syntax, you can access this objects properties and methods by the following:
x submitName.propertyName.
x submitName.methodName(parameters).
x formName.elements[index].propertyName.
x formName.elements[index].methodName(parameters).

When you click a submit button, it always loads a new pageeven if that page is the same page you were
already on. This is useful in that you can use a form to change attributes of the current page and see them
change when you submit the form. The submit object uses the onClick event handler and can be clicked by
using the submitName.click method.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.171

6.8.2 The Reset Object

The reset button allows a user to completely reset a forms input field to their defaults. The syntax is:
<INPUT
TYPE = "reset"
NAME = "resetName"
VALUE = "buttonText"
[onClick = "handlerText"]>

From the above syntax, you can access this objects properties and methods by the following:
x resetName.propertyName.
x resetName.methodName(parameters).
x formName.elements[index].propertyName.
x formName.elements[index].methodName(parameters).

The reset button uses the same onClick event handler and click method as the submit object.
Example Write a JavaScript program to demonstrate the submit and reset button using three text
input values.
Solution Write the following code in Notepad editor and save as event10.html.
<HTML>
<HEAD>
<TITLE>JavaScript submit and reset objects</TITLE>
<SCRIPT type="text/javascript">
<!--
function first()
{
if (document.forms[0].elements[0].value == " ")
{
alert("Please put a name in the first field!");
}
}
function second()
{
if (document.forms[0].elements[2].value.length < 10)
{
alert("Please input at least 10 characters");
}
}
function third()
{
if (document.forms[0].elements[4].value == "No")
{
alert("Please change the third field value!");
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<center>
<h2>Enter the field values</h2>
</center>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.172 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<HR>
<INPUT TYPE = "text" NAME = one VALUE = " "> Input your name (any text)
<INPUT TYPE = "button" NAME = check VALUE = checkme onClick = "first()"><p>
<INPUT TYPE = "text" NAME = two> Input at least 10 characters
<INPUT TYPE = "button" NAME = checktwo VALUE = checkme onClick = "second()"><p>
<INPUT TYPE = "text" NAME = three VALUE = "No"> Change this to something else
<INPUT TYPE = "button" NAME = three VALUE = checkme onClick = "third()"><p>
</FORM>
</BODY>
</HTML>

Open the event10.html file in a browser like IE, you will see the working of submit and reset buttons
result as shown in Figure 6.11.

Figure 6.11 JavaScript submit and reset object.


From the above example, you can see how an input of type button was used in place of an input of type
submit. In a real-world script, you could either use a button input type with an onClick event handler which
would then run a check on that field or you could keep the submit button and use an onSubmit event handler
to run checks on all of the input fields at once. The difference here is that when you use onClick and the button,
you can be more specific as to which area you are checking.

6.9 SELECTION OR SCROLLING USING SELECT OBJECT

When we design interactive form, the viewers probably also find our requests easier to understand in multiple
choice format. Understanding this aspect of form design, we have probably used radio buttons and checkboxes.
These are excellent devices for presenting a limited or fixed number of choices. But when we present the viewer
with a large number of choices, we use the SELECT object. This enables us to present a large list without
cluttering up our page. A good use would be geographical lists, such as states or countries in address forms.
Remember, SELECT is an element within a form, so it must be between the <FORM>. . . </FORM> tags.
The syntax is:
<SELECT
NAME = "selectName"
[SIZE = "integer"
[MULTIPLE]
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.173

[onBlur = "handlerText"]
[onChange = "handlerText"]
[onfocus = "handlerText"]
<OPTION VALUE = "optionValue" [SELECTED]> textToDisplay
[ . . . <OPTION> textToDisplay]
</SELECT>

From the above syntax:


x The SELECT tag has one required attribute : NAME. This name and a value associated with the selected
OPTION element are sent to the server when a form is submitted. The NAME attribute can also be used
as an anchor. An optional attribute is SIZE, which tells the browser how many options to display.
x MULTIPLE is an optional attribute of SELECT, which changes the list so that one or multiple items can
be selected by the user. This type of list is called a scrolling list.
x The SELECT tag always contains two or more OPTION elements. This is where you list the items for
the user to select. Each OPTION has a text property that is displayed in the select box.
x There is also an associated VALUE property that is sent to the server when the form is submitted along
with the name of the SELECT tag.
x The last attribute of OPTION is itself optional. The SELECTED attribute is means to have one of the
items in your selection list to be the default when the page is displayed.
Like other objects in JavaScript, the SELECT object responses to events.

6.9.1 onLoad Event

The onLoad event handler is used to call the execution of JavaScript after a page, frame or image has completely
loaded. The onLoad events for the body, window and document objects are the same. They fire after all
objects in the DOM (Document Object Modelling) hierarchy have finished loading and the document object
has been built up. Let us look at three different possibilities onload event:
x <body onload="hello()">

Here, the execution of the code will begin after the page has loaded.
x <frameset onload="hello()">

Here, the execution of the code will begin after the current frame has loaded.
x <img src = "nation.gif" onload="hello()">

Here, the execution of the code will begin after the image has loaded.
Let us take another example
<html>
<head><title>Onload event example</title>
</head>
<body onload="alert('This page has finished loading!')">
Welcome to my home page
</body>
</html>

Example Write a JavaScript program to demonstrate the onload event for the body element to change
the background color of web page.
Solution Write the following code in Notepad editor and save as onloada.html.
<HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.174 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<head>
<script type="text/javascript">
function bgcolor() {
alert ("The document has been loaded.");
document.body.style.backgroundColor = "aqua";
}
</script>
</head>
<body onload="bgcolor()">
</body>
</HTML>

When the above scripts executed, it first shows an asert message and then the background color of the
body will be changed.

6.9.2 onUnLoad Event

The onUnLoad executes JavaScript immediately after someone leaves the page. A common use (though not
that great) is to thank someone as that person leaves your page for coming and visiting. onUnLoad occurs
when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser
window, etc.) For example,
<head>
<script type="text/javascript">
function OnUnLoadMe() {
alert ("The current document will be unloaded!");
}
</script>
</head>
<body onunload="OnUnLoadMe()">
<b>Close this window or press F5 to reload the page.</b>
</body>

The above code will display an alert window with message "The current document will be unloaded!",
when leaving the page.

6.9.3 onChange Event

onChange event is raised when the text in a select, text, or textarea form item is altered by the user. The
onChange is the most common event that you monitor in SELECT. It looks for change from one selection to
another. When the event is triggered, your code executes.
For example, let us take the countries in world. When we change a country selection from India to
Bangladesh, then onChange triggers a JavaScript function that changes the currency type from Rupees to
Taka. However, if you did not change the selection, the event would not trigger.
Example Write a JavaScript program to demonstrate the onChange event of SELECT object for
above problem specification.
Solution Write the following code in Notepad editor and save as event11.html.
<HTML>
<HEAD>
<TITLE>JavaScript onChange event of SELECT object</TITLE>
<SCRIPT type="text/javascript">
<!--
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.175

function changeCurrency(form)
{
form.currency.value=form.country.options[form.country.selectedIndex].value
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<P>Demonstrating <I>onChange</I> event :</P>
<B>Select your country</B><BR>
<SELECT NAME = "country" onChange = "changeCurrency(this.form)">
<OPTION VALUE = "Indian Rupees">India
<OPTION VALUE = "Bangladeshi Taka">Bangladesh
<OPTION VALUE = "US Dollars">USA
<OPTION VALUE = "UK Pound">United Kingdom
</SELECT>
<P><B>Prices are displayed in : </B><BR>
<INPUT TYPE = "text" NAME = "currency">
</FORM>
</BODY>
</HTML>

Open the event11.html file in a browser like IE, you will the onChange event of SELECT object result as
shown in Figure 6.12.

Figure 6.12 onChange event of SELECT object.

6.9.4 onBlur Event

The onBlur event is a good way to verify proper selections. This event looks for when the focus is no longer
on the SELECT object. In other words, it looks for when you click somewhere other than the current element.
When the event is triggered, you could execute a verification function. Although you can use the onBlur event
to verify selections, using onBlur might ensure the viewers choice. This is because the onBlur event triggers
JavaScript code even if a change has not occurred. In other words, when the item loses focus, the onBlur event
is raised.
Verification is not always simply an either/or choice. For example, you might have a selection with some
uncommon, but acceptable answers. This might be an unusual color for a piece of merchandise. For this
circumstance, you might verify that this is indeed the correct selection, even if the user made no change in his
selection.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.176 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Example Write a JavaScript program to demonstrate the onBlur event of SELECT object. The script
will select an option and display appropriate message in the alert box.
Solution Write the following code in Notepad editor and save as event12.html.
<HTML>
<HEAD> <TITLE>JavaScript onBlur event of SELECT object</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkEggs(form)
{
form.eggs.value=form.quantity.options[form.quantity.selectedIndex].value
// document.write(form.eggs.value);
var qty = form.quantity.selectedIndex;
if (qty == 0)
{
alert("Order generally placed as a dozen!");
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<P>Demonstrating <I>onBlur</I> event. After you select a quantity, the number on-hold
is not updated until you click somewhere else.</P>
<B>Select the quantity</B><BR>
<SELECT NAME = "quantity" onBlur = "checkEggs(this.form)">
<OPTION VALUE = "6">Half dozen
<OPTION VALUE = "12">Dozen
<OPTION VALUE = "24">Two dozen
</SELECT>
<P><B>We are holding this many eggs for you :</B><BR>
<INPUT TYPE = "text" NAME = "eggs">
</FORM>
</BODY>
</HTML>

Open the event12.html file in a browser like IE, you will get the onBlur event of SELECT object result as
shown in Figure 6.13.

Figure 6.13 onBlur event of SELECT object.


3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.177

6.9.5 onFocus Event

The onFocus is just opposite of onBlur. The onFocus is an excellent way to assist the viewer in completing
your form. It looks for the viewer moving the cursor to the SELECT element and then triggers code prior to any
entry by the viewer.
For example, each question in your form can include particular instructions that assist the viewer in making
a proper selection. When onFocus is triggered, your code could display in a separate window or frame the
instructions related to that question. Or if you require a numeric answer to be calculated, why not pop up a
calculator in a new window ? Let us start an example for demonstrating the onFocus event.
Example Write a JavaScript program to demonstrate the onFocus event of SELECT object.
Solution Write the following code in Notepad editor and save as event13.html.
<HTML>
<HEAD>
<TITLE>JavaScript onFocus event of SELECT object</TITLE>
<SCRIPT type="text/javascript">
<!--
function dispAns(form)
{
var opt = form.answer.selectedIndex;
if (opt == 2)
{
alert("Delhites forget metro trains run on two tracks.");
}
}
var result = 0;
function callCalculator(form)
{
if (result == 0)
{
result = 1;
alert("You are focused");
}
}
<! end scripts >
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<P>Demonstrating <I>onFocus</I> event.</P>
<B>Select the quantity</B><BR>
<P><B>DMRC railroad track is ordered for three sections of track. The first is 12 kilometers
long. The second is 24 milometers long and the third is 10 kilometers long. How many
kilometers of track needs to be order to complete construction ?
</B></P>
<P><B>What is your answer : </B></P>
<SELECT NAME = "answers" onFocus = "callCalculator(this.form)" onBlur =
"dispAns(this.form)">
<OPTION VALUE = "12">22
<OPTION VALUE = "24">28
<OPTION VALUE = "10">98
</SELECT>
</FORM>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.178 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Open the event13.html file in a browser like IE, you will see the onFocus event of SELECT object result
as shown in Figure 6.14.

Figure 6.14 onFocus event of SELECT object.


Example A web page consists of three objects like text field, textarea (multiple lines) and a SELECT
object with multiple values as shown below:

Write the code using JavaScript to display appropriate message on the windows status bar
as shown in the above figure. For example, if you
x click on text box, then it will display,
You have placed the cursor in the one-line text field!
x click on textarea box, then it will display,
You have placed the cursor in multipleline text field!
x click on option box, then it will display,
You have placed the cursor in Field of choice field!
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.179

Solution Write the following code in Notepad editor and save as onfocus.html.
<html>
<head>
<title>OnFocus example</title>
<SCRIPT type="text/javascript">
<!--
function message(field){
window.status="You have placed the cursor in the " + field + " field!"
}
//-->
</script>
</head>
<body>
<form>
<input type="text" onFocus="message('one-line text')">
<textarea rows=4 cols=20 wrap=virtual onFocus="message('multipleline text
')"></textarea>
<select onFocus="message('Field of choice')">
<option>Hill side
<option>River side
<option>Ocean side
<option>Heaven side
</select>
</form>
</body>
</html>

Example A web page used multiple objects with an alert window for Send button as shown below:

Hints. For Send Button:


<input type="submit" value="Send" onClick="Display('Send Button')">
Write the complete HTML code using a JavaScript function Display() to display appropriate
message for other objects.
Solution Write the following code in Notepad editor and save as changeall.html.
<html>
<head>
<title>onClick event with multiple objects</title>
<SCRIPT type="text/javascript">
<!--
function Display(element){
alert("You clicked the " + element + " element!")
}
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.180 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

//-->
</script>
</head>
<body>
<form>
<input type="radio" name="Radio" onClick="Display('Radio Button1')">Option 1<br>
<input type="radio" name="Radio" onClick="Display('Radio Button2')">Option 2<br>
<input type="checkbox" onClick="Display('Check Button')">Check Button<br><br>
<input type="submit" value="Send" onClick="Display('Send Button')">
<input type="reset" value="Reset" onClick="Display('Reset Button')">
<input type="button" value="Personal" onClick="Display('Personal Button')">
</form>
</body>
</html>

6.10 TIMING EVENTS

With JavaScript, it is possible to execute some code at specified time intervals. This is called timing events. It
is very easy to time events in JavaScript.

VHW7LPHRXW  0HWKRG

The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
It allows code to be executed a set time after some trigger, such as when the page has loaded or a button is
pressed. This post looks at how to trigger events after a set time with Javascript and also how to clear the
timeout. The syntax is:
setTimeout("expression", delaytime)

Here, "expression" is the function/statement you want delayed, and delaytime is the delay time, in
milliseconds. Note that to get "1" second, we used "1000". (1 millisecond*1000) equals 1 second.
For example,
<input type="button" value="click me" onclick="setTimeout('window.alert(\'Hello!\')', 2000)" />

Here, the above code pop up an alsert box 2 seconds after the button is clicked.
Let us take another example, which calls a function instead when the button is clicked (timeout.html).
<HTML>
<HEAD>
<TITLE>Timeout example</TITLE>
<SCRIPT type="text/javascript">
<!--
function timeout_trigger() {
window.alert('Sorry for waiting me for 2 seconds!');
}
function timeout_init() {
setTimeout('timeout_trigger()', 2000);
}
<!-- end scripts -->
</script>
</HEAD>
<input type="button" value="Click Me" onclick="timeout_init()"/>
</HTML>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.181

Open the timeout.html file in a browser like IE, you will see the a Click Me button as shown in Figure
6.15.

Figure 6.15 onFocus event of SELECT object.


As can be seen in Figure 6.15, when you click on Click Me button, it will delay 2 seconds and then display
the popup.
Example Create a web application using JavaScript to display live clock with the help of a form as
shown below:

Remember, the format of hours in JavaScript is from 0 to 23, not 1 to 24. So, display "12"
whenever hours=0.
Solution Write the following code in Notepad editor and save as timer.html.
<html>
<head>
<title>Live clock</title>
</head>
<form name="Timer">
<input type="text" size="12" name="Clock">
</form>
<SCRIPT type="text/javascript">
function showClock(){
var CDate = new Date() // Current date
var hours = CDate.getHours() // returns the hour (Starts from 0-23)!
var minutes = CDate.getMinutes() // returns the minutes
var seconds = CDate.getSeconds() // returns the seconds
var ampm = "AM"
if (hours > 12){
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.182 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

ampm = "PM"
hours = hours - 12// The hours written out is in 12-hour format,
// instead of the default 24-hour format.
}
if (hours == 0)
hours = 12 // this is so the hours written out when hours=0
// (meaning 12a.m) is 12
if (minutes <= 9)
minutes = "0" + minutes
if (seconds <= 9)
seconds = "0" + seconds
document.Timer.Clock.value = hours + ":" + minutes + ":" +
seconds + " " + ampm
setTimeout("showClock()", 1000)
}
showClock()
</script>
<html>

The basic concept is to continuously write to a form field every 1 second, using the updated time from your
own computer.

FOHDU7LPHRXW  0HWKRG

The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.
The syntax is:
clearTimeout(setTimeout_variable)

Here, setTimeout_variable it the time which is the waiting time and set by setTimeout() method.
For example,
timeout = setTimeout('timeout_trigger()', 3000);
clearTimeout(timeout);

3RLQWVWR5HPHPEHU

1. Event handlers are JavaScript statements (usually functions) that are called whenever something
happens.
2. onClick event is raised when the user clicks on an object, e.g., button, image, hyper link etc.
3. onChange event is raised when the text in a select, text, or textarea form item is altered by the
user.
4. onBlur event is raised when a select, text, or textarea form item is acted upon and then moved
off of by the user.
5. onFocus event is raised when a select, text or textarea items is selected on an HTML form.
6. onSelect event, as its name implies, is raised when some text in a text box or text area is
selected.
7. onSubmit is an important event that is raised when the submit button on an HTML form is
clicked to submit the form data to the web server.
8. setTimeout, a method of the window object, basically delays the execution of a function or
statement until the specified time has passed.
9. The clearTimeout() method is used to stop the execution of the function specified in the
setTimeout() method.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.183

SOLVED EXERCISES
1. What are events?
Ans. Events are the actions or the happening of something on the machine and in the environment where the
program executes, e.g., the submission of a web form, clicking of a button, focusing an element,
hovering mouse over something, etc.
2. Differentiate between onload and onunload events.
Ans. The onLoad event is triggered when the user enters a webpage whereas the onUnload event is triggered
when the user leaves a webpage.
3. Define onfocus event.
Ans. The onfocus event fires when the user clicks on an element, usually <input> or <textarea> elements, and
the mousover event fires when the pointer mouses over any element on the page.
4. Write an HTML code using the JavaScript to enter the name and display the message "Hello " + name
as shown in following web page:

Ans. The HTML coding is as : (dname.html)


<HTML>
<HEAD>
<TITLE>Displaying name</TITLE>
<SCRIPT type="text/javascript">
<!--
function Display(form)
{
if (form.one.value.length > 0)
{
form.myName.value = "Hello! " + form.one.value;
}
}
<!-- end script ->
</SCRIPT>
</HEAD>
<BODY>
<h2>Input your name (any text) </h2>
<FORM>
<INPUT TYPE = "text" NAME = "one" VALUE = " ">
<INPUT TYPE = "button" NAME = "two" VALUE = "ClickMe" onClick = "Display(this.form)">
<INPUT TYPE = "text" name = "myName" size = 60>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.184 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

</FORM>
</BODY>
</HTML>
5. Write an HTML code using the JavaScript to enter the first name and last name and display the full
name uppercase in a textbox, i.e., first name + second name as shown in the following web page:

Ans. The HTML coding is as : (fullname.html)


<HTML>
<HEAD>
<TITLE>Displaying full name</TITLE>
<SCRIPT type="text/javascript">
<!--
function Display(form)
{
if (form.one.value.length > 0)
{
form.myName.value = "Hello! " + form.one.value.toUpperCase() + " "
+ form.two.value.toUpperCase();
}
}
<!-- end script ->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<h3>Enter your first name :</h3>
<INPUT TYPE = "text" NAME = "one" VALUE = " ">
<h3>Enter your last name :</h3>
<INPUT TYPE = "text" NAME = "two" VALUE = " ">
<INPUT TYPE = "button" NAME = "joint" VALUE = "ClickMe" onClick = "Display(this.form)">
<INPUT TYPE = "text" name = "myName" size = 40>
</FORM>
</BODY>
</HTML>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.185

6. ABC Electronic Shop handles its sales on Internet and the company provides easy installments to his
customers. Consider the following web page layout:

The company appoints a lady for his front office to meet the customers need. The lady manages the
product and the payment mode as:
x The payment mode is either as cash or installment.
x If you choose cash down, then you will avail 5% discount.
x If you choose installment, then for 1 year the rate of interest is 5% and for the subsequent years an
additional 2 % will increase from the previous year.
Write an interactive HTML program with JavaScript to calculate the cash down price or monthly installment
price for same product.
Ans. The HTML coding is as : (eshop.html)
<HTML>
<TITLE>ABC Electronic Shop</TITLE>
<SCRIPT type="text/javascript">
function open1(form)
{
var amount = 0;
var opt = form.list.selectedIndex;
var opt1 = form.list1.selectedIndex;
//var opt1 = form.payment.value;
if (opt == 0)
{
amount = 10000;
}
else
if (opt == 1)
{
amount = 14000;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.186 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

}
else
if (opt == 2)
{
amount = 5600;
}
if (document.frm1.payment[0].checked)
{
document.frm1.txt1.value = amount amount *.05;
document.frm1.txt2.value = " ";
}
if (document.frm1.payment[1].checked)
{
if (opt1 == 0)
{
document.frm1.txt1.value = amount + amount *.05;
document.frm1.txt2.value = Math.round((document.frm1.txt1.value)/12);
}
if (opt1 == 1)
{
document.frm1.txt1.value = amount + amount *.07;
document.frm1.txt2.value = Math.round((document.frm1.txt1.value)/24);
}
if(opt1 == 2)
{
document.frm1.txt1.value = amount + amount *.09;
document.frm1.txt2.value = Math.round((document.frm1.txt1.value)/36);
}
}
}
</SCRIPT>
<BODY>
<center>
<H1> A B C Electronics Shop </H1>
</center>
<HR ALIGN = "CENTER" SIZE = 5 WIDTH = 450 NOSHADE>
<H4>Select the item from the list</H4>
<FORM NAME = "frm1">
<SELECT NAME = "list" SIZE = 3>
<OPTION>TV!!
<OPTION>AC!!
<OPTION>Microwave!!
</SELECT>
<INPUT TYPE = "radio" NAME = "payment" VALUE = "1" CHECKED> Cash
<INPUT TYPE = "radio" NAME = "payment" VALUE = "2" > Installment
<SELECT NAME = "list1" SIZE = 3 >
<OPTION>One Year!!
<OPTION>Two Years!!
<OPTION>Three Years!!
</SELECT>
<INPUT TYPE = "button" NAME = checktwo VALUE = Tell_Amount
onClick = "open1(this.form)"><p>
<h5> Total Amount to be paid:</H6>
<INPUT TYPE = text" NAME = "txt1" VALUE = " " >
<h5> Monthly Installment:</H6>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.187

<INPUT TYPE = text" NAME = "txt2" VALUE = " " >


</FORM>
</BODY>
</HTML>
7. Write an HTML program using JavaScript to check whether current date (i.e., year) is a leap year or
not.
Ans. The function is as : (leapyear.html)
<HTML>
<TITLE>Leap year</TITLE>
<SCRIPT type="text/javascript">
function today_date()
{
var dd;
var mm;
var yy;
var now = new Date();
dd = now.getDate();
mm = now.getMonth();
yy = now.getYear();
document.write("Today is : " + dd + "" + mm + "" + yy + "<br>");
if ( mm==1 || mm == 3 || mm == 5 || mm == 7 || mm == 10 || mm == 12)
{
if (dd<=31 && dd >0)
document.write("Valid date");
else
document.write("Invalid date");
}
else
if ( mm==4 || mm == 6 || mm == 9 || mm == 11)
{
if (dd<=30 && dd >0)
document.write("Valid date");
else
document.write("Invalid date");
}
else
if (mm = 2)
{
if (( yy % 100 == 0) && (yy%400 == 0) || (!yy%100 == 0)
&& (yy%4 == 0))
if (dd>0 && dd<=29)
document.write("Valid date");
else
document.write("Invalid date");
else
if (dd>0 && dd<= 28)
document.write("Valid date");
else
document.write("Invalid date");
}
else
document.write("Invalid date");
}
today_date();
</script>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.188 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

8. Consider the following web page layout:

Following is the HTML code for the above web page:


<HTML>
<TITLE>Linking to mail</TITLE>
<BODY>
<H4>Select a location from the list</H4>
<FORM> <SELECT NAME = "list" SIZE = 3 onChange = "open1()">
<OPTION>Go to Yahoo!!
<OPTION>Go to Hotmail!!
<OPTION>Go to Rediff!!
</SELECT>
</FORM>
</BODY>
</HTML>
Write the JavaScript code to be embedded in the above HTML code to open the corresponding website
in a new window on the selection of any list item.
x Go to Yahoo !! links to http://www.yahoo.com
x Go to Hotmail !! links to http://www.hotmail.com
x Go to Rediff !! links to http://www.rediff.com
Ans. The JavaScript code is as : (ewab.html)
<HTML>
<TITLE>Linking to mail</TITLE>
<SCRIPT type="text/javascript">
function open1(form)
{
var opt = form.list.selectedIndex;
if (opt == 0)
{
document.location = "http://www.yahoo.com";
}
else
if (opt == 1)
{
document.location = "http://www.hotmail.com";
}
else
if (opt == 2)
{
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.189

document.location = "http://www.rediff.com";
}
}
</SCRIPT>
<BODY>
<H4>Select a location from the list</H4>
<FORM>
<SELECT NAME = "list" SIZE = 3 onChange = "open1(this.form)">
<OPTION>Go to Yahoo!!
<OPTION>Go to Hotmail!!
<OPTION>Go to Rediff!!
</SELECT>
</FORM>
</BODY>
</HTML>
9. Consider the following web page layout:

Following is the HTML code for the above web page.


<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM name = "frm1">
<P>Enter background color:
<INPUT TYPE = "text" NAME = "txt1">
<INPUT TYPE = "button" VALUE = "Click to change color" onClick = "bcolor()"><BR>
Select image file:
<INPUT TYPE = "file" NAME = "txt2">
<INPUT TYPE = "button" VALUE = "Click to see image" onClick = "imgselect()"><BR><BR>
<IMG NAME = "img1" SRC = " " ALT = "Image will be loaded here" WIDTH = 200 HEIGHT =
200>
</FORM>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.190 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Write the JavaScript code that needs to be embedded in the above HTML code to do the following:
x The click event of the first button should call a function bcolor() which will change the background
color entered by the user in textbox txt1.
x The click event of the second button should select a function imgselect() which will display the
image selected by the user in the file textbox txt2 in the space of the image img1.
Ans. The functions are : (colorimage.html)
<HTML>
<HEAD>
<TITLE>Background colorl</TITLE>
</HEAD>
<SCRIPT type="text/javascript">
<!--
// for changing the background color
function bcolor() {
var col = document.frm1.txt1.value;
document.bgColor = col;
}
function imgselect() {
var imgd = document.frm1.txt2.value;
document.write("<img" + " " + "name = " + "img1" + " " + "SRC = " + imgd + ">");
}
<!--end scripts -->
</SCRIPT>
<BODY>
<FORM name = "frm1">
<P>Enter background color:
<INPUT TYPE = "text" NAME = "txt1">
<INPUT TYPE = "button" VALUE = "Click to change color" onClick = "bcolor()"><BR>
Select image file:
<INPUT TYPE = "file" NAME = "txt2">
<INPUT TYPE = "button" VALUE = "Click to see image" onClick = "imgselect()"><BR><BR>
<IMG NAME = "img1" SRC = " " ALT = "Image will be loaded here" WIDTH = 200 HEIGHT =
200>
</FORM>
</BODY>
</HTML>
10. Consider the following page layout:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.191

Following is the HTML code for the above web page:


<HTML>
<BODY>
<H1>Enter the details</H1>
<FORM NAME = "frm1">
Enter your nationality:
<INPUT TYPE = "Text" NAME = "txtNat" SIZE = "20"><BR><BR>
Enter your age:
<INPUT TYPE = "Text" NAME = "txtAge" SIZE = "2"><BR><BR>
<INPUT TYPE = "Button" NAME = "BSubmit" VALUE = "Send details">
</FORM>
</BODY>
</HTML>
Write the JavaScript code to be embedded in the above HTML code for the click event of the button
which will display the alert message "Eligible for Voting" if the following validations are true:
x The age should be numeric and should be > 18.
x The nationality should be "Indian".
The alert message "Not eligible to vote" should be displayed if any of the abovementioned validations
are false.
Ans. The JavaScript code is as: (vmessage.html)
<HTML>
<TITLE>Message display</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkAge(form) {
var nNat = document.frm1.txtNat.value.toUpperCase();
var nAge = document.frm1.txtAge.value;
if ((nAge > 18) && (nNat == "INDIAN")) {
alert("Eligible for Voting");
} else {
alert("Not eligible to vote");
}
}
<!--end scripts -->
</SCRIPT>
<BODY>
<H1>Enter the details</H1>
<FORM NAME = "frm1">
Enter your nationality:
<INPUT TYPE = "Text" NAME = "txtNat" SIZE = "20"><BR><BR>
Enter your age:
<INPUT TYPE = "Text" NAME = "txtAge" SIZE = "2"><BR><BR>
<INPUT TYPE = "Button" NAME = "BSubmit" VALUE = "Send details"
onClick = "checkAge(this.form)">
</FORM>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.192 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

11. Pizza Hut company provides online services to his customer regularly with following details as shown
in the figure given below:

Following is the HTML code for the above web page:


<body>
<h2>Pizza Hut Online</h2>
<form action="mailto:gbsahoo@yahoo.com" method="post"
onSubmit="PlaceAnOrder()">
Customer Details:<br>

Name: <input name="Name" size=20>


Address: <input name="address" size=20>
Mobile No.: <input name="mobileno" size=20><br>
<p>Your Pizza Details:<br>
Size:
<select name="size">
<option>Small
<option selected>Medium
<option>Large
</select><br>
Toppings:<br>
<input type=checkbox name="topping">Ham
<input type=checkbox name="topping">Peppers<br>
Packaging:<br>
<input type=radio name="packaging">Cardboard box
<input type=radio name="packaging">Styrofoam-insulated container<p>
<input type=submit value="Place Order">
</form>
</body>

Write the JavaScript code for PlaceAnOrder() function which will be embedded in the above HTML
code for the click event of the button which will display the alert message with all details of the customer.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.193

Ans. The JavaScript code is: (pizzadelivery.html)


<SCRIPT type="text/javascript">
<!--
function PlaceAnOrder(){
var result="Dear "
result = result + document.forms[0].Name.value
result = result + ", You have ordered a "
if (document.forms[0].size.options[0].selected){
result = result + "small"
}
if (document.forms[0].size.options[1].selected){
result = result + "medium"
}
if (document.forms[0].size.options[2].selected){
result = result + "large"
}
result = result + " pizza with cheese, tomatoes, "
if (document.forms[0].topping[0].checked){
result = result + "and ham. "
}
if (document.forms[0].topping[1].checked){
result = result + "and peppers. "
}
result = result + " It will be delivered in a "
if (document.forms[0].packaging[0].checked){
result = result + "cardboard box"
}
if (document.forms[0].packaging[1].checked){
result = result + "styrofoam-insulated container"
}
result = result + " to the following address: "
result = result + document.forms[0].address.value
alert(result)
}
//-->
</script>
12. Develop an Euro Calculator web application using JavaScript to convert all currencies of the Euro
countries into Euros and vice versa. The following is the web application form:
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.194 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Following is the HTML code for the above web page:


<body>
<h2>Euro Calculator </h2>
<form>
<input name=amount size=10 onChange="a=0">
<select name="currency" onChange="calculate()"
onFocus="calculate()">
<option value="13.7603">ATS Austria, Schilling</option>
<option value="40.3399">BEF Belgium, Franc</option>
<option value="1.95583">DEM Germany, Deutsche Mark</option>
<option value="0.58527">CYP Cyprus, Pound</option>
<option value="15.6466">EEK Estonia, Kroon</option>
<option value="166.386">ESP Spain, Peseta</option>
<option value="5.94573">FIM Finland, Markka</option>
<option value="6.55957">FRF France, Franc</option>
<option value="340.750">GRD Greece, Drachma</option>
<option value="0.787564">IEP Ireland, Pound</option>
<option value="1936.27">ITL Italy, Lira</option>
<option value="3.45280">LTL Lithuania, Litas</option>
<option value="40.3399">LUF Luxembourg, Franc</option>
<option value="0.70280">LVL Latvia, Lats</option>
<option value="0.42930">MTL Malta, Lira</option>
<option value="2.20371">NLG Netherlands, Guilder (Florin)</option>
<option value="200.482">PTE Portugal, Escudo</option>
<option value="239.640">SIT Slovenia, Tolar</option>
<option value="30.1260">SKK Slovakia, Koruna</option>
</select>
corresponds to <input name=euro size=10 onChange="a=1">Euros.<br>
<input type=button value="Calculate" onClick="calculate()">
</form>
</body>

Write the JavaScript code for calculate() function which will be embedded in the above HTML code for
the click event of the button which will display the conversion value of Euro to its patner countries and
vice versa.
Ans. The JavaScript code is: (erocalculator.html)
<SCRIPT type="text/javascript">
<!--
var a = 0
function calculate(){
if (a == 0){
document.forms[0].euro.value=Math.round(document.forms[0].amount.value /
document.forms[0].currency[document.forms[0].currency.selectedIndex].value * 100) / 100
}
if (a == 1){
document.forms[0].amount.value=Math.round(document.forms[0].euro.value *
document.forms[0].currency[document.forms[0].currency.selectedIndex].value * 100) / 100
}
}
//-->
</script>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.195

REVIEW QUESTIONS
1. What is an event?
2. What is an event handler? Write its syntax.
3. What is button object?
4. What is checkbox object?
5. What is the purpose of Radio object?
6. What is the use of password object?
7. Differentiate between text and textarea object.
8. What is the purpose of submit object?
9. What is select object?
10. What is onBlur event? Why is it called so?
11. What is onFocus event?
12. What is date object?
13. Write an HTML program using JavaScript to input your percentage of marks and display the grade as
explained below:
if StPer >= 90
document.write("Grade is A")
else
if StPer >= 80 Then
document.write("Grade is B")
else
if StPer >= 70 Then
document.write("Grade is C")
else
if StPer >= 60 Then
document.write("Grade is D")
else
document.write("Grade is F")
14. A government lab wants to install a security check system at the gate and only authorised personnel
may enter the office, using their security codes. The following are valid security codes:
100 200 Technicians
201 400 Custodians
401 600 Special Services
601 800 Chief Scientist
801 1000 Scientists
As an added security measure, the keypad treats any access more than 1000 as a panic code by
displaying the message in red colour. Once an access code is entered, access is either granted or denied.
If access is granted, then the Welcome message with blue background and group (i.e., scientist,
custodian, etc.) are written to the window. If access is denied, then the message Not Allowed with black
background will be displayed on the window.
15. The state electricity board generates monthly electricity bill to be computed as follows:
Minimum : Rs. 200 for first 100 units.
Plus Rs. 1.00 per unit for the next 100 units.
Plus Rs. 0.75 per unit for the next 100 units.
Plus Rs. 0.50 per unit for any unit beyond 300.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.196 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

Write a program in Visual Basic which calculates the monthly bill for a customer based on the number of
units consumed selected by the user displayed using the radio button. Also implement this program
using the list option.
16. NHPC has different categories of workers, who are paid different hourly rates (R). Wages are then
determined after accepting the number of hours (H) one works during the week. The different classes are
paid as follows:
Category `)
Hourly Rate(`
Unskilled 25.00
Semi-skilled 35.00
Skilled 45.00
Write a program to input the hours of a worker and weekly wages using Option button.
17. Write an HTML program using JavaScript to select the name of the cricket player from the list and display
its record like Total runs, Number of 50s, 100s etc.
18. Read the following case study and answer the question that follows:
Mr. Nath of ABC Software Corporation has got requirement of a Software Project from a Customer in
Tours and Travel Business. He performed the preliminary analysis and found that software application
should be based on Client/Server technology. We had taken the excerpt from his analysis and present
you one of the forms to enquire about railway reservation.
Carefully observe the following picture.

Write a JavaScript function to check for the validity of the entered date value. Clear the textboxes for
invalid date value and set the focus on txtDD.
19. Sumeet Electronics has the following products with their list prices given. The store gives a 10%
discount on every product. However, at the time of festival seasons, the store gives a further 7% festival
discount after 10%.
Product List Price (Rs.) Discount Price
Washing Machine 12000 ---
Colour Television 17000 ---
Refrigerator 18000 ---
OTG 8000 ---
CD Player 4500 ---
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.197

Write an HTML program using JavaScript to with a function to calculate the net price for a product. Enter
product name, list price and select either festival or not by clicking an option button as shown in the
form.
20. Write an HTML program using JavaScript to display the colors name using radio object and as the user
select any of the colour the background will be changed with that colour.
21. Write an HTML program using JavaScript to enter the URL of any site in the textbox and the program will
open that site as the user click on the Go button.
22. Write an HTML program using JavaScript to generate a simple calculator which will find the result when
you click on the = button.
23. Write a JavaScript (and the HTML page) that asks for the users name and then tells the user how many
characters are in his/her name.
24. Write a script and page that show an alert box when the user clicks an anchor link.
25. Write a JavaScript that determines whether or not a number entered in a textbox is 786.
26. Write an HTML application in which is displayed the code of the courses in the list and student will enter
their marks in the text and use JavaScript to know whether the student is eligible for the course or not.
27. Akash International Tourism arranges tours for its customers in India. He manages his tour in two
service packages: Normal and De Luxe. Consider the following page layout:

Following is the HTML code for the above web page :


<HTML> <TITLE>ABC Electronic Shop</TITLE>
<BODY>
<center> <H2>Akash International Tourism</H2> </center>
<HR ALIGN="CENTER" SIZE = 5 WIDTH = 450 NOSHADE>
<H4>Select a tour package</H4>
<FORM NAME = "frm1">
<SELECT NAME = "list" SIZE = 3 >
<OPTION>Shimla
<OPTION>Nainital
<OPTION>Darjeeling
<OPTION>Kashmir
</SELECT>
<INPUT TYPE = "radio" NAME = "payment" VALUE = "1" CHECKED>Normal
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.198 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234

<INPUT TYPE = "radio" NAME = "payment" VALUE = "2" >De Luxe


<INPUT TYPE = "button" NAME = checktwo VALUE = "Check Amount"
onClick = "open1(this.form)"><p>
<h6> Tour fare :</H6>
<INPUT TYPE = text" NAME = "txt1" VALUE = " " > </FORM>
</BODY>
</HTML>

The following are the fare for different tourist places :


Place Fare
Normal De luxe
Shimla 3000 4500
Nainital 4000 6500
Darjeeling 8000 11000
Kashmir 14000 18000
Write the JavaScript code to be embedded in the above HTML code for the click event of the button to
find the fare for a tourist place in the respective textbox.

You might also like