0% found this document useful (0 votes)
101 views

Java Script

JavaScript is a client-side scripting language that is commonly used to make web pages interactive. It can be included in HTML pages using <script> tags and is interpreted by browsers rather than compiled. JavaScript allows elements on web pages to change dynamically in response to user actions or input. Some key uses of JavaScript include form validation, generating dropdown menus, displaying clocks and calendars, and opening dialog boxes.

Uploaded by

kskchari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Java Script

JavaScript is a client-side scripting language that is commonly used to make web pages interactive. It can be included in HTML pages using <script> tags and is interpreted by browsers rather than compiled. JavaScript allows elements on web pages to change dynamically in response to user actions or input. Some key uses of JavaScript include form validation, generating dropdown menus, displaying clocks and calendars, and opening dialog boxes.

Uploaded by

kskchari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Downloaded from: www.sucomputersforum.com Web Technologies B.

Sc(Sem-VI)

UNIT-III
JAVA SCRIPT
Introduction:-
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to interact
with the user and make dynamic pages. It is an interpreted programming language with object-
oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers
JavaScript is a programming language that can be included on web pages to make them more
interactive. You can use it to check or modify the contents of forms, change images, open new
windows and write dynamic page content. You can even use it with CSS to make DHTML (Dynamic
HyperText Markup Language). This allows you to make parts of your web pages appear or disappear
or move around on the page.
JavaScripts only execute on the page(s) that are on your browser window at any set time.
When the user stops viewing that page, any scripts that were running on it are immediately stopped.
The only exceptions are cookies or various client side storage APIs, which can be used by many
pages to store and pass information between them, even after the pages have been closed.
Java script is easily to code and increase the functionality of html.Java script, we can design
dynamic and interactivity WebPages easily.Java script, script are small pieces of code which perform
a single, relative simple task.
Java script, scripts are interpreter where as programs like c and c++ are compiled programs
are converted into binary code (0,1).They can be run directly by the operating system of the
computer .Compiled programs are platform dependent but interpreter programs are platform
independent and can be run everywhere.Java script is platform independent can be run
everywhere.Java script is a client side scripting language as well as server’s side scripting language.
Client-Side and Server-Side JavaScript:-
JavaScript is a client-side scripting language, which means the source code is processed by
the client's web browser rather than on the web server. This means JavaScript functions can run after
a webpage has loaded without communicating with the server. For example, a JavaScript function
may check a web form before it is submitted to make sure all the required fields have been filled out.
The JavaScript code can produce an error message before any information is actually transmitted to
the server.
Like server-side scripting languages, such as PHP and ASP, JavaScript code can be inserted
anywhere within the HTML of a webpage. However, only the output of server-side code is displayed
in the HTML, while JavaScript code remains fully visible in the source of the webpage. It can also be
referenced in a separate .JS file, which may also be viewed in a browser.
Application of JavaScript:-
JavaScript is used to create interactive websites. It is mainly used for:
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
 Displaying clocks etc.
Features of Java script:-
 Java script is an object based language that is confined to run within the web browsers only.
 Java script in an interpreter language so we need complication steps.
 Java script can directly embed in html.

R.Prashanth Kumar M.C.A 1


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

 Java script is loosely typed language i.e. one data type can be automatically converted into
other types without explicitlyconversion.
 Java script is platform independent but browser dependent.
 The Java script application work on any machine that has an appropriate java script inbuilt
browser installed.
 A java script program develop an unique machine will work perfectly an windows machine
will work perfectly an windows machine.
 Java scripts supports events based programming.
 JavaScript is a case-sensitive language.
 Java scripts are multiple functional i.e. it can be used at aclient side scripting as well as
server side scripting.
 It is the default scripting language for most web browsers.
 It is a light weighted.
 The same character (+) is used for addition and concatenation.
Implementation of JavaScript:-
JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web
page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these
tags as a script. A simple syntax of your JavaScript will appear as follows.
Syntax:-

<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
 Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript.
 Type − This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javascript".
Syntax:-

<script language = "javascript" type = "text/javascript">


JavaScript code
</script>
Sample Program:-
Let us take a sample example to print out "Hello World". Here we call a function
document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both.
Example:-
<html>
<body>
<scriptlanguage="javascript"type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Output:-
Hello World!

R.Prashanth Kumar M.C.A 2


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Whitespace and Line Breaks:-


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can
use spaces, tabs, and newlines freely in your program and you are free to format and indent your
programs in a neat and consistent way that makes the code easy to read and understand.
Semicolons are Optional:-
Simple statements in JavaScript are generally followed by a semicolon character, just as they
are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your
statements are placed on a separate line. For example, the following code could be written without
semicolons.
<scriptlanguage="javascript"type="text/javascript">
var1 =10
var2 =20
</script>
But when formatted in a single line as follows, you must use semicolons −
<scriptlanguage="javascript"type="text/javascript">
var1 =10; var2 =20;
</script>
Note − It is a good programming practice to use semicolons.
Case Sensitivity:-
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization of
letters.
So the identifiers Total and TOTAL will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.
Comments in JavaScript:-
JavaScript supports both C-style and C++-style comments, Thus −
 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.
Example:-
<scriptlanguage="javascript"type="text/javascript">
<!--
// This is a comment. It is similar to comments in C++

* This is a multi-line comment in JavaScript


//-->
</script>
The Document Object:-
A document is a webpage that is being either displayed or created. The document has a
number of properties that can be accessed by JavaScript by programs and used to manipulate the
content of the page.
When an HTML document is loaded into a web browser, it becomes a document object.
The document object is the root node of the HTML document and the “owner” of all other nodes.

