0% found this document useful (0 votes)
3 views43 pages

JavaScript Notes

The document provides an overview of client-side scripting, specifically focusing on JavaScript and its integration with HTML. It covers topics such as variable declaration, data types, operators, and built-in functions, along with examples and syntax. Additionally, it discusses decision-making statements and user-defined functions in JavaScript programming.

Uploaded by

shetyeom45
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

JavaScript Notes

The document provides an overview of client-side scripting, specifically focusing on JavaScript and its integration with HTML. It covers topics such as variable declaration, data types, operators, and built-in functions, along with examples and syntax. Additionally, it discusses decision-making statements and user-defined functions in JavaScript programming.

Uploaded by

shetyeom45
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Client Side Scripting Script Placed inside body section

3.11 Introduction <!DOCTYPE html>


There are a variety of scripting <html>
languages used to develop dynamic web <head><title>First</title>
pages. JavaScript was initially created </head>
to “make webpages alive”. They <body>
don’t need a special preparation or a <script language="javascript">
compilation to run. Using HTML one // javascript statements
can only design a web page but cannot </script>
implement any logic on web browsers </body>
like addition of two numbers, check
</html>
any condition, looping statements
(for, while), decision making statements Script Placed inside head section
(if-else) etc. This is possible by embedding <!DOCTYPE html>
JavaScript block into HTML.
<html>
3.12 Scripting language <head><title> Second </title>
A script is a list of commands that <script language="javascript">
are executed by a scripting engine. // javascript statements
Scripts are used to generate dynamic </script>
Web pages on the Web. Scripts can </head>
be opened and edited by using a <body></body>
text editor. </html>
Insertion of JavaScript in HTML :
JavaScript can be use for client Note : It's best practice to
side or server side scripting language. terminate JavaScript statements with
semicolon(;). It's not required if you
JavaScript code can be inserted in
write each statement on a new line.
HTML program between <script> and
</script> tag. Language attribute is used
to set scripting language. You can place 3.13 Variables
any number of scripts in HTML. There The variable is a basic unit of storage
are two methods to insert JavaScript in the in a JavaScript program.
HTML. Scripts can be placed in <body> Rules to declare variables :
or in <head> section of an HTML or in Variable name may consist of
both. alphabets, digits and underscore and
dollar character with following rules :
42
1. They must start with an alphabet. 3.14 Data Types
2. Uppercase and lowercase are distinct. Computer is mainly used to
This means that variable ‘sum’ is not store information and to do complex
same as ‘SUM’. calculations. When we store information
it is in the form of alphabets, numbers or
3. It should not contain blank space or
alphanumeric values. JavaScript provides
special symbol except underscore.
data types to store and use different types
4. Standard keywords are not allowed of values that are :
as variable name. For Example
1. Number type : Numerical value
document, while.
specially belongs to the ‘number’
5. Variable name can be limited up to data type. Number data type stores
255 characters. (holds) both whole number (integer)
Variable name in javascript is or decimal point numbers which stores
declared with keyword ‘var’. fractional part of number (also called
as floating point numbers). Number
Syntax : data type can hold positive as well as
var variablename; negative values.

var variablename, variablename; Example :


//To declare more than one variable, var y=100000
variablenames are separated by a var z= -67.99
comma.
2. String Type : Strings are used for
Example : storing text. Strings must be inside of
var a //variable a has been declared. either double or single quotes.
var a,b,c // variables a, b and c have been Example :
declared. var x=‘‘Hello”
var z=40,y=100// declaring variables var str= ‘Information Technology’
with initialization
3. Boolean Type : It represents only two
values ‘true’ and ‘false’. All relation-
al, conditional and logical operators
Do it yourself produce Boolean values true/false or
yes/no.
 Define five correct and five incorrect
variable names. 4. Infinity : Division by 0 gives you an-
other special value.
 List some scripting languages.
Example : a=3/0
Result: Infinity

43
5. null : In JavaScript null is, just a value require one operand is called as unary
which means “nothing”, ”empty”, operator and operators that require two ope
”unknown”. It is supposed to be rands are called as binary operator. Most
something that doesn’t exist. of the operators can be divided into groups :
6. undefined : JavaScript returns Arithmetic, Relational and Logical
‘undefined’ when variable which is operators.
declared but not assigned. Then java
3.15.1 Arithmetic operators :
interpreter shows that it is undefined.
Arithmetic operators are used in
Example : var age; alert(age); mathematical expressions in the same
way that they are used in algebra. For
3.15 Operators following example consider:
Operators are used to do arithmetic var a = 40, b = 4.5;
and logical operations. Operators that
Operator Definition Example Result
+ Addition a+b 44.5
- Subtraction a-b 35.5
* Multiplication a*b 180
/ Division a/b 8.89
Modulus
% a%b 4
(It returns remainder after division)
Table: 4 Arithmetical Operators in JavaScript

Note : - Type your Javascript program in editors and execute it in browser


similar to HTML programs.

Program 8 :
<!DOCTYPE html>
<html>
<head><title>multiplication</title> </head>
<body bgcolor="yellow">
<h1> Program to calculate multiplication of two numbers </h1>
<script language="javascript">
var a,b,c;
a=76;
b=99.45;
c=a*b;
[Link]("<br><h1>multiplication of two numbers : " +c+"</h1>");
</script></body></html>
44
Output 8 :

Program to calculate multiplication of two numbers

Multiplication of two numbers : 7558.2

Here, document. write() is used to


Example :
display or write content on a web page.
var p=400; //assigns value to the variable p
3.15.2 ‘+’ operator in JavaScript : var e=457.930;//assigns value to the variable e
In JavaScript ‘+’ operator has two var a=a+7;// evaluates expression a+7 and
meanings, arithmetic addition and string assigns value to a
concatenation operator. var str=”Hello”; // assigns string value to
variable str
Example : var a=15+”Hello”
var c=d; //assigns value of d to c
Result : 15Hello
Example : var a=15+7+”Hello” Expression : There is a difference
Result : 22Hello between algebraic mathematical
equations and computer programming
Do it yourself statements. Following statements
 Find the result of…. are valid expressions in algebraic
1. 20+‘20’ mathematics, but they are invalid in
2. 10+20+‘‘2” programming languages.
3. 10+‘2’+‘2’
a+b=10; //error
a+b=c+d; //error
3.15.3 Assignment Operators (=) : c+d=p; //error
It is important to know that assignment 10=x; //error
operator is not ‘equal to’ operator. X=10; //valid
Assignment operator is used to assign
value of an expression to a variable. This Note : Remember that in a programming
means that value of an expression on the statement = operator just evaluates
right hand side is assigned to the single right side expression and assigns it to
variable on the left hand side. Value of the left hand side variable so at the
variable may change during the next left hand side of = , operator always
programming instruction. contains a single variable.

45
Do it yourself
 Which of the following arithmetic
