0% found this document useful (0 votes)
1 views36 pages

JavaScript Mca Unit 3

JavaScript is a lightweight, object-based scripting language created by Brendan Eich in 1995, primarily for client-side web development. It features dynamic typing, a range of data types, and supports various operators and control statements, while also having limitations such as lack of file access and multithreading. The document covers variable declaration, functions, recursion, global functions, and arrays, providing examples and syntax for each concept.

Uploaded by

ravirampaul1416
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)
1 views36 pages

JavaScript Mca Unit 3

JavaScript is a lightweight, object-based scripting language created by Brendan Eich in 1995, primarily for client-side web development. It features dynamic typing, a range of data types, and supports various operators and control statements, while also having limitations such as lack of file access and multithreading. The document covers variable declaration, functions, recursion, global functions, and arrays, providing examples and syntax for each concept.

Uploaded by

ravirampaul1416
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
You are on page 1/ 36

Unit III

Java script

JavaScript is an object-based scripting language and it is light


weighted. It is first implemented by Netscape (with help from
Sun Microsystems). JavaScript was created by Brendan Eich at
Netscape in 1995 for the purpose of allowing code in web-pages
(performing logical operation on client side).

Features of javascript
 JavaScript is a object-based scripting language.
 Giving the user more control over the browser
 It is used to perform client side validations.
 Build small but complete client-side programs .
 It Handling dates and time.
 It is light weighted.
 JavaScript is a scripting language and it is not java.
 JavaScript is case sensitive.
 JavaScript is object based language as it provides
predefined objects.
 Most of the javascript control statements syntax is same as
syntax of control statements in C language.
 An important part of JavaScript is the ability to create new
functions within scripts. Declare a function in JavaScript
using function keyword.
Limitations of JavaScript
1
JavaScript have some limitations they are;
 Client-side JavaScript does not allow the reading or writing
of files.
 It cannot be used for networking applications because there
is no such support available.
 It doesn't have any multithreading or multiprocessor
capabilities.

Variable Declaration
Java script did not provide any data types for declaring variables
and a variable in java script can store any type of value. Hence
java script is loosely typed language. We can use a variable
directly without declaring it.
Only var keyword are use before variable name to declare any
variable.
Syntax
var x;
Rules to declaring a variable
 Name must start with a letter (a to z or A to Z), underscore(
_ ), or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example
value1.
 Javascript variables are case sensitive, for example x and X
are different variables.

2
JavaScript Data Types
There are eight basic data types in JavaScript. They are:

Data
Description Example
Types

String represents textual data hello' , "hello world!" etc

Number an integer or a floating-point number 3 , 3.234 , 3e-2 etc.

900719925124740999n , 1n
BigInt an integer with arbitrary precision
etc.

Boolean Any of two values: true or false true and false

a data type whose variable is not


undefined let a;
initialized

Null denotes a null value let a = null;

data type whose instances are unique


Symbol let value = Symbol('hello');
and immutable

Object key-value pairs of collection of data let student = { };

Here, all data types except Object are primitive data types,
whereas Object is non-primitive.
3
Types of Variable in JavaScript
 Local Variable
 Global Variable
Local Variable
A variable which is declared inside block or function is
called local variable. It is accessible within the function.
A global variable is accessible from any function. A variable i.e.
declared outside the function or declared with window object is
known as global variable

// program to display welcome to javascript


<html>
<head>
<script language="javascript">
document.writeln("welcome to java script");
</script></head></html>
// program to format the text
<html><head>
<script language="javascript">