R.Prashanth Kumar M.C.A 3


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Properties and methods of Document object:-


write() Method:-
The write() method writes HTML expressions or JavaScript code to a document.The write()
method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete
all existing HTML.
Note: When this method is not used for testing, it is often used to write some text to an output
stream opened by the document.open() method. See "More Examples" below.
Ex:
document.write(“Hello”);
document.write(”<h1>Nalanda</h1>”);
writeln() Method:-
The document.writeln() method is similar to write(), only it adds a newline character after
each statement.
Ex:-
document.write(“Hello”);
document.write(”<h1>Nalanda</h1>”);
Creating a JavaSrcipt Program:-
JavaScript program can be created in following ways
1. Script in <head>...</head> section.
2. Script in <body>...</body> section.
3. Script in <body>...</body> and <head>...</head> sections.
4. Script in an external file and then include in <head>...</head> section.
1. JavaScript in <head>...</head> section:-
If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows –
<html>
<head>
<script type = "text/javascript">
<!--
function f1()
{
alert("Hello Nalanda")
}
//-->
</script>
</head>

<body>
<input type = "button" onclick = "f1()" value = "Say Hello" />
</body>
</html>
Output:-

Click the above button then it display the following window

R.Prashanth Kumar M.C.A 4


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

2. JavaScript in <body>...</body> section:-


If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript.
Example:-
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello Nalanda")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
Output:-
Hello Nalanda
This is web page body
3. JavaScript code in <head> and <body> section altogether as follows
JavaScript code can be created in both head and body section

<html>
<head>
<script type = "text/javascript">
<!--
function f1()
{
alert("Hello Nalanda")
}
//-->
</script>
</head>

<body>
<script type = "text/javascript">
<!--
document.write("Hello Nalanda")
//-->
</script>
<input type = "button" onclick = "f1()" value = "Say Hello" />
</body>
</html>
Output:-

Click the above button then it display the following window

R.Prashanth Kumar M.C.A 5


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

4. JavaScript in External File


As you begin to work more extensively with JavaScript, you will be likely to find that there
are cases where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it into
your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.
<html>
<head>
<scripttype="text/javascript"src="filename.js"></script>
</head>

<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can use
sayHello function in your HTML file after including the filename.js file.
function f1()
{
alert("Hello Nalanda")
}
JavaScript Data types:-
Data type tells which type of data stored in a variable and how much of memory required for
that variable.
JavaScript allows you to work with three primitive data types −
 Numbers, eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
Note − JavaScript does not make a distinction between integer values and floating-point values. All
numbers in JavaScript are represented as floating-point values.
Variables:-
Variable means name of the memory location. Variable are used to store the data. Variable
value change at the time of program execution.
‘‘var’’ key word is used to declared variable in JavaScript. Variable must be declared before
they are used in the program.
Syntax:-
var var1,var2,var3……………….var n
Rules of Naming a variable:-
1. Variable name is always starting with alphabets or underscore.

R.Prashanth Kumar M.C.A 6


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

2. Variable name should not a keyword.


3. Variable name should not be duplicate.
4. Variable name should not have any white space or special symbols
5. Variable names are case-sensitive. For example, Name and name are two different
variables..
Initialization of variable:-
Storing a value in a variable is called variable initialization. You can do variable
initialization at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it
later. For another variable, you can assign a value at the time of initialization as follows
var sname ="Giri";
var age;
age =20;
Note :- Use the var keyword only for declaration or initialization, once for the life of any variable
name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change during
the execution of a program and JavaScript takes care of it automatically.
Variable Scope:-
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
 Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
Local variable:-
A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only.
For example:-
<script>
function abc()
{
var x=10;//local variable
}
</script>
Global variable:-
A JavaScript 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.
For example:-
<html>
<script>
var A=20;//gloabal variable
function a()
{
document.writeln(A);
}
function b()
{
var A=100;
document.writeln(A);

R.Prashanth Kumar M.C.A 7


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

}
a();//calling JavaScript function
b();
</script>
</html>
Output:-
20
100
Declaring JavaScript global variable within function:-

To declare JavaScript global variables inside function, you need to use window object.
For example:-
window.value=90;
Now it can be declared inside any function and can be accessed from any function.
For example:-
function m()
{
window.value=100;//declaring global variable by window object
}
function n()
{
alert(window.value);//accessing global variable from other function
}
JavaScript Reserved Words(Key Words):-
A list of all the reserved words in JavaScript are given in the following table.
They cannot be used as JavaScript variables, functions, methods, loop labels, or any object
names.

Abstract Boolean break byte case catch char


class const continue debugger default delete do
double do double else enum export extends
false final finally float for function goto
if implements import in instanceof int interface
long native new null package private protected
public return short static super switch synchronized
this throw throws transient true try typeof
var void volatile while with.

Operators:-
An Operator is symbol which can perform a task. JavaScript supports the following types of
operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators:-
 Arithmetic operators are used to perform mathematical operations between numeric
operands.

R.Prashanth Kumar M.C.A 8


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Operator Description
+ Adds two numeric operands.
- Subtract right operand from left operand
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two operands.
++ Increment operator. Increase operand value by one.
-- Decrement operator. Decrease value by one.
<html>
<body>
<script language="javascript">

var x = 5, y = 10, z = 15;