expressions are valid in JavaScript.
a) A=25/3%2
b) X=12.67*-5.0
c) 21%45-34+12=a+x
d) (23/5)+4-7=c
e) c+f=45*5/5%12

3.15.4 Relational Operators :


Relational operators are used to check conditions or comparison of operands.
Result of relational operators is Boolean value ‘true’ or ‘false’. They are used in
looping and control structures. Following table shows JavaScript relational operators.
For result consider the values as : a=10 and b=30…
Operator Description Example Result
< Less than a<b True
> Greater than a>b False
<= Less than equal to a<=b True
>= Greater than equal to a>=b False
== Equal to a==b False
!= Not equal to a!=b True
Table: 5 Relational Operators in JavaScript
3.15.5 Logical Operators :
Logical operators are used to verify more than one condition at a time or to
negate the condition. JavaScript has three logical operators.
Operator Description Example Result
This operator evaluates var age=25; First condition evaluates to false and
&& to ‘true’ only when all var salary=50000; second condition evaluates to true, so
(and) its operands are ‘true’. if(age>55 && that whole expression returns Boolean
salary>25000) value as false.

This operator evaluates var number =-1; First condition evaluates to true and
|| to ‘true’ when any one if(number<0 || second condition evaluates to false, so
(or) of the operand is ‘true'. number>100) whole expression returns Boolean value
true.
This unary operator var z=0; Expression returns Boolean value as
!
is used to invert the if(!(z==0)) false.
(not) Boolean expression.
Table: 6 Logical Operators in JavaScript
46
Do it yourself
 Determine the Boolean value of each of the following logical expressions if
a=10, b=-5 and c=20
1. a<b && c>b 2. a==b || c==d
3. c>-24 && a<50 4. a<b && b==c && a==b
5. c<0.0 || a>-20 6. b<c && a==67
7. a<b || a<c || b<c

3.15.6 Increment (++) and Decrement (--)Operators :


Increment (++) operator in JavaScript is used to increment value of variable by one
and Decrement operator in JavaScript is used to decrement value of variable by one.
They can be used in two ways :
++x Pre- increment Value of variable x is incremented before it is used in
expression
x++ Post –increment Value of variable x is incremented after it is used in
expression
--x Pre- decrement Value of variable x is decremented before it is used in
expression
x-- Post –decrement Value of variable x is decremented after it is used in
expression
Table: 7 Increment and Decrement Operators in JavaScript

Example :
var a=100; var a=100;
b=++a b=a++;
output : b=101 and a=101 output : b=100 and a=101

Comments in JavaScript
Comments are non-executable statements in program. Comments are used
to provide information or explanation about your programming construct.
Statements added in comments are ignored by JavaScript. It supports two types
of comments.
1. Single line comment (//…………..) : Single line comment begin with //. The
JavaScript ignores everything from // to the end of the line.
2. Multiline comment : Multiline comments are used to comment on more than
one line. It starts with /* and end with */
47
3.16 Commonly used Built-In Functions in JavaScript
Function is used to perform repetitive tasks whenever required. It is reusable code-
block that will be executed when it is called.
Function Description Example
This function is used to parse Example Output
a string and convert it into parseInt(‘MH100’) NaN
parseInt() a number parseInt(‘100’) 100
parseInt(‘100MH’) 100
This function is used to parse a Example Output
string and convert it into parseFloat(‘MH100’) NaN
parseFloat() floating point representation parseFloat(‘100.00’) 100
parseFloat(‘100.2MH’) 100.2
This function displays alert popup Example
alert() box with ok button. This is also alert(“welcome to javascript ”)
called as a message box. or [Link](“Hello”)
This function is used when you Example:
want input value from user at var n;
the time of program execution. n=prompt(“Enter value for n”)
prompt() It displays ok and cancel but-
tons. Ok button returns input
value, Cancel button returns null
value.
This function displays Example:
confirmation message box with var ans;
confirm() ok and cancel button. Ok button ans=confirm(“Do you want to
returns ‘true’ and cancel returns continue”)
‘false’
This string function used to con- Example:
toLowerCase() vert the given string into lower case var str=”JavaSCRIPT”
alphabets str=[Link]()
This is string function is used to Example:
toUpperCase() convert given string into uppercase var str= “JavaSCRIPT”
alphabets str=[Link] Case()
It returns true'' if given value is not Example:
isNaN() a number. It returns 'false'if given isNaN(CP100)
value is number isNaN(100)
Table: 8 Built-in functions in JavaScript

Note : alert(), prompt() and confirm() are window functions we can use it without
the window prefix.

Note : length is a property of string object used to calculate length of string.

48
Program 9 : Output 9 :
Program to calculate area of circle you
<!DOCTYPE html> entered radius value: 5.5
<html> Area of circle is : 94.985
<head><title>Area of circle</title>
</head>
<body bgcolor=yellow>
<h1> Program to calculate area of circle </h1>
<script language="javascript">
var r,area;
r=prompt("Enter the radius of circle");
area=3.14*r*r;
[Link]("<h1>you entered radius value:</h1>" +r);
[Link]("<h1>Area of circle is :</h1>" +area);
</script>
</body></html>

3.17 Decision Making Statements 2) if else statement :


Syntax :
1) if statement :
Syntax : if(condition)
{
if(condition)
{ statement block;
statement block; }
} else
{
If the conditional expression given in
statement block;
the parenthesis is true, then the statements
within the block will be executed, followed }
by execution of the remaining program.
If the conditional expression evaluates If the conditional expression
to false, thenthe statement block will not be evaluates to true, then true block
executed. Note that if statement block statements will be executed otherwise
constitutes a single statement, then false block that is the else part will be
drawing curly brackets is optional. executed. At a time either true block or
false block will be executed, not both.
49
3.18 User Defined Functions
Note : - if…..else if ladder is used to
check multiple conditions, at a time A function in any scripting and
only one condition is true. if not, then programming languages is small part
else part is executed. of program that we require again and
again. It helps to make program smaller,
A function is a subprogram designed to
Program 10 : perform a particular task. Functions can
be called either by an event or by giving
<!DOCTYPE html>
call to that function.
<html>
<head><title>Even Odd</title></head> Function definition :
<body bgcolor="green"> Rules to declare function name is
<h1> Program to check number is even or similar to variable
odd </h1>
<script language="javascript"> function functionname(argument1,argu
var a,b ment2…)
a=prompt("Enter your value:-");
{
b=parseInt(a) ;
// input is converted into number data type statement block;
if(b%2==0) }
alert("Number is even"); Values to be passed to the function
else for further processing
alert("Number is odd");
</script>
Program 11 :
</body></html>
<!DOCTYPE html>
<html>
<head><title>Function program</title>
Output 10 :
<script language="javascript">
function show()
{
alert("Welcome to function");
}
</script></head>
<body bgcolor="green">
<h1> Use of Function in Javascript </h1>
<script language="javascript">
show();//calling of function
</script> </body></html>
50
Output 11: Event Handler Description
Mouse Events
onMouseOut When user moves the
mouse away from an
element
onClick When user clicks an
element
onMouseOver When user moves
the mouse over an
element
3.18.1 Event Handling :
onMouseUp When user releases a
JavaScript is an event-driven mouse button over an
language. Event is an action done by element
the user or an application. JavaScript's Keyboard Events
interaction with HTML is handled through onKeyDown When user presses a
events that occur when user or browser key
manipulates page. When the page loads, onKeyUp When user releases
key.
it is called an event, When the user clicks
Table: 9 Event Handler in JavaScript
a button, that click is also an event. Other
examples include events like pressing
Features of Javascript
any key, closing a window, resizing a
window, etc. Perform input It is light weight
JavaScript lets you execute a code data validation scripting languge
when events are detected. You can respond
to any event using an Event Handler,
Features of
which is just a function that’s called Javascript
when an event occurs. This event handler
may cause button to close windows, It is case It makes web pages
messages to be displayed to users, data sensitive language more interactive
to be validated and virtually any other
type of response. Some commonly used
It can handle date and
events are :
time effectively