4
document.writeln("<u><h1 align=center>html</h1></u>");
document.writeln("<font color=red>html stands for hypertext
markup language</font>");

</script>
</head>
</html>
JavaScript Dialog boxes
All JavaScript dialog box is a predefined function which is used
to perform different tasks. Some functions are given below;

Function Description
alert() To give alert message to user.
prompt() To input value from user
To get confirmation from user before executing some
confirm()
task.

Alert()
Alert function of java script is used to give an alert message to
the user.
prompt()
Prompt function of java script is used to get input from the user.
confirm()
5
confirm function of java script is used to get confirmation from
user before executing some task.
Program to accept your name and display that
<html>
<head>
<script language="javascript">
var name;
name=prompt("enter ur name");
document.writeln("hello "+name);
</script>
</head>
</html>
Acccept a color and display that as background to the body
<html>
<head>
<script language="javascript">
var co;
co=prompt("enter a colorname");
document.bgColor=co;

6
</script>
</head>
<body>

// program for adding two nos


<html>
<head>
<script language="javascript">
var a,b,c;
a=parseInt(prompt("enter a no"));
b=parseInt(prompt("enter another no"));
c=a+b;
document.writeln("sum = "+c);
</script>
</head></html>
// program to find square and cube of a number
<html>
<head>
<script language="javascript">
7
var n;
n=parseInt(prompt("enter a no"));
document.writeln("suare is "+(n*n));
document.writeln("<br>cube is "+(n*n*n));
</script>
</head>
<h2> refresh the page to enter another number</h2>
</html>

//changing background color


<html>
<head>
<script language="javascript">
var co;
co=prompt("enter a colorname");
document.bgColor=co;
</script></head>
<body>
<h2>refresh the page to enter another color</h2>

8
</body></html>

Operators in java script


 Java script support following operators
 Arithmetic operators (+, -, *, /, %)
 Relational operators (< ,<= , > , >=, = =.!=)
 Logical operators (&&, ||, !AND OR NOT)
 Assignment operators (=, +=, -= , *=, /=, %=)
 Increment, decrement operators (++, --)
 Conditional operators (?, :)
// program for arithmetic operations
<html>
<head>
<script language="javascript">
var a,b,add,sub,mul,div;
a=parseInt(prompt("enter a number"));
b=parseInt(prompt("enter another number"));
add=a+b;
sub=a-b;
mul=a*b;

9
div=a/b;
document.writeln("add="+add);
document.writeln("sub="+sub);
document.writeln("mul="+mul);
document.writeln("div="+div);
</script></head><body>
<h2>refresh the page to enter another numbers</h2>
</body></html>

Control statements
These are used to control the flow of the program
according to the user requirement.
There are 2 types of control statements.
1.Conditional statements (Decision making statements)
if, if else, if else ladder, nested if, switch
2. Loop statements ( Iterative statements)
while, do while, for

10
program to test number is positive or not
<html>
<head>
<script language="javascript">
var n;
n=parseInt(prompt("enter a no"));
if(n>0)
document.writeln("positive no");
else
document.writeln("negagive no");
</script></head>
<body>
<h2> refresh the page to test another number</h2>
</body></html>
// program to display 1 to 10 numbers
<html>
<head>

11
<title> loop</title>
<script language="javascript">
var i;
i=1;
while(i<=10)
{
document.writeln(i+ " ");
i++;
}
</script></head></html>

programs
 test given number is odd or even
 accept two number and find out the maximum
number if they are same display both are equal
 find out the maximum of given three numbers
 accept a number and display the day of the week
using switch
 program to print 1 to 10 numbers using while, do
while and for

12
Functions
Function is self contained block which will perform a
particular task.
Modules in the java script are called as functions. There are
two types of functions
1.pre packaged function (pre defined )
2.user defined functions
The prepackaged functions are those already defined by the
java script and make it available with the objects. The
prepackaged functions that belongs to java script objects are
called methods.
Ex: max(), min(), parseInt(), parseFloat(), random() ….

User defined functions


The functions which are defined by the user are called user
defined functions.
Syntax:
function functionname(arguments)
{
Statements
}

13
A function will be called using function name followed by the
parameters
Ex: add(5,6);

// adding two nos using functions


<html>
<head>
<script language="javascript">
var a,b,c;
a=parseInt(prompt("enter a number"));
b=parseInt(prompt("enter another number"));
c=add(a,b);
document.writeln("sum="+c);
function add(x,y)
{
return(x+y);
}
</script>

14
</head>
</html>
// program to find out max from two nos using functions
// program to accept a no and find out cube of that using
funcitons

recursion
if a function call itself then it is called function recursion
// program to find out factorial of given no using function
recursion
<html>
<head>
<script language="javascript">
var n;
n=parseInt(prompt("enter a number"));
document.writeln("factorial of "+n+" is " +fact(n));
function fact(n)
{
if(n==0||n==1)

15
return 1;
else
return n*fact(n-1);
}
</script>
</head>
</html>

Iteration vs recursion
1.both iteration and recursion are based on control statements.
The iteration uses the repetitions structure such as while, do
while and for where as recursion uses a selection structure
such as if , if else
2. Both recursion and iteration involves repetition . iteration
explicitly uses a repetition structure , recursion achieves
repetition throw the repeated function calls
3. Both will involve termination test. iteration terminates
when the loop continuous condition fails, recursion terminates
when the base case is recognized
4. both iteration and recursion can occur infinitely when the
given condition is not satisfied

16
Conclusion
Recursion has many negative points. It repeatedly invokes the
mechanism and consequently overhead of function calls. This
effect cab be expensive in both process time and memory
space. Each recursion call causes another copy of a function
can be created. Iteration normally occurs with in a function so
that overhead of repeated function calls and extra memory
assignment is omitted. Any problem can be solved recursively
or non recursively. The recursion approach is normally
chosen in preference to iterative approach when recursive
approach is easier to understand and dubug.

Global functions
Java script provides 7 functions that are available globally in the script.
These functions are called global functions.
escape()
unescape()
eval()
isfinite(0
isNaN()
parseInt()
parseFloat()

17
escape() :-this function will take string as an argument and written a
string in which all the spaces, punctuations, any other characters that are
not in the ASCII character set are encoded to the hexa decimal format.
Ex: document.wirteln(escape(“this is test”))
o.p this%20is%20test
unescape() :- this function takes string as argument and written a string
in which all the characters that are previously encoded with escape() are
decoded
ex:
s1=”this is test”;
s2=escape(s1);
document.write(unescaped(s2));
o/p : this is test

eval() :- this function takes string as an argument representing javascirpt


code to execute. Javascript interpreter evaluate the code and execute it
when the eval() is called
ex: a=4;
b=5;
document.writeln(eval(“a+b”));
o/p 9
isFinite() :- this function takes an argument and returns true if the value
of the argument is a finite number other wise return false

18
ex: document.writeln(isFinite(5)): true
document.writeln(isFinite(“a”)); false
isNaN() :- this function takes an argument and returns true if the value of
the argument is a not a number other wise return false
ex: document.writeln(isFinite(5)): false
document.writeln(isFinite(“a”)); true
parseInt() :-this function takes string as an argument and attempts to
convert in to integer value. If conversion is not successful It will return
NaN
ex: document.writeln(parseInt(“123”)); o/p 123
document.writeln(parseInt(“abc”)); o/p NaN

parseFloat() :-this function takes string as an argument and attempts to


convert in to floating point value. If conversion is not successful It will
return NaN
ex: document.writeln(parseFloat(“123.5”)); o/p 123.5
document.writeln(parseFloat(“abc”)); o/p NaN
// example program for global functions
<html>
<head>
<script language="javascript">
a=5;

19
b=6;
document.writeln(escape("This is a test"));
document.writeln("<br>");
document.writeln(eval("a+b") + "<br>");
document.writeln(isFinite(5));
document.writeln(isFinite("c") + "<br>");
document.writeln(isNaN("5") + "<br>");
document.writeln(isNaN("c") + "<br>");
s1="This is a test line";
s2=escape(s1);
document.writeln(s2);
s3=unescape(s2);
document.writeln("<br>");
document.writeln(s3);
</script>
</head>
</html>

20
Arrays
Group of variables referred by single name which are similar
type is called an array
We can locate a particular element of an array using array name
and its position number. The array positions are starts from o to
size-1 of the array
An array in java script is an Array object..we have to use new
operator to allocate the memory for an array dynamically.
Syntax
var arrayname=new Array(size);
Ex:
var a=new Array(5); // int a[5];
Here the individual elements of an array are
a[0],a[1],a[2],a[3],a[4]

Initializing an array
Var a=new Array(10,20,30,40,50);
Var a=[10,20,30,40,50];
The length of the array can be determined by using length
property
21
Ex: a.length; -> 5
Storing and displaying values from an array
<html><head>
<script language="javascript">
var a=new Array(5);
for(i=0;i<5;i++)
a[i]=parseInt(prompt("enter a number"));
for(i=0;i<5;i++)
document.writeln(a[i] + " ");
</script></head></html>
//Max from array
<html>
<head>
<script language="javascript">
var a=new Array(5);
for(i=0;i<5;i++)
a[i]=parseInt(prompt("enter a number"));
max=a[0];
for(i=0;i<a.length;i++)
{
if(a[i]>max)
22
max=a[i];
}
document.writeln("max=" +max);
</script>
</head>
</html>

References and reference parameters


There are two types of parameter passing techniques. They are
1. Call by value
2. Call by reference

When the arguments are passed to functions by using call by value


a copy of argument value is passed to called function. The changes
to the called function copy do not affect the original values in
calling function. In the java script numbers, Boolean values are
passed to functions by using call by value technique.

When arguments are passed to functions by using call by reference


the caller gives the called functions to directly access the callers
data and modify that.
Call by reference can improve the performance because it
eliminates the overhead of copying large amount of data but it is
weaker in the security issue because called function can access the
calling data.

23
In java script all the objects and arrays are passed to functions by
using call by reference.

// program to passing array as parameter to function


(call by reference)
<html>
<head>
<script language="javascript">
var a=new Array(5);
for(i=0;i<a.length;i++)
a[i]=parseInt(prompt("enter a number"));
disp(a);
modi(a);
document.writeln("after modifying array values are");
disp(a);
function modi(x)
{
for(i=0;i<x.length;i++)
x[i]=x[i]+1;
}
function disp(x)
{
24
for(i=0;i<x.length;i++)
document.writeln(x[i] +" ");
}
</script></head></html>

Objects in java script


Objects encapsulate the data and methods . the data which is
used in the object are called as attributes, the methods which are
used in the object are called as behaviour.
Java script supports many number of objects like window,
document, Math,Date,Array,String,Boolean, Number etc.

Math object
Java script provides a Math object which contain the functions called
mathematical functions are used to perform mathematical operations.
They are
abs(x)
it will return the absolute value of x;
ex: Math.abs(5); -> 5
Math.abs(-6);; -> 6

25
ceil(x)
return the smallest integer which is greater than or equal to x.
ex: Math.ceil(9.2); -> 10
Math.ceil(-10.4); ->-10
floor(x)
return the largest integer which is smaller than or equal to x
Math.floor(9.2); -> 9
Math.floor(-10.4); -> -11

sin(x)
return the trigonometric sine of x
ex: Math.sin(90*Math.PI/180); -> 1
cos(x)
return the trigonometric cosine of x
ex: Math.cos(90*Math.PI/180); -> 0
tan(x)
return the trigonometric tangent of x
ex: Math.tan(45*Math.PI/180); -> 1
max(x,y)
return the maximum value from x,y;
ex:Math.max(5,7); -> 7
26
min(x,y)
return the minimum value from x,y;
ex: Math.min(5,7); -> 5
pow(x,y)
return the x raised to power y i.exy
ex: Math.pow(2,3); -> 8
round(x)
round the x to closest integer
ex: Math.round(7.6); ->8
Math.round(7.2); -> 7

Example program
<html>
<head>
<script language="javascript">
document.writeln(Math.abs(-5));
document.writeln("<br>"+Math.abs(8));
document.writeln("<br>"+Math.ceil(5.8));
document.writeln("<br>"+Math.floor(5.3));
document.writeln("<br>"+Math.round(7.8));
document.writeln("<br>"+Math.round(7.3));
27
document.writeln("<br>"+Math.max(9,7,4,10));
document.writeln("<br>"+Math.min(4,2,9,1));
document.writeln("<br>"+Math.sin(90*Math.PI/180));
document.writeln("<br>"+Math.cos(0*Math.PI/180));
document.writeln("<br>"+Math.tan(45*Math.PI/180));
</script>
</head>
</html>

string object
Java script provides a string object which contain the functions called
string functions are used to perform string operations. They are
charAt(index)
return the character at the specified index. If no character at specified
index then it return empty string. The first character is located at index 0
toLowerCase()
it will convert the string from upper case to lower case
toUpperCase()
it will convert the string from lower case to uppercase
substr(startindex,length)
28
it will return the substring from given string from specified starting
index to given length
ex: a=”welcome”;
a.substr(2,4); ->lcom
substring(startindex,endindex)
return the substring of given string from starting index to end-1 index
ex: a=”welcome”;
a.substring(2,4); -> lc
fontColor(color)
wrap the source string in<font> and </font>
ex: a.fontColor(“red”); -><font color=”red”> welcome</font>
fontSize(size)
wraps the source string in <font> and </font>
ex: a.fontSize(5); -><font size=”5”> welcome</font>

big()
wrap the source string in <big> and </big>
ex: a.big(); -><big>welcome</big>

blink()
wrap the source string in <blink> and </blink>

29
ex: a.blink(); -><blink>welcome</blink>
bold()
wrap the source string in <b> and </b>
ex: a.bold(); -><b>welcome</b>
fixed()
wrap the source string in <tt> and </tt>
ex: a.fixed(); -><tt>welcome</tt>
italics()
wrap the source string in <i> and </i>
ex: a.italics(); -><i>welcome</i>
small()
wrap the source string in <small> and </small>
ex: a.small(); -><small>welcome</small>
strike()
wrap the source string in <strike> and </strike>
ex: a.strike(); -><strike>welcome</strike>
sub()
wrap the source string in <sub> and </sub>
ex: a.big(); -><sub>welcome</sub>
sup()
wrap the source string in <sup> and </sup>
30
ex: a.sup(); -><sup>welcome</sup>
example program

<html>
<head>
<script language="javascript">
var s1;
s1="welcome";
document.writeln(s1.charAt(2));
document.writeln("<br>"+s1.toLowerCase( ));
document.writeln("<br>"+s1.toUpperCase( ));
document.writeln("<br>"+s1.substr(2,4));
document.writeln("<br>"+s1.substring(2,5));
document.writeln("<br>"+s1.big( ));
document.writeln("<br>"+s1.small( ));
document.writeln("<br>"+s1.blink( ));
document.writeln("<br>"+s1.bold( ));
document.writeln("<br>"+s1.italics( ));
document.writeln("<br>"+s1.strike( ));
document.writeln("<br>"+s1.fixed( ));
document.writeln("<br>"+s1.fontcolor("red"));
31
document.writeln("<br>"+s1.sub( ));
document.writeln("<br>"+s1.sup( ));
</script>
</head>
</html>

Date object
This object provides methods for date and time manipulations.
The date functions are
getDate()
return the date i.e number from 1 to 31
ex:var d=new Date( );
d.getDate( );

getDay()
return the day number i.e number from 0 (Sunday) to 6
(Saturday)
ex:var d=new Date( );
d.getDay( );
getMonth()

32
return the month part from the date i.e 0 (jan) to 11 (dec)

getFullYear()
return the four digit format of the year
ex:var d=new Date( );
d.getFullYear( );

getHours()
return the hours part from time
ex:var d=new Date( );
d.getHours( );

getMinutes()
return the minutes part from time
ex:var d=new Date( );
d.getMinutes( );

getSeconds()
return the seconds part from time
ex:var d=new Date( );
d.getMinutes( );

33
example program

<html>
<head>
<script language="javascript">
var d=new Date( );
document.writeln(d.getDate( ));
document.writeln("<br>"+d.getDay( ));
document.writeln("<br>"+d.getMonth( ));
document.writeln("<br>"+d.getFullYear( ));
document.writeln("<br>"+d.getHours( ));
document.writeln("<br>"+d.getMinutes( ));
document.writeln("<br>"+d.getSeconds( ));
</script>
</head>
</html>

Boolean object
Java script provides Boolean and Number objects as object
wrappers for Boolean true/false values and numbers. When the
Boolean value is required in the java script program

34
automatically it creates Boolean object to store the value. We
can create Boolean object explicitly as followes
Var a =new Boolean(booleanvalue);
If Boolean values is false, 0, null, Number.Nan or empty string
or no argument is specified then Boolean object contains false
other wise it contains true
The methods supplied by Boolean object are
toString(),valueOf()

Number object
Java script automatically create number object to store numeric
values. We can create number object explicitly as follows
Var n=new Number(numeric value);
The methods provided by number object are toString(radix),
valueOf().
<html>
<head>
<script language="javascript">
var b=new Boolean(0);
document.writeln(b.toString());
document.writeln(b.valueOf());

var n=new Number(5);


35
document.writeln(n.toString(2));
document.writeln(n.valueOf());
document.writeln(Number.MAX_VALUE);
document.writeln(Number.MIN_VALUE+"<br>");
document.writeln(Number.NaN+"<br>");
document.writeln(Number.POSITIVE_INFINITY+"<br>");
</script>
</head>
</html>

36

You might also like