document.write(x + y); //returns 15
document.write("<br>");
document.write(y - x); //returns 5
document.write("<br>");
document.write(x * y); //returns 50
document.write("<br>");
document.write(y / x); //returns 2
document.write("<br>");
document.write(x % 2); //returns 1
document.write("<br>");
document.write(x++); //returns 6
document.write("<br>");
document.write(x--); //returns 4
</script>

</body>
</html>
Output:-
15
5
50
2
1
5
6
Note: “ + ”Operator performs concatenation operation when one of the operands is of string type.
The following example shows how + operator performs operation on operands of different data
types.
var a = 5, b = "Hello ", c = "World!", d = 10;
a + b; // "5Hello "
b + c; // "Hello World!"
a + d; // 15
The following example demonstrates how arithmetic operators perform different tasks on operands.

R.Prashanth Kumar M.C.A 9


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Comparison Operators
JavaScript language includes operators that compare two operands and return Boolean value true or
false.
Operators Description
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type.
!= Compares inequality of two operands.
Checks whether left side value is greater than right side value. If yes
>
then returns true otherwise false.

< Checks whether left operand is less than right operand. If yes then
returns true otherwise false.
Checks whether left operand is greater than or equal to right operand.
>=
If yes then returns true otherwise false.
Checks whether left operand is less than or equal to right operand.
<=
If yes then returns true otherwise false.

Example program for Comparison Operators :-


<html>
<body>
<script type = "text/javascript">
<!--
var a = 5, b = 10, c = "5";
var x = a;
document.write(a == c); // returns true
document.write("<br>");
document.write(a === c); // returns false
document.write("<br>");
document.write(a == x); // returns true
document.write("<br>");
document.write(a != b); // returns true
document.write("<br>");
document.write(a > b); // returns false
document.write("<br>");
document.write(a < b); // returns true
document.write("<br>");
document.write(a >= b); // returns true
document.write("<br>");
document.write(a <= b); // returns true
document.write("<br>");
document.write(a >= c); // returns true
document.write("<br>");
document.write(a <= c); // returns true
//-->
</script>
</body>
</html>

R.Prashanth Kumar M.C.A 10


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Logical Operators:-
Logical operators are used to combine
two or more conditions. JavaScript includes
following logical operators.
Operator Description
&& is known as AND operator. It checks whether two operands are non-zero
&& (0, false, undefined, null or "" are considered as zero), if yes then returns 1
otherwise 0.
|| is known as OR operator. It checks whether any one of the two operands is
||
non-zero (0, false, undefined, null or "" is considered as zero).
! is known as NOT operator. It reverses the boolean result of the operand (or
!
condition)
Example program for Logical Operators:-

<html>
<body>
<script type = "text/javascript">
<!--
var a = 5, b = 10;
document.write((a != b) && (a < b)); // returns true
document.write("<br>");
document.write((a > b) || (a == b)); // returns false
document.write("<br>");
document.write((a < b) || (a == b)); //
returns true
document.write("<br>");
document.write(!(a < b)); // returns
false
document.write("<br>");
document.write(!(a > b)); // returns
true
//-->
</script>
</body>
</html>
Output:-

Assignment Operators:-
JavaScript includes assignment operators to assign values to variables with less key strokes.
Assignment
Description
operators

= Assigns right operand value to left operand.


+= Sums up left and right operand values and assign the result to the left operand.
Subtract right operand value from left operand value and assign the result to the
-=
left operand.
*= Multiply left and right operand values and assign the result to the left operand.

R.Prashanth Kumar M.C.A 11


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Assignment
Description
operators
Divide left operand value by right operand value and assign the result to the left
/=
operand.
Get the modulus of left operand divide by right operand and assign resulted
%=
modulus to the left operand.

Example program for Assignment operators :-


<html>
<body>
<script language="javascript">
var x = 5, y = 10, z = 15;
document.write(x = y); //x would be 10
document.write("<br>");
document.write(x += 1); //x would be 6
document.write("<br>");
document.write(x -= 1); //x would be 4
document.write("<br>");
document.write(x *= 5); //x would be 25
document.write("<br>");
document.write(x /= 5); //x would be 1
document.write("<br>");
document.write(x %= 2); //x would be 1
</script>
</body>
</html>
Output:-
10
11
10
50
10
0

Conditional (or ternary) Operators:-

JavaScript includes special operator called ternary operator :? that assigns a value to a
variable based on some condition. This is like short form of if-else condition.
Syntax:-

<condition> ? <value1> : <value2>;


Ternary operator starts with conditional expression followed by ? operator. Second part (
after ? and before : operator) will be executed if condition turns out to be true. If condition becomes
false then third part (after :) will be executed.
Example program for Ternary operator:-

<html>
<body>
<script type = "text/javascript">
<!--
R.Prashanth Kumar M.C.A 12
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

var a = 10, b = 5;
var c = a > b? a : b; // value of c
would be 10
document.write("c value is ",+c);
document.write("<br>");
var d = a > b? b : a;
// value of d would be 5
document.write("d value is ",+d);
document.write("<br>");
//-->
</script>
</body>
</html>
Output:-

Points to Remember : -
1. JavaScript includes operators that perform some operation on single or multiple operands
(data value) and produce a result.
2. JavaScript includes various categories of operators: Arithmetic operators, Comparison
operators, Logical operators, Assignment operators, Conditional operators.
3. Ternary operator ?: is a conditional operator.
Bitwise Operators
JavaScript supports the following bitwise operators −Assume variable A holds 2 and variable B
holds 3, then −
Sr.No. Operator & Description
& (Bitwise AND)
1 It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
3 arguments. Exclusive OR means that either operand one is true or
operand two is true, but not both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of
places specified in the second operand. New bits are filled with zeros.
5
Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by
6 the number of bits specified by the right operand.
Ex: (A >> 1) is 1.