51
Program 12 : Output 12:
<!DOCTYPE html> Enter your age:- 22

<html><head><title>conditional statement</title> SUBMIT

<script language="javascript">
function check()
{ Qualifies for driving

var age;
OK
age=[Link];
if(age>=18)
alert("Qualifies for driving"); Enter your age:- 15

else SUBMIT

alert("Does not qualifies for driving");


}
</script></head> Does not qualifies for driving

<body>
OK
<form name="form1">
<center>
Enter your age:-
<input type="text" name="t1"><br><br>
<input type="button" value="SUBMIT" onClick="check()">
</form></body></html>

Program 13 : Output 13:


<!DOCTYPE html> Enter string value:- India

<html><head><title>Uppercase function</title> Press button

<script language="javascript"> Uppercase String is:- INDIA

function display()
{
var a;
a=[Link]
[Link]=[Link]()
}
</script></head>
<body><form name="form1">
Enter string value:-
<input type="text" name="t1"><br><br>
<input type="button" value="Press button"
onKeyPress="display()">
Uppercase String is:-
<input type="text" name="t2"></form></body></html>
52
Program 14 :
<!Doctype Html>
<html>
<head><title> Html 5 </title>
</head>
<body bgcolor=yellow>
<header>
<h1>HTML5 includes new semantics</h1>
<p >It includes semantic tags like header, footer, nav
</header>
<header>
<h1>Example of complete HTML5 Basics</h1>
<h2>The markup of the future under development.</h2>
</header>
<nav><h1><p>The nav element represents a section of navigation links. It is suitable for
either site navigation or a table of contents.</p></h1>
<a href="/">[Link]
<a href="[Link] website</a><br>
</nav>
<aside>
<h1>Other education based websites of State</h1>
<a href="[Link] Board website</a><br>
<a href="[Link] Exam website</a><br>
</aside>
<section>
<h1>Impressive Web Designing</h1>
<p>The aside element is for content that is tangentially related to the content around it, and
is typically useful for marking up sidebars.</p>
</section>
<section>
<h1>Articles on:Article tag</h1>
</section>
<article>
<p>The article element represents an independent section of a document,
page or site. It is suitable for content like news or blog articles, forum posts or
individual comments.</p>
</article>
<footer>© 2018 Balbharti.</footer>
</body></html>

53
Output 14:
HTML5 includes new semantics
It includes semantic tags like header,footer,nav
Example of complete HTML5 Basics
The markup of the future under development.
The nav element represents a section of navigation links.
It is suitable for either site navigation or a table of
contents.
[Link]
Balbharti website
Other education based websites of State
State Board website
Online Exam website
Impressive Web Designing
The aside element is for content that is tangentially related
to the content around it, and is typically useful for mark-
ing up sidebars.
Articles on:Article tag
The article element represents an independent section of a
document, page or site. It is suitable for content like news
or blog articles, forum posts or individual comments.
© 2018 Balbharti.

54
Summary
 WWW stands for world wide web normally referred to as web.
 Webpage: A simple text file created using HTML.
 Website: A collection of web pages containing text images audios and videos.
For Example Internet.
 Web Browser: A web browser is used to view web pages or websites on the
internet For Example Internet Explorer, Google Chrome, Mozilla Firefox.
 Web Server: A Web server is an application or a computer that sends
webpages over the internet using the HTTP protocol. The functionality of
website is managed by web server. For Example IIS, Apache.
 URL(Uniform Resource Locator): It is an address of a webpage on the internet.
The webpages are retrieved from the original location with the help of URL.
 HTTP: HTTP(Hyper Text Transfer Protocol) is a protocol used by WWW to Cli-
ent server communication.
 Protocol : A protocol is a set of communication standards used for transferring
information between computers in a network.
 <Html> and </Html>: This tag indicates that the document is an html file.
 <Head> and </Head>: It includes <Title> within it, the text within <head> is not
displayed on the webpage.
 <title> and </title> : The content within this tag is displayed in a title bar.
 <body> and </body>: This tag includes all content which is to be developed in
the web browser. Most of the tags are included in this tag.
 Text formatting element <b>,<I>,<u>,<small>,<sup>,<Sub>,<mark>,<del>, <ins>
 HTML provides six levels of heading tags. The range is from 1 to 6
 <IMG> this tag is used to insert an image within a webpage
 <Hr> this tag is used to display horizontal ruled line
 <table>: It is used to indicate creation of a table.
 <caption>: It is used to specify table heading. It has align attribute which
can have top or bottom as it’s values. Top is the default value.
 <tr> : This tag is used to create each row of the table.
 <th> : It is generally used for first row content of the table. It displays content in
the bold format. It can be replaced with <td>.
 <td> : It specifies data within the table.(cell content)
 <Form> : It is used to accept users' entry . It has a collection of different elements
or controls .

55
 <input> : It is used to create different controls .
 Type attribute of<input > can have values like text, password, radio, checkbox,
submit, reset.
 <textarea> It is used to create text with multiple lines.
 JavaScript is scripting language which can be used to develop dynamic
webpages. It is an event based scripting language; It is a platform
independent language.
 Variables are the basic units of storage.
 JavaScript supports different types of operators such as arithmetic (+,-,*,/,%),
relational (<,>,<=,>=,==), logical (&&,||,!) etc.
 if, if…else, are control statements in JavaScript.
 Javascript supports built-In functions like parseInt(), parseFloat(), prompt(),
confirm(), alert() etc.
 Javascript supports user defined functions also that can be called either by an
event or by giving call to that function.

56
3 Advanced Javascript

Let us learn • No need of special software to run


JavaScript programs
 Features of JavaScript, difference • JavaScript is object oriented scripting
between client side scripting and language and it supports event based
server side scripting. programming facility. It is case
 Looping structures. sensitive language.
 DOM Objects and window object in • JavaScript helps the browser to
JavaScript. perform input validation without
 Inbuilt objects such String, Math, wasting the user's time by the Web
Array, Date and Number with its server access.
properties and Methods. • It can handle date and time very
 Simple JavaScript programs to do effectively.
validations and user interaction.
• Most of the JavaScript control
statements syntax is same as syntax
3.1 Introduction of control statements in other
programming languages.
There is variety of scripting languages
used to develop dynamic websites. • An important part of JavaScript is the
JavaScript is an interpreted scripting ability to create new functions within
language. An interpreted language is a scripts. Declare a function in
type of programming language that JavaScript using function keyword.
executes its instructions directly and • Software that can run on any hardware
freely without compiling machine platform (PC, Mac, SunSparc etc.) or
language instructions in precious software platform (Windows, Linux,
program. Program is a set of instructions Mac OS etc.) is called as platform
used to produce various kinds of outputs. independent software. JavaScript is
JavaScript was initially created to "make platform independent scripting
webpages alive". The programs in this language. Any JavaScript-enabled
language are called scripts. browser can understand and
3.1.1 Features of JavaScript : interpreted JavaScript code. Due to
different features, JavaScript is known
• JavaScript is light weight scripting
as universal client side scripting
language because it does not support
language.
all features of object oriented
programming languages.
35
There are two types of scripting : Server validation purpose and effectively
side scripting and Client side scripting. minimize the load to the server.
Client-side Scripting : In this type, the 5. Special software (web server
script resides on client computer (browser) software) is required to execute
and that can run on the client. Basically, server-side script, whereas client side
these types of scripts are placed inside an scripts requires web browser as an
HTML document. interface.
Server-side Scripting : In this type, the Do you know?
script resides on web server. To execute
There are some popular framework /
the script it must be activated by client libraries.
then it is executed on web server.
 Angular JS : It is a java script based
3.1.2 Difference between Server side open source frontend web framework
scripting and client side scripting devloped mainly for single page
application.
1. Server-side scripting is used at the
backend, where the source code is not  Vue JS : It is javascript based frame
visible or hidden at the client side work for building interactive user
interface (UI). It can be easly
(browser). On the other hand, client-
integrated with other projects and
side scripting is used at the frontend
libraries.
which users can see from the browser.
 React : It consists of javascript
So Server-side scripting is more secure
libraries for building UI for single
than client-side scripting.
page application and mobile
2. When a server-side script is processed application.
it communicates to the server. As
against, client-side scripting does not 3.2 Switch case and Looping Structures
need any server interaction.
Previous year we have learnt different
3. The client-side scripting language basic syntax of javascript such as variable
involves languages such as HTML5, declaration, if structure, function etc. Let
JavaScript etc. In contrast, us learn some extra features:
programming languages such as PHP,
[Link], Ruby, ColdFusion, Python, 3.2.1 Switch Case statement
C# etc. are server side scripting JavaScript has a built–in multiway
languages. decision statement known as Switch. The
4. Server-side scripting is useful in switch statement test the value of given
customizing the web pages and expression against a list of case values
implements the dynamic changes in and when match is found, a block of
the websites. Conversely, the client- statement associated with that case is
side scripts are generally used for executed. There should not be duplicity
36
between the cases. The value for the case Output :
must be similar data type as the variable
in switch. The default statement is not
mandatory.
Syntax :
switch(expression)
{
case value1:
statement block 1;
break; Note : 'language' attribute of <Script>
case value2: is replaced by 'type' attribute in all the
statement block 2; programs as it is standardised.
break;
………….... 3.2.2 Looping Statement
case value n:
While creating programming logic,
statement block n;
break; we need to execute some statements
default: repeatedly. Iteration refers to the
statement block ; execution of statement or a group of
} statements of code for a fixed number of
times or till the condition is satisfied. The
Program : condition should be boolean condition.
<!DOCTYPE html> Some commonly used JavaScript looping
<head><title>Javascript Program statements are:
</title></head>
<body> 1. for…….loop
<h1> use of switch case </h1> This loop executes statements as
<script type="text/javascript"> long as condition becomes true,
var day=6; control comes out from the loop
switch(day) when condition becomes false.
{
Benefit of for-loop is that it combines
case 1: alert("Monday"); break;
case 2: alert("Tuesday"); break; initialization, condition and loop
case 3: alert("Wednesday"); break; iteration (increment or decrement) in
case 4:alert("Thursday"); break; single statement.
case 5: alert("Friday"); break;
case 6: alert("Saturday"); break; Syntax :
case 7: alert("Sunday"); break;
default: alert("Invalid day"); for(initialization;condition;iteration)
} {
</script></body></html> statement block;
}
37
Initialization is assigning initial value condition always true then loop would be
to the variable, which executes only once, executed infinitely so after some execution
and then the condition is checked. Loop condition becomes false.
will execute statements in statement
block till the condition is true. When Example :
condition becomes false control is
transferred out of the loop and it will var i=1
execute remaining program. Iteration while(i<=5)
means increment or decrement value of a {
running variable. [Link](i);
i=i+1;
Example :
Output:
}
for(i=1;i<=5;i++)
1
{ 2
[Link](i); 3 Program for loop
} 4
5
<!DOCTYPE html>
for(i=5;i>=1;i--) Output: <head><title>Table-I</title>
5
{ 4
<script type="text/javascript">
[Link](i); 3 function display()
} 2
1 {
var i,a;
2. While…..loop a=[Link]
for(i=1;i<=10;i++)
This loop executes statements as long
{
as the condition is true. As soon as
[Link](a*i + "<br/>");
condition becomes false control
}
comes out of the loop.
}
Syntax: </script></head>
initialization; <body>
while(condition) <form name="form1">
{ Enter number to display table:-
statement block;
} <input type="text" name="t1">
<input type="button" value=" Display
The statement within the loop may be Table" onClick="display()">
a single line or a block of statements. If </body>
the statement within loop is a single line </html>
then the curly parenthesis is optional.
Here loop will be executed repeatedly as
long as the condition is true. Note that if

38
Output : Break and continue statements
Break statement is used to jump out
of loop. It is used to make an early exit
from a loop. When keyword break is
encountered inside the loop, control
automatically passes to the next statement
after the loop.
Do it yourself Sometimes in looping it may be
necessary to skip statement block and
Find syntax of do…..while() loop and
take the control at the beginning for next
difference between while() and do...
iteration. This is done by using ‘continue’
while() loop.
statement in JavaScript.