R.Prashanth Kumar M.C.A 13


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

>>> (Right shift with Zero)


This operator is just like the >> operator, except that the bits shifted in on
7
the left are always zero.
Ex: (A >>> 1) is 1.
<html>
<body>
<scripttype="text/javascript">
<!--
var a =2;// Bit presentation 10
var b =3;// Bit presentation 11
document.write("(a & b) => ");
document.write((a & b));
document.write(“<br>“);
document.write("(a | b) => ");
document.write((a | b));
document.write(“<br>“);
document.write("(a ^ b) => ");
document.write((a ^ b));
document.write(“<br>“);
document.write("(~b) => ");
document.write((~b));
document.write(“<br>“);
document.write("(a << b) => ");
document.write((a << b));
document.write(“<br>“);
document.write("(a >> b) => ");
document.write((a >> b));
document.write(“<br>“);
//-->
</script>
</body>
</html>

Output:-
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string,
or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
R.Prashanth Kumar M.C.A 14
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Object "object"
Function "function"
Undefined "undefined"
Null "object"
<html>
<body>
<scripttype="text/javascript">
<!--
var a =10;
var b ="String";
var“<br>“="<br />";

result =(typeof b =="string"?"B is String":"B is Numeric");


document.write("Result => ");
document.write(result);
document.write(“<br>“);

result =(typeof a =="string"?"A is String":"A is Numeric");


document.write("Result => ");
document.write(result);
document.write(“<br>“);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...

Control Statements/Control Constructs:-


A program is a set of statements which are normally executed sequentially in the order in
which they appear.We have a number of situations where we may have to change the order of
execution of statements based on the certain conditions or repeat a group of statement until certain
specific condition is met.
Java Script supports the following Control statements…
1. Conditional Statements.
2. Looking Statements.
3. Jumping Statements.
1. Conditional Statement:-
A conditional statement is basically used to test a condition. The result determines which
statement or block of statements to be executed and which are not to be executed.

In Java Script we have the following conditional statements:-


if...else Statement:-
While writing a program, there may be a situation when you need to adopt one out of a given
set of paths. In such cases, you need to use conditional statements that allow your program to make
correct decisions and perform right actions.

R.Prashanth Kumar M.C.A 15


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

JavaScript supports conditional statements which are used to perform different actions based
on different conditions.
if..else statement.:-
Flow Chart
The following flow chart shows how the if-else statement works.

JavaScript supports the following forms of if..else statement −


 if statement
 if...else statement
 if...else if... statement.
if statement:-
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression (condition) is evaluated. If the condition is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the times,
you will use comparison operators while making decisions.

Example
<html>
<body>
<scripttype="text/javascript">
<!--
var age =20;

if( age >18){


document.write("<b>Qualifies for vote </b>");
}
R.Prashanth Kumar M.C.A 16
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Qualifies for vote
Set the variable to different value and then try...
if...else statement:-
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax:-

if(expression)
{
Statement(s) to be executed if expression is true
}
else