Program :
<!DOCTYPE html>
<html><head><title>Prime number</title>
<script type="text/javascript">
function display()
{
var a,ans;
a=parseInt([Link]);
ans=1;
for(i=2;i<a;i++)
{
if(a%i==0)
{
ans=0;
break;
}
}
if(ans==1)
alert("Number is prime");
else
alert("Number is not prime");
}
</script></head>
<body>
<h1 align="center"> Program to check number is prime or not </h1>
<form name="form1" style="text-align:center">
Enter your Number (Greater than one):-<input type="text" name="t1"> <br>
<input type="button" value="check Prime number" onClick="display()">
</body></html>
39
Output : Properties and methods of object's are
accessed with '.' operator. JavaScript
supports 2 types of objects built-in objects
and user defined objects.
1. Built in objects such as Math, String,
Array, Date etc.
2. JavaScript gives facility to create user
defined objects as per user
requirements. The ‘new’ keyword is
used to create new object in JavaScript.
e.g.
d= new Date();
3.3 Objects in JavaScript // ‘d’ is new instance created for Date object.
JavaScript is an object based scripting
language. Almost everything is an object DOM (Document Object Model) :
in JavaScript. A JavaScript object is an When HTML document is loaded into
entity having state (properties) and a web browser, it becomes a document
behavior (methods). An object can group object. It defines logical structure of
data together with functions needed to document. The way in which HTML
manipulate it. Look around you, you will document content is accessed and
find many examples of real world objects. modified is called as Document Object
Such as table, board, television, bicycle, Model. It is programming interface for
shop, bus, car, monitor etc. All these HTML and XML (Extensible Markup
tangible things are known as objects. Language) documents.
Take an example of car object. It has The standardization of DOM was
properties like name, model, weight, founded by W3C (World Wide Web
color etc. and methods like start, stop, Consortium) which works for
brake etc. All cars have same properties standardization of web technologies.
but contain different values from car to According to W3C :
car. All cars have same methods but
perform differently. "The W3C Document Object Model
Object Properties Methods (DOM) is a platform and language-
[Link]=Ferrari [Link]()
neutral interface that allows programs
[Link]=F430 [Link]() and scripts to dynamically access and
car update the content, structure, and style of
car. weight=1517kg [Link]()
[Link]=red [Link]() a document."

40
Following diagram shows hierarchy of The innerHTML Property
DOM object: The innerHTML property is useful for
getting html element and changing its
content. The innerHTML property can be
used to get or change any HTML element,
including <html> and <body>.

<!DOCTYPE html>
<html>
Fig. 3.1 Document Object Model
<head>
Following are some of the predefined <script type="text/javascript">
methods and properties for DOM object.
function changeText3()
Property Description
{
head Returns the <head>
element of the var style="<h2 style= 'color:green'>";
document var text="Welcome to the HTML5 and
title Sets or returns title Javascript";
of the document.
URL Returns full URL var closestyle="</h2>";
of the HTML [Link]('para').
document. innerHTML =style+text+closestyle;
body, img Returns <body>,
<img> elements }
respectively. </script></head>
Method Description <body style="background-
write() Writes HTML
expressions or color:cyan">
JavaScript code to <h1 align="center">
a document.
<p id="para">Welcome to the site</p>
writeln() Same as write(),
but adds a newline <input type="button"onclick="
character after "changeText3()" value="click this
each statement. button to change above text">
getElementById() There are many
ways of accessing </h1>
form elements, of </body>
which the easiest is
by </html>
getElementById()
method. In which
id property is used
to find an element.
41
Output :

Before button click After button click

Window Object :
At the very top of the object hierarchy is the window object. Window object is
parent object of all other objects. It represents an open window in a browser. An object
of window is created automatically by the browser. Window object represents an open
window in a browser. An object of window is created automatically by the browser.
Following table shows some of the methods and properties for window object.
Property Description
name Sets or returns the name of a window.
location Returns the Location object for the window.
document Returns the Document object for the window.
closed Returns a Boolean value indicating whether a window has been
closed or not.
Method Description
alert() Displays the alert box containing message with ok button.
confirm() Displays the confirm dialog box containing message with ok
and cancel button.
prompt() Displays a dialog box to get input from the user.
open() Opens the new window.

close() Closes the current window.


blur() Removes focus from the current window.
focus() Sets focus to the current window.
print() Prints the content of current window.
setTimeout() Calls a function or evaluates an expression after a specified
number of milliseconds.

42
Program : Program :
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title >Window Opener and Closer
<script type="text/javascript">
</title>
function sampleFunction()
<script type="text/javascript"> {
function makeNewWindow() [Link](next(), 4000);
{ }
var newwin=[Link](); function next()
[Link]("<h1>This is {
new window</h1>"); alert("4 seconds have passed");
[Link]. }
backgroundColor="skyblue"; </script></head>
} <body style="background-color:cyan">
</script></head> <h1 align="center">
<body><form> Click button and wait for message
<input type="button" value="Create </h1>
New Window" <input type="button" value="Timeout
onClick="makeNewWindow()"> function"
</form></body> onClick="sampleFunction()">
</html> </body>
</html>
Output : Output :

43
Do it yourself
1. Write JavaScript program to display status"Hi this is status
property"in status bar of window.
2. Write JavaScript program to set three different background color to
webpage on onClick, onMousemove and onMouseover events of button
object.

3.4 JavaScript Event


Events are actions done by the user or an application that occurs on the webpage.
In previous year we studied different keyboard events (onKeypress, onKeydown,
onkeyup) and mouse events (onClick, onMousemove, onMouseout, onMouseover).
Similarly there are some more events used with form objects.
Input and other object Events:

Event handler Description

onblur It occurs when user leaves field or losses focus of an element.


onfocus It occurs when an element gets focus.
onchange It occurs when user changes content of an element or selects
dropdown value. E.g. for textbox, password, select box, textarea
etc.
onselect It occurs when user selects some text of an element.
onsubmit It occurs when user clicks submit button.
onreset It occurs when user clicks reset button.
onload It occurs when page/image has been loaded.
onunload It occurs when document/page has been unloaded or closes.

3.5 JavaScript Built-in Objects


JavaScript has several built-in or core language objects. These built-in objects are
available regardless of window content and operates independently of whatever page
browser has loaded. These objects provide different properties and methods that are
useful while creating live web pages.

44
String Object :
String is used to store zero or more characters of text within single or double quotes.
String object is used to store and manipulate text.
Property Description
length Returns the number of characters in a string
Method Description
charAt() Returns the character at the specified position (in Number).
indexOf() Returns the index of the first occurence of specified character in
given string, or -1 if it never occurs, so with that index you can
determine if the string contains the specified character.
lastIndexOf() Returns the index of the last occurence of specified character in
given string.
substr() Returns the characters you specified: (14,7) returns 7 characters,
from the 14th character.
substring() Returns the characters you specified: (7,14) returns all characters
between the 7th and the 14th.
trim() The trim() method removes whitespace from both sides of a
string
toLowerCase() Converts a string to lower case
toUpperCase() Converts a string to upper case
Example :
var str="Information Technology";
[Link] ("length of string is :-" + [Link]);
[Link] ("Substring is :-" + [Link] (12,10));
Output :
Length of string is :-22
Substring is :- Technology
Math Object :
The built-in Math object includes mathematical constants and functions. You do
not need to create the Math object before using it. Following table contains list of math
object methods: e.g. var x=56.899; alert([Link](x));
Method Description
abs(x) Returns the absolute value of a number.
cbrt(x) Returns the cube root of a number.
Returns the next integer greater than or equal to a given number
ceil(x)
(rounding up).
45
Method Description
Returns the next integer less than or equal to a given number (rounding
floor(x)
down).
max(x, y, ...) Returns the highest-valued number in a list of numbers.
min(x, y, ...) Returns the lowest-valued number in a list of numbers.
pow(x, y) Returns the base to the exponent power, that is, xy.
random(x) Returns a random number between 0 and 1 (including 0, but not 1).
sqrt(x) Returns the square root of a number.

Do it yourself
1. Write event driven JavaScript program to take number as user input and find its
square root and cube root.

Date Object :
The date object is used to create date and time values. It is created using new
keyword. There are different ways to create new date object.
var currentdate=new Date();
var currentdate=new Date(milliseconds);
var currentdate=new Date(dateString);
var currentdate=new Date(year, month, day, hours, minute, seconds, milliseconds);
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits).
getHours() Returns the hour (from 0-23).
getMinutes() Returns the minutes (from 0-59).
getMonth() Returns the month (from 0-11).
getSeconds() Returns the seconds (from 0-59).
getTime() Returns the number of milliseconds since midnight Jan 1, 1970.
now() Returns the number of milliseconds since midnight Jan 1, 1970.
setDate() Sets the day of the month of a date object.
setFullYear() Sets the full year of a date object.
setHours() Sets the hours of a date object.
setMinutes() Set the minutes of a date object.
setMonth() Sets the month of a date object.
setSeconds() Sets the seconds of a date object.
setTime() Sets a date to a specified number of milliseconds after/before Jan 1,
1970.
46
Number Object :
It helps us to work with numbers. Primitive values (like 34 or 3.14) cannot have
properties and methods, but with JavaScript it is available with primitive values.
Property Description
MIN_VALUE Returns the largest minimum value.
MAX_VALUE Returns the largest maximum value.
NaN It represents ‘Not a Number’ value.
Method Description
isInteger() It determines whether the given value is a Integer
parseFloat() It converts the given string into a floating point number.
parseInt() It converts the given string into a integer number.
isFixed() It returns the string that represents a number with exact digits
after a decimal point.
Array Object :
An array is an object that can store a collection of items. JavaScript arrays are
used to store multiple values in single variable. An array is a special variable which
can hold more than one value at a time. Arrays become really useful when you need
to store large amounts of data of the same type. You can create an array in JavaScript
as given below.
var fruits=["Mango","Apple","Orange","Grapes"];
OR
var fruits=new Array("Mango","Apple","Orange","Grapes");
You can access and set the items in an array by referring to its indexnumber and
the index of the first element of an array is zero. arrayname[0] is the first element,
arrayname[1] is second element and so on.
e.g. var fruitname=fruits[0];
[Link]("demo").inner HTML=fruits[1];

Property Description
index The property represents the zero-based index of the match in the string
length Reflect number of elements in array.
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
copyWithin() Copies array elements within the array, to and from specied positions.

47
Method Description
Returns the value of the first element in an array that satisfies a test
find() in testing.
forEach() Calls a function for each array element.
indexOf() Search the array for an element and returns its position.
isArray() Checks whether an object is an array.
pop() Removes the last element of an array, and returns that element.
push() Adds new elements to the end of an array, and returns the new length.
reverse() Reverses the order of the elements in an array.
sort() Sorts the elements of an array.
Program Using array object :

<!DOCTYPE html>
<html><head>
<title>use of array methods</title>
</head>
<body style="color:blue;background-color:pink;font-size:30px">
<script type="text/javascript">
var city = ['Pune', 'Kolhapur', 'Mumbai', 'Nashik', 'Latur', 'Nagpur'];
[Link]("Original array elements are <br>");
[Link](city);
[Link]("<br><br>Copy elements at end to the beginning <br>");
[Link]([Link](0, 3));
city = ['Pune', 'Kolhapur', 'Mumbai', 'Nashik', 'Latur', 'Nagpur'];
[Link]("<br><br>Copy elements at the beginning to the end<br>");
[Link]([Link](3, 0));
city = ['Pune', 'Kolhapur', 'Mumbai', 'Nashik', 'Latur', 'Nagpur'];
[Link]("<br><br>Copy first 3 elements to middle<br>");
[Link]([Link](2, 0, 3));
city = ['Pune', 'Kolhapur', 'Mumbai', 'Nashik', 'Latur', 'Nagpur'];
[Link]("<br><br>Adding an element to an array<br>");
[Link]([Link]('Kokan'));
[Link](city);
[Link]("<br><br>Reversing an array element <br>");
[Link]([Link]());
</script> </body></html>

48
Output :

Validation program in JavaScript :


<!DOCTYPE html>
<html><head><title>Pincode Validation</title></head>
<body style="color:blue;background-color:cyan"><form name="form1">
<h1 align="center">
Enter Pincode value:-<input type="text" name="t1"><br><br>
<input type="button" value="Submit value" onClick="validate()"></h1>
<script type="text/javascript">
function validate()
{
var pincode; pincode=[Link];
if([Link]==0)
{
alert("please check, enter value");
[Link]();
}
else if([Link](pincode))
{
alert("please, enter integer number only");
[Link]();
}
else if([Link]<6||[Link]>8)
{
alert("pincode length range between 6 to 8");
[Link](); }
else
alert("Pincode is accepted");
}
</script> </body></html>

49
Note : islnteger() is supported by version Mozilla Firefox 16 and higher.

Do it yourself
1. Find more Math object methods useful for trigonometric functions.
2. Write JavaScript Program to create simple calculator using JavaScript Math
object.

Summary

 JavaScript is light weight scripting language. It is platform independent language.


 There are two types of scripts; client side script and server side scripts. Client side
scripts reside on client machine and server side script resides on web server.
 JavaScript provide ‘switch…case’ as multi way decision statement.
 For....loop, while…loop and do…while are commonly used looping structures in
JavaScript.
 DOM (Document Object Model) is a programming interface for HTML and XML
documents. It defines logical structure of document.
 Window object is parent object of all other objects hence its methods can be used
without specifying it.
 JavaScript is event based language support objects events such as onBlur, onFocus,
onChange, onSelect, onSubmit, onLoad, onUnload, onResize etc.
 JavaScript supports built-In objects such as Date, String, Math, Number and array
etc. These objects contain number of properties and methods that are useful while
creating interacting web pages.