{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block
are executed.
Example:-

<html>
<body>
<scripttype="text/javascript">
<!--
var age =15;

if( age >18){


document.write("<b>Qualifies for vote</b>");
}else{
document.write("<b>Does not qualify for vote</b>");
}
//-->
</script>
</body>
</html>
Output
Does not qualify for vote
if...else if... statement:-
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax:-

if (expression 1)
{

R.Prashanth Kumar M.C.A 17


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Statement(s) to be executed if expression 1 is true


}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
} else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part of
the else clause of the previous statement. Statement(s) are executed based on the true condition, if
none of the conditions is true, then the else block is executed.
Example:-
<html>
<body>
<scripttype="text/javascript">
<!--
var a = 10,b=20;
if( a>b ){
document.write("<b>A in Big</b>");
}elseif( a<b ){
document.write("<b>B is Big</b>");
}
else{
document.write("<b>Number are equal</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output
B isbig
Set the variable to different value and then try...
Switch Case:-
The switch case statement in JavaScript is also used for decision making purposes. In some
cases, using the switch case statement is seen to be more convenient over if-else statements.
Consider a situation when we want to test a variable for hundred different values and based on the
test we want to execute some task. Using if-else statement for this purpose will be less efficient over
switch case statements and also it will make the code look messy.
The switch case statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Flow Chart
The following flow chart explains a switch-case statement works.

R.Prashanth Kumar M.C.A 18


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Syntax:-
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case against
the value of the expression until a match is found. If nothing matches, a default condition will be
used.
switch (expression)
{
case condition 1:
statement(s)
break;

case condition 2:
statement(s)
break;
...

case condition n:
statement(s)
break;

default:
statement(s)
}

 expression can be of type numbers or strings.


 Dulplicate case values are not allowed.
 The default statement is optional. If the expression passed to switch does not matches with
value in any case then the statement under default will be executed.
 The break statement is used inside the switch to terminate a statement sequence.

R.Prashanth Kumar M.C.A 19


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

 The break statement is optional. If omitted, execution will continue on into the next case.

<html>
<head>
<title>Demo Switch case statement</title>
</head>
<body>
<script type = "text/javascript">
// JavaScript program to illustrate switch-case
var i = 9;
switch (i)
{
case 0:
document.write("i is zero.");
break;
case 1:
document.write("i is one.");
break;
case 2:
document.write("i is two.");
break;
default:
document.write("i is greater than 2.");
}

</script>
</body>
</html>

Output:-

Looping Statements:-
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.
JavaScript Support the following looping statements:-
1.while loop statement
2.do…while loop statement
3.for loop staement
1. The while Loop:-
While loop is an entry controlled looping statement. The purpose of a while loop is to
execute a statement or code block repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.

R.Prashanth Kumar M.C.A 20


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Flow Chart
The flow chart of while loop looks as follows −

Syntax
while (expression)
{
Statement(s) to be executed if expression is true
}

Statement-x;

Explanation:-
Whenever controller encounter the while statement it is initially check the condition if the
condition is true execute the body of the loop then the control transferred to while statement and
check the condition once again if the condition is true again execute the body of the loop this
processes will continue until the condition become false. if the condition become false the control
transfer to statement-x.
Example
<html>
<body>

<script type = "text/javascript">


<!--
var count = 0;
document.write("Starting Loop ");

while (count < 10) {


document.write("Current Count : " + count + "<br />");
count++;
}

R.Prashanth Kumar M.C.A 21


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

document.write("Loop stopped!");
//-->
</script>

</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
2. The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of
the loop. This means that the loop will always be executed at least once, even if the condition is
false. do…while loop is also called Exit-controlled looping statement.
Flow Chart
The flow chart of a do-while loop would be as follows −

Syntax
Do
{
Statement(s) to be executed;
}
while (expression);
statement-x
Note − Don’t miss the semicolon used at the end of the do...while loop.
Explanation:-
R.Prashanth Kumar M.C.A 22
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Whenever controller encounter the do… while statement it is initially execute the body of the
loop then after check the condition if the condition is true again execute the body of the loop this
processes will continue until the condition become false. if the condition become false the control
transfer to statement-x.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do {
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>
</body>
</html>
Output:-
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
3. for loop:-
The 'for' loop is the most compact form of looping. It includes the following three important parts –
 The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is true,
then the code given inside the loop will be executed, otherwise the control will come out of
the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax:-

for (initialization; test condition; iteration statement)

Statement(s) to be executed if test condition is true


}
Statement-x;
Flow Chart
The flow chart of a for loop in JavaScript would be as follows –

R.Prashanth Kumar M.C.A 23


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Explanation:-
Whenever controller encounter the for statement it is initialization the counter value and then
check the test condition if the condition is true execute the body of the loop then the control
transferred to for statement for increment/decrement the counter value by one and check the
condition once again if the condition is true again execute the body of the loop this processes will
continue until the condition become false. if the condition become false the control transfer to
statement-x.
Example
<html>
<body>
<scripttype="text/javascript">
<!--
var count;
document.write("Starting Loop"+"<br />");

for(count =0; count <10; count++){


document.write("Current Count : "+ count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6

R.Prashanth Kumar M.C.A 24


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
for...in loop:-
The for...in statement is used to loop (iterate) through the elements of an array or through the
properties of an object.
JavaScript For...In Statement
The for...in statement is used to loop (iterate) through the elements of an array or through the
properties of an object.
The code in the body of the for ... in loop is executed once for each element/property.
Syntax:-
for (variablename in object)
{
statement or block to execute
}
The variable argument can be a named variable, an array element, or a property of an object.
Example:-
Using for...in to loop through an array:
<html>
<body>
<script type="text/javascript">
var x
var mygroup = new Array()
mygroup[0] = "MStCS"
mygroup[1] = "MCCS"
mygroup[2] = "MPCs"
for (x in mygroup)
{
document.write(mygroup[x] + "<br />")
}
</script>
</body>
</html>
The for...in loop is used to loop through an object's properties.
break Statement:-
The break statement exits a switch statement or a loop (for, for ... in, while, do ... while).
When the break statement is used with a switch statement, it breaks out of the switch block. This will
stop the execution of more execution of code and/or case testing inside the block.
When the break statement is used in a loop, it breaks the loop and continues executing the code after
the loop (if any).
The break statement can also be used with an optional label reference, to "jump out" of any
JavaScript code block (see "More Examples" below).
Note: Without a label reference, the break statement can only be used inside a loop or a switch.
Example Program:-

<html>
<head>
<title>JavaScript Break Statement</title>
</head>
<body>

R.Prashanth Kumar M.C.A 25


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

<p>Loop breaks when i becomes equal to 5</p>


<p id="break_statement_para1"></p>
<script>
var text = "";
var i;
for(i = 0; i < 10; i++)
{
if(i === 5)
{
break;
}
text += + i + "<br>";
}
document.getElementById("break_statement_para1").innerHTML = text;
</script>

</body>
</html>
Here is the output produced by the above JavaScript break statement example program.

Here is the live demo output of the above break keyword example in JavaScript.
Loop breaks when i becomes equal to 5
0
1
2
3
4
Here is another example also demonstrates the use of break statement/keyword in JavaScript.
<HTML>
<HEAD>
<TITLE>JavaScript Break Statement Example</TITLE>
</HEAD>
<BODY>

<SCRIPT type="text/javascript">
var count=0;
R.Prashanth Kumar M.C.A 26
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

while(count<10)
{
++count;
if((count%5==0))
break;
else
document.write("count="+count+"<BR/>");
}
document.write("The while loop exited.");
</SCRIPT>

</BODY>
</HTML>
Here is the output produced by the above break example in JavaScript.

continue Statement:-
The continue statement breaks one iteration (in the loop) if a specified condition occurs, and
continues with the next iteration in the loop.
The difference between continue and the break statement, is instead of "jumping out" of a loop, the
continue statement "jumps over" one iteration in the loop.
However, when the continue statement is executed, it behaves differently for different types of loops:
 In a while loop, the condition is tested, and if it is true, the loop is executed again
 In a for loop, the increment expression (e.g. i++) is first evaluated, and then the condition is
tested to find out if another iteration should be done
The continue statement can also be used with an optional label reference.
Note: The continue statement (with or without a label reference) can only be used inside a loop.
<html>
<head>
<title>JavaScript continue Statement Example</title>
</head>
<body>

<p>Loop breaks when i becomes equal to 5</p>


<p id="continue_statement_para1"></p>
<script>
var text = "";
var i;
for(i = 0; i < 10; i++)
{

R.Prashanth Kumar M.C.A 27


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

if(i === 5)
{
continue;
}
text += + i + "<br>";
}
document.getElementById("continue_statement_para1").innerHTML = text;
</script>

</body>
</html>
It will skip to print the value 5, so it will display the following result:

Here is the live demo output of the above continue statement example program in JavaScript.
Loop breaks when i becomes equal to 5
0
1
2
3
4
6
7
8
9
Here is another example also demonstrates continue statement in JavaScript.
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>JavaScript continue Statement Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">

R.Prashanth Kumar M.C.A 28


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

var count=0;
while(count<10)
{
++count;
if(count%2==0)
continue;
else
document.write("count="+count+"<BR/>");
}
document.write("The while loop exited.");
</SCRIPT>
</BODY>
</HTML>

Output:-

Functions:-
A function is a group of reusable code which can be called anywhere in the program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions. This process is called modularity.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions.
JavaScript has two types of functions they are…
1.Built-in function. These function definition in built the library
2.User defined function. Theses function definition is defined by the user.
Creating User-Defined Function
Function Definition:-
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
<script type = "text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
R.Prashanth Kumar M.C.A 29
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Example

<scripttype="text/javascript">
<!--
function demo(){
alert("Hello Nalanda");
}
//-->
</script>
Calling a Function
Function can be called by using function name.
<html>
<head>
<scripttype="text/javascript">
function demo(){
document.write ("Hello Nalanda!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<inputtype="button"onclick="demo()"value="Say Hello">
</form>
</body>
</html>
Output
Click the following button to call the function

Hello Nalanda
Function Parameters
To pass different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those parameters. A function can
take multiple parameters separated by comma.
Example
<html>
<head>
<scripttype="text/javascript">
function demo(name, age){
document.write (name +" is "+ age +" years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<inputtype="button"onclick="demo('Raju', 15)"value="Say Hello">
</form>
R.Prashanth Kumar M.C.A 30
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

</body>
</html>
Output
Click the following button to call the function

Raju age is 15 years old


Parameter Rules:-
1. JavaScript function definitions do not specify data types for parameters.
2. JavaScript functions do not perform type checking on the passed arguments.
3. JavaScript functions do not check the number of arguments received.
Parameter Defaults
If a function is called with missing arguments (less than declared), the missing values are set to:
undefined
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:
function myFunction(x, y)
{
if (y === undefined)
{
y=0;
}
}
The return Statement
A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to return
their multiplication in your calling program.
Example:-
Try the following example. It defines a function that takes two parameters and concatenates them
before returning the resultant in the calling program.
<html>
<head>
<scripttype="text/javascript">
function demo(first, last){
var full;
full = first + last;
return full;
}
function secondFunction(){
var result;
result = demo('BSc','MStCs');
document.write (result );
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<inputtype="button"onclick="secondFunction()"value="Call Function">
</form>
</body>
R.Prashanth Kumar M.C.A 31
Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

</html>
Output
Click the following button to call the function

BSc MStCs
Function can also be defined in the following way…
Function Expressions:-
A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:
var x = function (a, b) {return a * b};
After a function expression has been stored in a variable, the variable can be used as a function:
var x = function (a, b)
{
return a * b
};
var z = x(4, 3);
The function above is actually an anonymous function (a function without a name).
Functions stored in variables do not need function names. They are always invoked (called) using the
variable name.
The function above ends with a semicolon because it is a part of an executable statement.
The Function () Constructor: -
Functions can also be defined with a built-in JavaScript function constructor called Function().
Example:-
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
You actually don't have to use the function constructor. The example above is the same as writing:
Example
var myFunction = function (a, b) {return a * b};
var x = myFunction(4, 3);
Self-Invoking Functions:-
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:
(function ()
{
var x = "Hello!!"; // I will invoke myself
})();
Recursive Function:-
Recursion is the process in which a function is called by itself, either directly or indirectly.
We will take the classic factorial function for the demonstration.
function factorial(n)
{
if (n <= 1)
{ return 1;
} else
{ return n * factorial(n - 1); }
}
`

R.Prashanth Kumar M.C.A 32


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

This is how it works. If ‘n’ is equal to one or zero, the factorial of ‘n’ is 1; otherwise, the factorial
of ‘n’is the product of ‘n’ and factorial of’ n – 1’.
The function seems to work fine initially. However, as mentioned in the Function type tutorial, the
name of a function is a pointer pointing to the function object.

Dialog Boxes:-
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users.
Alert Dialog Box:-
The alert() function display an alert box with a specified message and an OK button.An alert dialog
box is mostly used to give a warning message to the users. For example, if one input field requires
entering some text but the user does not provide any input, then as a part of validation, you can use
an alert box to give a warning message.
Alert box gives only one button "OK" to select and proceed.
<html>
<head>
<scripttype="text/javascript">
<!--
functionWarn(){
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<inputtype="button"value="Click Me"onclick="Warn();"/>
</form>
</body>
</html>

R.Prashanth Kumar M.C.A 33


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Confirmation Dialog Box:-


A confirm() function display a dialog box with a specified user's message, along with an OK and
Cancel button.If the user clicks on the OK button, the window method confirm() will return true. If
the user clicks on the Cancel button, then confirm() returns false. The confirm box takes the focus
away from the current window, and force the browser to read the message.
You can use a confirmation dialog box as follows.
Example:-

<html>
<head>
<scripttype="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal ==true){
document.write ("User wants to continue!");
returntrue;
}else{
document.write ("User does not want to continue!");
returnfalse;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<inputtype="button"value="Click Me"onclick="getConfirmation();"/>
</form>
</body>
</html>

R.Prashanth Kumar M.C.A 34


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Click the ‘click me button then it display the following window.

Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user input.
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 has two buttons: OK and Cancel. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user clicks the
Cancel button, the window method prompt() returns null.
Example:-
<html>
<head>
<scripttype="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ","your name here");
document.write("You have entered : "+ retVal);
}
//-->
</script></head>
<body>
<p>Click the following button to see the result:
</p>
<form>
<inputtype="button"value="Click
Me"onclick="getValue();"/>
</form>
</body>
</html>
Output:-

R.Prashanth Kumar M.C.A 35


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Arrays:-
In JavaScript, array is a single variable that is used to store different elements. It is often used
when we want to store list of elements and access them by a single variable. Unlike most languages
where array is a reference to the multiple variable, in JavaScript array is a single variable that stores
multiple elements. The maximum length allowed for an array is 4,294,967,295.
In JavaScript, We can access the data element wither sequentially by reading from the start of
array or by their index.
The starting index value of an array is zero and last index value of an array is length-1 (n-1).
By using arrays we can perform number of operations like inserting, deleting, finding,
searching and sorting the elements.
Arrays in JavaScript are simple built-in object. In JavaScript arrays can store dynamically
types and can increase the size dynamically.
Ex:- var data=[“sun””mun”,25,1.414];
The basic operations that are performed on arrays are creation, adding of elements, accessing
individual elements, removing elements, searching an array.

Creating an array:-
1. In JavaScript an array can be created in three different ways
Syntax:-
var arrayname=[Number of elements separated by commas];
Ex:- var days=[“Sun”,”Mon”,”Tue”,”Wed”];
2. To create an array object using the keyword “new”and set of elements to store.
Syntax:- var arrayname=new array[element 1,element 2,………,element n];
Ex:-var days=new array[“Sun”,”Mon”,”Tue”,”Wed”];
In this Construct the contents of array surrounded by parenthesis because they are permits to
construct array objects.
1. An empty array object which has space for a no.of elements can br stored.
Syntax:- var days=new array( );
 The above statement an array is created with no element.
 The actual size is decided dynamically depending on the elements to be assigned.
Adding element to an array:-
 An array elements add by using index of an array.
Ex:- var days[3]=”Wed”;
 In java script the array is dynamically increase and decrease its size means if an already
created with full of elements we can add a new element at the end of array.
Ex:- var data=[“Sun”,”Mon”] ; _____________1
data[2]=”Thu”; _______________2
data[20]=40;______________3
 The above code create an array of two elements in line ’1’
 A new element is added at position ‘2’ in line ‘2’.
 At the line ‘3’ an element is added to position 20 to do this the array is first expand and add
new element into the array.
Accessing array elements:-
 The elements in the array are accessed through their index.
 The accessing method is used to find the element and to change their values.
 The ‘length’ attribute is used to find the no.of elements have been stored.
WAP to accept no.of elements into the array and print.
<html>
<head>
<title>Accessing array elements</title>
</head>

R.Prashanth Kumar M.C.A 36


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

<body>
<script language=” java script ”>
var days =[“Sun”,”Mon”,”Tue”,”Wed”]
var n=length.days;
for( var i=0;i<n;i++)
{
document.write (days[ i ] , “ ,” );
}
</script>
</body>
</html>
Searching an element from array:-
 To search an array simply read element compare it with the value that we are looking for
WAP to search an element in the array .
<Html>
<Head>
<Title> Searching an array elements</Title>
</Head>
<Body><script language=”java script”>
var days =[“Sun”,”Mon”,”Tue”,”Wed”,”Thur”,”Fri”,”Sat”]
var success =false
var n=length.days
var searching =prompt [“Enter Searching elements”];
for (var i=0; i<n; i++ ; )
{
if (days[ I ]==searching)
{
Success=true ;
break;
}
}
if (success==true)
document.write(“element found”);
else
document.write(“element not found”);
</script>
</body>
</html>
Removing an element from an array:-
 Removing element from an array is quite state forward.
 Java script doesnot provide any built -in function to remove the element.
 To remove an element from yourself use the following procedure.

1.Read the element in the array.


2.If the element is not the one we want to delete , copy it into a temporary array.
3.If we want to delete the element then do nothing .
4.Implementing the loop counter .
5.Repeat the process.

R.Prashanth Kumar M.C.A 37


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

# Write a program demonstrate remove an element from array ?


<html>
<head><title> Remove an element form an array</title>
</head>
<body>
<script language=”javascript”>
var days=[“sun”,”mon”,”tue”,” wed”,”Thu”,”fri”,”sat”]
var len=days.length;
for (count1=0;count1<len;count1++)
{
document.write(days[count1]+” ,“);
}
document.write(“<br>”);
var rem=prompt(“Enter an item shalli remove”);
var tem=new array(days.length-1);
var count2=0;
for (count1=0;count1<len;count1++)
{
if(days[count1]==rem
{
}
else
{
Tem[count2]=days[count1];
Count2++;
}
}
days=temp;
document.write(“<br>”);
var len=days.length;
for(count1=0;count1<len;count1++)
{
document.write(day[count1]+ “,”
}
</script>
</body>
</html>
Array as object:-
 In java script an array can act like an object.
 We can perform various operations with use array functions with array objects.
 To call a function we must specify the name of the array which we want to operate on,
followed by dot(.) then the name of the function.
 Finally in parenthesis we must specify any parameters in a comma(,) separated list .
Syntax:-
arrayname.function(parameter 1,parameter 2,………,parameter n);
Array functions:-
1) concat():- This function is used a list of array is concatenate on to the end of the array and a
new array returned.
Syntax:- Arrayname.concat(array 2,array 3,……array n);
Ex:- var first=new array(“sun”,”mon”,”tue” );
var second =new array(“mpcs”,”mstcs”,);

R.Prashanth Kumar M.C.A 38


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

var third = new array (10,20,30);


var result =first.concat(second,third);
The result array consist of sun,mon,tue,mpcs,mstcs,10,20.
2) join(separate):- The result is string element are separated using the optional string parameter
. If this is omitted the element will be separated using a comma. But if we want anything
more complex such as “comma” then we will have to specify its explicity.
Syntax:- arrayname .join (separate);
Ex:- var days=new array (“sun”,”mon”,”tue”);
days.join(“_”);
The result is sun-mon-tue.
3) reverse():- This function is used to reverse the list of array elements.
Syntax:- arrayname.reverse( );
Ex:- var days=new array(“sun”,”mon”,”tue”);
days.reverse( );
The result is tue mon,sun.
4) shift( ):- This function is used to remove the first element of the array and decrease
length of the array by ‘1’.
Syntax:- arrayname.shift( );
Ex:- var days=new array(“sun”,”mon”,”tue”);
days.shift ( );
The result is mon,tue
5) unshift:- This function is used to insert a list of elements onto the front of the arrays .The list
of the new elements can have just one item.
Syntax:- arrayname.unshift(element);
Ex:- var days=new array (“sun”,”mon”,”tue”);
days.unshift(“wed”);
Then the result is wed,sun,mon,tue.
6) pop( ):- This function is used to remove the last element of the array and decrease the length
of the array by one.Removing the element as LIFO based
Syntax:- arrayname.pop( )
var days=new array (“mon”,”tue”,”wed”);
days.pop( )
Then the result is mon,tue.
7) push( ):- This function is used to add a list of items onto the end of the array.The items are
Separated by using commas in the parameter list
Syntax:- arrayname.push(elements)
Ex:- var days =new array (“mon”,”tue”,”wed”);
days.push(“thu”,”fri”,”sat”)
Then the result is mon,tue,wed,thu,fri,sat.
8) Slice():- This function is used to divided an array into pieces.The slice function require two
parameters .The first one is starting index and second one is ending index .

Syntax:- arrayname.slice(starting index ,ending index)


Ex:- var days=new array(“mon”,”tue”,”wed”,”thu”,”fri”,”sat”);
days.slice (2,6)
Then the Result is tue,wed,thu,fri,sat.

JavaScript | Math.random() function:-


The Math.random() function is used to return a floating-point pseudo-random number
between range [0,1) , 0 (inclusive) and 1 (exclusive).This random number can then be scaled
according to the desired range.

R.Prashanth Kumar M.C.A 39


Downloaded from: www.sucomputersforum.com Web Technologies B.Sc(Sem-VI)

Syntax:-
Math.random();
ReturnValue:- The math.random() function returns a floating-point, pseudo-random number
between range [0,1) , 0 (inclusive) and 1 (exclusive).
Below are some examples of using Math.random() in JavaScript to generate random numbers in
different ranges:
1. Getting a random number between 0 (inclusive) and 1 (exclusive):-
For getting a random number between 0(inclusive) and 1(exclusive),the following code can
be executed:
<script type="text/javascript">
var random = Math.random( );
document.write("Random Number Generated : " + random );
</script>
Output:-
Random Number Generated : 0.1688193265389777

2. Getting a random number between two values:-


Math.random() can be used to get a random number between two values. The
returned value is no lower than min and may possibly be equal to min, and it is also less than
and not equal to max.
For getting a random number between two values the math.random() function can be
executed in the following way:
<script type="text/javascript">
var min=4;
var max=5;
var random = Math.random() * (+max - +min) + +min;
document.write("Random Number Generated : " + random );
</script>
Output:-
Random Number Generated : 4.188653691028517

3. Getting a random integer between two values:-


Math.random() can be used to get an integer between two values. The returned
value is no lower than min or it is the next integer greater than min if min isn’t an integer. It
is also less than but not equal to max.
For getting a random integer between two values the Math.random() function can be executed in the
following way:
<script type="text/javascript">
var min=4;
var max=5;
var random =Math.floor(Math.random() * (+max - +min)) + +min;
document.write("Random Number Generated : " + random );
</script>

Output:-

Random Number Generated : 4

R.Prashanth Kumar M.C.A 40

You might also like