50
Exercise
Q.1 Fill in the blanks. c) Both a and b
1. -------------script resides on server d) None of the above
computer. 2. Select correct method name of
2. --------- statement is used to jump String object---------------------.
out of loop. a) charAt() b) characterAt()
3. ------------------ defines logical c) valueAt() d) lengthAt()
structure of document. 3. ---------------- method displays
4. ---------------- property of window message box with Ok and Cancel
object returns Boolean value in- button.
dicating whether window is a) Confirm() b) Alert()
closed or not. c) both a and b d) None of these
5. -------------------- event occurs 4. We can declare all types of vari-
when an element looses its focus. ables using keyword ------------.
Q.2. State whether given statement is a) var b) dim
true or false. c) variable d) declare
1. JavaScript is case sensitive 5. Trace ouput of following
language. JavaScript code.
2. [Link]() function is used to var str="Information
return the nearest integer less Technology";
than or equal to given number. [Link]
3. MAX_VALUE property of (str. lastIndexOf("o");
number object returns smallest
a) 18 b) 19
possible value.
c) 20 d) 21
4. getDay() method of Date object
returns month in number. Q.4. Multiple choice questions. Select
two correct answer.
5. onKeydown event occurs when
user moves mouse pointer. 1. Valid two methods of Date object
are ---------------- and -------------.
Q.3. Multiple choice questions. Select
a) setTime()
one correct answer.
` b) getValidTime()
1. JavaScript is ----------------------
language. c) getTime()
a) Compiled d) setValidTime()
b) Interpreted

51
2. Properties of document object are Q.6 Explain the following.
---------------- and ----------------. 1. What are similarities and
a) URL b) title differences between client side
scripting and server side scripting.
c) name d)status
2. Briefly explain features of
3. ---------- and ----------- are event / JavaScript.
event handler used with text 3. Explain switch….........case
object in JavaScript. conditional statement in
a) onBlur b) onMove JavaScript with example.
c) onFocus d) onAction Q.7 Write event driven JavaScript
Q.5 Multiple choice questions. Select program for the following.
three correct answers. 1. Display Addition, multiplication,
division and remainder of two
1. Select three correct methods of
numbers, which were accepted
window object----------------
from user.
a) write() b) alert()
2. Display number sequence from
c) writeln() d) close() 100 to 150 in following format.
e) open() f) charAt()
(100 101 102.............150)
2. JavaScript features are -----------
3. Find and display factorial of
------------ , ---------------and ------
given number.
-----------.
a) supports event based facilities 4. Accept any string from user and
count and display number of
b) is platform dependent vowels occurs in it.
language
Q.7 Match the following.
c) case insensitive scripting
language A B
d) provide inbuilt objects ceil() Writes HTML expression or
e) can handle date and time javascript code to a
effectively document.
f) requires special software to floor() Sets focus to current window.
run write() Removes white spaces from
both sides of string.
3. Inbuilt objects in JavaScript are focus() Returns next integer greater
-----------------, ---------------- and than or qual to to given
--------------. number.
a) Time b) Date trim() Returns the next integer less
than or equal to given
c) Inheritance d) Array number.
e) Number f) function

52
1. Find the area of following figure:
1. Area of Circle
<! DOCTYPE html><html><head><title></title></head>
<body><script language="JavaScript">
var r, area;
r=prompt ("Enter r");
area=3.14*r*r;
document. write ("Area of Circle is:"+area);
</script></body></html>
2. Area of rectangle
<! DOCTYPE html><html>
<head><title> Area of rectangle</title></head><body>
<script language="JavaScript">
var l, b, area;
l=prompt ("Enter length");
b=prompt ("Enter breadth");
area=l*b;
document. write ("Area of rectangle is:"+area);
</script></body></html>
3. Area of Square
<! DOCTYPE html><html><head>
<title> Area of Square</title></head><body>
<script language="JavaScript">
var s, area;
s=prompt ("Enter side");
area=s*s;
document. write ("Area of Square is:"+area);
</script></body></html>
4. Area of Triangle
<! DOCTYPE html><html><head>
<title> Area of Triangle</title></head><body>
<script language="JavaScript">
var a, b, area;
a=prompt ("Enter a");
b=prompt ("Enter b");
area= (1/2) *a*b;
document. Write ("Area of Triangle is:"+area);
</script></body></html>

2. Find the factorial of following numbers


<! DOCTYPE html><html><head>
<script type="text/JavaScript">
var i, fact=1;
var n=parseInt (prompt ("Enter a number:"));
for(i=1;i<=n;i++)
{
fact=fact*i;
}
[Link]("Factorial of "+n+" is:"+fact);
</script></head><body></body></html>
3. Write a program for Fibonacci series
<! DOCTYPE html><html><head>
<script type="text/JavaScript">
var a=0, b=1, c, i=1;
document. write (a+" "+b);
var n=parseInt (prompt ("Enter a number:"));
while(i<=n)
{
c=a+b;
document. Write (c+" ");
a=b;
b=c;
i++;
}
</script></head><body></body></html>
4. WRITE PROGRAM TO VALIDATE FORM USING JAVASCRIPT USER DEFINED FUNCTION.
<! DOCTYPE html><html><head>
<script type="text/JavaScript">
function validate ()
{
if (document. [Link]=="")
{
alert ("Please provide your name!");
document. myform. Name. Focus ();
return false;
}
if([Link]=="")
{
alert("Please provide your Email!");
[Link]();
return false;
}
if (document. [Link]=="“) ||
isNaN (document. [Link]) ||
[Link]!=6)
{
alert("Please provide your Zip on the format######.");
[Link]();
return false;
}
if([Link]=="-1")
{
alert("Please provide your Country!");
return false;
}
return(true);
}
</script></head><body>
<form name="myForm" onsubmit="return (validate ());">
Name:<input type="text" name="Name"><br>
Email:<input type="text" name="EMail"><br>
Zip code:<input type="text" name="Zip"><br>
Country:<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">INDIA</option>
<option value="2">USA</option>
<option value="3">UK</option>
</select>
<input type="submit" value="Submit">
</form></body></html>
5. WRITE PROGRAM IN JAVASCRIPT FOR ARMSTRONG NUMBER.
<! DOCTYPE html><html>
<head>
<script type="text/JavaScript">
var n=parseInt(prompt("Enter a number:"));
[Link](n);
var r,ans=0;
var num=n;

while(num>0)
{
r=num%10;
ans=ans+(r*r*r);
num=[Link](num/10);
}
if(n==ans)
{
[Link]("Armstrong number");
}
else
{
[Link]("no armstrong number");
}
</script>
</head>
<body>
</body>
</html>
6. WRITE JAVASCRIPT PROGRAM FOR FINDING BMI.
<! DOCTYPE html><html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript">
var height, weight;
height=prompt("Enter height");
weight=prompt("Enter weight");
c=weight/(height**2);
[Link]("BMI is:"+c);
</script>
</body>
</html>
7. WRITE A PROGRAM IN JAVASCRIPT FOR FABONACCI SERIES.
<! DOCTYPE html><html>
<head>
<script type="text/JavaScript">
var a=0, b=1, c, i=1;
[Link](a+" "+b);
var n=parseInt(prompt ("Enter a number:"));
while(i<=n)
{
c=a+b;
[Link](c+" ");
a=b;
b=c;
i++;
}
</script>
</head>
<body>
</body>
</html>
8. WRITE JAVASCRIPT PROGRAM FOR FINDING GREATER NUMBER.
<! DOCTYPE html><html>
<head><title></title></head>
<body>
<script language="JavaScript">
var a,b;
a=prompt("Enter a");
b=prompt ("Enter b");
if(a>b)
{
[Link]("a is greater than b");
}
else
{
[Link]("b is greater than a");
}
</script>
</body>
</html>
9. WRITE JAVASCRIPT PROGRAM FOR LOOPING STATEMENT.
<! DOCTYPE html><html>
<head>
<title>Looping Statements</title>
</head>
<body>
<script type="text/JavaScript">
[Link]("For Loop");
[Link]("<br>");
for(var i=10;i>=1;i--)
{
[Link](i+"<br>");
}
[Link]("<br>");
[Link]("While Loop");
[Link]("<br>");
var e=11;
while(e<=20)
{
if(e%2==0)
{
[Link](e+"<br>");
}
e++;
}
[Link]("<br>");
[Link]("Do While Loop");
[Link]("<br>");
a=1;
do
{
[Link](a);
a++;
}while(a<1);
</script>
</body>
</html>
10. WRITE JAVASCRIPT PROGRAM TO FIND ODD OR EVEN NUMBER.
<! DOCTYPE html><html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript">
var a, b;
a=prompt("Enter a");
if(a%2==0)
{
[Link]("no is even");
}
else
{
[Link]("no is odd");
}
</script>
</body>
</html>
11. WRITE HTML CODE TO CREATE HYPERLINK ON WEB PAGE.
<! DOCTYPE html><html>
<head>
<title>Hyperlinks</title>
</head>
<body>
<p align="center">First page</p>
<p align="center"><a href="[Link]">Links to second page</a></p>
</body>
</html>
12. WRITE JAVASCRIPT PROGRAM FOR PALINDROM.
<! DOCTYPE html><html>
<head>
<script type="text/javascript">
var n=parseInt(prompt("Enter a number:"));
[Link](n);
var r,ans=0;
var num=n;

while(num>0)
{
r=num%10;
ans=(ans*10)+r;
num=[Link](num/10);
}
if(n==ans)
{
[Link]("is palindrome");
}
else
{
[Link]("is palindrome");
}
</script>
</head>
<body>
</body>
</html>
13. WRITE JAVASCRIPT PROGRAM FOR PYTHAGORAS.
<! DOCTYPE html><html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript">
var a,b,c,d;
a=prompt("Enter a");
b=prompt("Enter b");
c=(a*a+b*b);
d=[Link](c);
[Link]("Hypotenuse is:"+d);
</script>
</body>
</html>
14. WRITE JAVASCRIPT PROGRAM FOR RAISED TO
<! DOCTYPE html><html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript">
var a,b,c,d;
a=prompt("Enter a");
b=prompt("Enter b");
c=a**b;
[Link]("n1 raised to i is:"+c);
</script>
</body>
</html>
15. WRITE JAVASCRIPT PROGRAM TO FIND NUMBER OF WORDS IN SENTENCE.
<! DOCTYPE html><html>
<head>
<script type="text/javascript">
var s=prompt("enter a sentence","");
var count=0;
for(i=0;i<[Link];i++)
{
if([Link](i,1)==" ")
count++;
}
[Link]("no of words in a sentence is = " + (count+1));
</script>
</html>
16. WRITE JAVASCRIPT PROGRAM FOR CALCULATOR
<! DOCTYPE html><html>
<head>
<script language="javascript">
function calc()
{
var n1,n2,opr,x;
n1=parseInt([Link]);
n2=parseInt([Link]);
opr=[Link];
if(opr=="add")
x=n1+n2;
else if(opr=="sub")
x=n1-n2;
else if(opr=="multi")
x=n1*n2;
else if(opr=="div")
x=n1/n2;
else
alert("please select operator")
[Link]("ans").innerHTML="answer is:"+x;
}
</script>
</head>
<body>
<form name="f1">
Number 1:
<select name="s1" size=1>
<option>Select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select><br>
Operator:
<select name="s2" size=1>
<option>Select</option>
<option value="add">+</option>
<option value="sub">-</option>
<option value="multi">*</option>
<option value="div">/</option>
</select><br>
Number 2:
<select name="s3" size=1>
<option>Select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<input type="button" value="calculate" onclick="calc()">
</form>
<p id="ans"></p>
</body>
</html>
17. WRITE JAVASCRIPT PROGRAM FOR SUM OF TWO NUMBERS.
<! DOCTYPE html><html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript">
var a,b,U,V;
a=prompt("Enter a");
b=prompt("Enter b");
U=parseInt(a);
V=parseInt(b);
var c;
c=U+V;
[Link]("sum is:"+c);
</script>
</body>
</html>
18. WRITE JAVASCRIPT PROGRAM FOR SUMMATION OF TWO NUMBER.
<! DOCTYPE html><html>
<head>
<title></title>
</head>
<body>
<script language="JavaScript">
var a,b,U,V,c;
a=prompt("Enter a");
b=prompt("Enter b");
c=a+b;
[Link]("summation is:"+c);
</script>
</body>
</html>
19. WRITE JAVASCRIPT PROGRAM FOR SUM OF DIGITS.
<! DOCTYPE html><html>
<head>
<script type="text/javascript">
var n=parseInt(prompt("Enter a number:"));
[Link](n);
var r, sum=0;
while(n>=1)
{
r=n%10;
sum=sum+r;
n=[Link](n/10);
}
[Link]("Sum of digit :"+sum);
</script></head><body></body></html>
20. WRITE JAVASCRIPT PROGRAM FOR CALLING FUNCTIONS
<! DOCTYPE html><html>
<head><title>Function program</title>
<script language="javascript"> function show()
{
alert("Welcome to function");
}
</script></head>
<body bgcolor="green">
<h1> Use of Function in Javascript </h1>
<script language="javascript"> show () ;//calling of function
</script> </body></html>

21. WRITE JAVASCRIPT PROGRAM FOR FUNCTION CHECK.


<! DOCTYPE html>
<html><head><title>conditional statement</title>
<script language="javascript"> function check()
{
var age; age=[Link]; if(age>=18)
alert("Qualifies for driving"); else
alert("Does not qualifies for driving");
}
</script></head><body>
<form name="form1"><center>
Enter your age: -
<input type="text" name="t1"><br><br>
<input type="button" value="SUBMIT" onClick="check()">
</form></body></html>
22. WRITE JAVASCRIPT PROGRAM FOR UPPERCASE FUNCTION
<! DOCTYPE html>
<html><head><title>Uppercase function</title>
<script language="javascript"> function display()
{
var a; a=[Link]
[Link]=[Link]()
}
</script></head>
<body><form name="form1"> Enter string value:-
<input type="text" name="t1"><br><br>
<input type="button" value="Press button" onKeyPress="display()">
Uppercase String is:-
<input type="text" name="t2"></form></body></html>

-END-

You might also like