[Go to site: main page, start]

0% found this document useful (0 votes)
2 views74 pages

Introduction To JavaScript-1

JavaScript, created by Brendan Eich in 1996, is an object-based, interpreted scripting language primarily used for web development. It allows for dynamic content and interactivity on web pages, can be embedded directly in HTML, and supports various programming features like event-based programming and variable manipulation. The document also covers JavaScript syntax, including how to insert code, declare variables, use literals, operators, and implement conditional statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views74 pages

Introduction To JavaScript-1

JavaScript, created by Brendan Eich in 1996, is an object-based, interpreted scripting language primarily used for web development. It allows for dynamic content and interactivity on web pages, can be embedded directly in HTML, and supports various programming features like event-based programming and variable manipulation. The document also covers JavaScript syntax, including how to insert code, declare variables, use literals, operators, and implement conditional statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript

History of JavaScript

The first scripting language was first introduced by Brendan Eich, a


member of the Netscape2 group, in early 1996 to provide dynamically and
interactivity to web pages. This first version capable of being embedded in web pages
could only process numbers and modify HTML forms contents. During the
development phase it was known as Mocha, then as Livewire and even later
LiveScript. The name LiveScript was chosen because the browser itself could interprets
on the fly without requiring the code to be compiled. When it was released it was named
as JavaScript.

Features of JavaScript

1. JavaScript is an Object based language that is confined to run within the web
browsers only.
2. JavaScript is an interpreted language and requires no compilation steps.
3. JavaScript can directly be embedded in HTML files. The Html files with
embedded JavaScript commands interpreted by browser that is JavaScript enabled.
4. JavaScript is loosely typed language i.e. one data type can be automatically
converted into other types without explicit conversion.
5. JavaScript is platform independent but browser dependent. The JavaScript
applications work on any machine that has an appropriate JavaScript enabled
browser installed.
6. A scripting language is a lightweight programming language
7. JavaScript supports event-base programming.
8. Performance is good since the JavaScript programs are included in the same file
as the HTML code for a web page, the download time for the client minimum.

Inserting javaScript Code

JavaScript code is executed from within HTML Documents. So your WebPages will
not only contain HTML tags, but also the JavaScript statements (called scripts).
There are two ways to insert JavaScript Code into an HTML file.

1. One way to insert JavaScript Code is to embed it directly within the <script> and
</script> tag pair. The <script> tag notifies the browser that everything contained
within is script and is to be interpreted by a suitable interpreter.

[Link] RAO Assistant Professor(SVIT) Page 1


Department of CSE(IOT)
<script language=”javascript”>

JavaScript code

</script>

The optional attribute language specifies the programming language used for
scripting. there are many languages available in the market for scripting. common
languages are javascript and VBscript.. this attribute basically instructs the browser
which interpreter to use for interpretation. If nothing is specified JavaScript is
assumed by the browser

2. Another way to insert JavaScript Code is to place it in the external source file
and refer to it from an HTML file. This external source file generally has extension
.js. a source file contains only JavaScript Statements without any script tag or
other HTML tags. The tag <script> has the attribute src, which may be used to
refer top the external JavaScript Source file.

<script language=”javascript” src=[Link]>

When using a javaScript file, the browser ignores any javaScript Statements within
the <script> and </script> tags. So do not write anything between the opening and
closing <script> tag.

If the JavaScript Code is fairly lang. it is easy to use the source file. It has many
distinct advantages.

1. This makes the HTML file neater and cleaner. Too much javaScript Code
makes it large and unreadable.
2. The same JavaScript Source file can be reused in many HTML files.
3. The JavaScript code remains hidden if the browser is not compatible with it.
Incompatible embedded JavaScript code is displayed as if it is normal text.

Placement of javaScript

JavaScript code may be placed anywhere in an HTML [Link] is interpreted in the


order in which it [Link] tags are also rendered according to their documents
order. A function must be declared before it is called. This is true for variables as

[Link] RAO Assistant Professor(SVIT) Page 2


Department of CSE(IOT)
well. This suggests us to write JavaScript functions and declare global variables
within the head section, which is rendered before the body section.

/* sample program*/

<html>
<head>
<script language="javascript">
[Link]("welcome to java script");
</script>
</head>
<body>
</body>
</html>

Adding comments

Adding comments to programs is considered to be a good practice. Comments are


used for documentation. They help reader to understand the meaning of the code.
Comments, when encountered by the interpreter, are not treated as programming
statements and are ignored altogether. Like any other programming language,
javascript also allows comments. Comments are of two types.

1. Line comments
Line comments starts with //. The entire line is treated as comment line and is
skipped.
Eg: // this is a line comment and it will be ignored
2. Block comments
A block comment stats with /* and ends with */. Everything within theses
opening and closing character sequence is ignored.
Eg:
/*
This is a block comment
This will also be ignored
*/

Javascript keywords

[Link] RAO Assistant Professor(SVIT) Page 3


Department of CSE(IOT)
Variables in javaScript

Programming means manipulation of data. Data are stored in variables. JavaScript


like other programming languages. Allows us to create and manipulate variables.
However JavaScript variables are different from other variables in the sense that
they are un-types. This means that no type keyword is used during a variable
declaration. However, this does not mean that variables do not have any type. The
type of the variables, at any instant is determined by its content. It may change
from time to time as the content changes.

Naming conventions in declaring variable

[Link] name of variable cannot be a keyword.


[Link] must start with letter or an underscore(“_”) followed by zero or more letters,
underscore or digits.
[Link] can never contain white spaces, or any punctuation character such as comma(,),
full stop (.) etc.
[Link] unlike HTML is case sensitive.
[Link] versions of browsers also allow variables names to start with the “$” sign
[Link] there is no limit on number of characters in a variable.

[Link] RAO Assistant Professor(SVIT) Page 4


Department of CSE(IOT)
Global variables & Local variables in JavaScript

A variable declared without the keyword var is always a global variable and the
variables which precede with var keyword are called local variables. This allows us
to create a global variable from within a function.

Eg:

function f(a) // a is local variable


{
x=a; // x is global variable
}
f(3);
[Link](“x=”+x); //x is defined and has value 3;

introduction to JavaScript Literals

JavaScript Literals are constant values that can be assigned to the variables that are
called literals or constants. JavaScript Literals are syntactic representations for different
types of data like numeric, string, Boolean, array, etc data. Literals in JavaScript provide
a means of representing particular or some specific values in our program. Consider an
example, var name = “john”, a string variable named name is declared and assigned a
string value “john”. The literal “john” represents, the value john for the variable name.
There are different types of literals that are supported by JavaScript.

What are the Types of JavaScript Literals?


Javascript literals hold different types of values. Examples of JavaScript Literals are
given below:

1. Integer Literals
Integer literals are numbers, must have minimum one digit (0-9). No blank or comma is
allowed within an integer. It can store positive numbers or negative numbers. In integers,
literals in JavaScript can be supported in three different bases.

1. The base 10 that is Decimal (Decimal numbers contain digits (0,9) ) examples for
Decimal numbers are 234, -56, 10060.
2. Second is base 8 that is Octal (Octal numbers contains digits (0,7) and leading 0
indicates the number is octal), 0X 073, -089, 02003.

[Link] RAO Assistant Professor(SVIT) Page 5


Department of CSE(IOT)
3. Third is base 16 that is Hexadecimal numbers (Hexadecimal numbers contains
(0,9) digits and (A,F) or (a, f) letters and leading 0x or 0X indicates the number is
hexadecimal), examples for hexadecimal numbers are 0X8b, – 0X89, 0X2003.

2. Floating Number Literals


Floating numbers are decimal numbers or fraction numbers or even can have an
exponent part as well. Examples for hexadecimal numbers are 78.90, -234.90, 78.6e4
etc.

3. String Literals

A string literals are a sequence of zero or more characters. A string literals are either
enclosed in the single quotation or double quotation as ( ‘ ) and ( “ ) respectively and to
concatenate two or more string we can use + operator. Examples for string are “hello”,
“hello world”, “123”, “hello” + “world” etc.

List of special characters that can be used in JavaScript string are.

 \b: Backspace.
 \n: New Line
 \t: Tab
 \f: Form Feed
 \r: Carriage Return
 \\: Backslash Character (\)
 \’ : Single Quote
 \”: Double Quote

4. Array Literals
Array literals are a list of expressions or other constant values, each of which expression
known as an array element. An array literal contains a list of element s within square
brackets ‘ [ ] ‘ . If no value is a pass when it creates an empty array with zero length. If
elements are passed then its length is set to the number of elements passed. Examples for
string are var color = [ ], var fruits = [“Apple”, “Orange”, “Mango”, “Banana”] (an array
of four elements).

5. Boolean Literals
Boolean literals in JavaScript have only two literal values that are true and false.

[Link] RAO Assistant Professor(SVIT) Page 6


Department of CSE(IOT)
6. Object Literals
Object literals are collection zero or more key-value pairs of a comma-separated list,
which are enclosed by a pair of curly braces ‘ { } ‘.Examples for object literal with
declaration are

var userObject = { }
var student = { f-name : “John”, l-name : “D”, “rno” : 23, “marks” : 60}

Javascript operators

JavaScript supports most of the traditional operators, which are grouped depending on
their functionality as follows

1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Conditional Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=y++ x=6
-- Decrement x=y-- x=4

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.
[Link] RAO Assistant Professor(SVIT) Page 7
Department of CSE(IOT)
Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings


The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What a verynice
day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3 contains:
"What a very nice day"
Adding Strings and Numbers
Look at these examples:
x=5+5;
[Link](x);

[Link] RAO Assistant Professor(SVIT) Page 8


Department of CSE(IOT)
x="5"+"5";
[Link](x);

x=5+"5";
[Link](x);

x="5"+5;
[Link](x);

Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.
Given that x=5, the table below explains the comparison operators:
Operator Description Example
== is equal to x==8 is false
x==5 is true
=== is exactly equal to (value and type)
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used


Comparison operators can be used in conditional statements to compare values and take
action depending on the result:
if (age<18) [Link]("Too young");

Logical Operators
Logical operators are used in determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:

[Link] RAO Assistant Professor(SVIT) Page 9


Department of CSE(IOT)
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
If the variable visitor has the value of "PRES", then the variable greeting will be
assigned the value "Dear President " else it will be assigned "Dear".
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
 if statement - use this statement if you want to execute some code only if a
specified condition is true
 if...else statement - use this statement if you want to execute some code if the
condition is true and another code if the condition is false
 if...else if....else statement - use this statement if you want to select one of many
blocks of code to be executed
 switch statement - use this statement if you want to select one of many blocks of
code to be executed

If Statement
You should use the if statement if you want to execute some code only if a specified
condition is true.
Syntax
if (condition)

[Link] RAO Assistant Professor(SVIT) Page 10


Department of CSE(IOT)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!
Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=[Link]();

if (time<10)
{
[Link]("<b>Good morning</b>");
}
</script>
Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=[Link]();

if (time==11)
{
[Link]("<b>Lunch-time!</b>");
}
</script>
Note: When comparing variables you must always use two equals signs next to each
other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code
only if the specified condition is true.

If...else Statement
If you want to execute some code if a condition is true and another code if the condition
is not true, use the if....else statement.
Syntax
if (condition)
[Link] RAO Assistant Professor(SVIT) Page 11
Department of CSE(IOT)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = [Link]();

if (time < 10)


{
[Link]("Good morning!");
}
else
{
[Link]("Good day!");
}
</script>

If...else if...else Statement


You should use the if....else if...else statement if you want to select one of many sets of
lines to execute.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{

[Link] RAO Assistant Professor(SVIT) Page 12


Department of CSE(IOT)
code to be executed if condition1 and
condition2 are not true
}
Example
<script type="text/javascript">
var d = new Date()
var time = [Link]()
if (time<10)
{
[Link]("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
[Link]("<b>Good day</b>");
}
else
{
[Link]("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement


You should use the switch statement if you want to select one of many blocks of code to
be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each

[Link] RAO Assistant Professor(SVIT) Page 13


Department of CSE(IOT)
case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=[Link]();
switch (theDay)
{
case 5:
[Link]("Finally Friday");
break;
case 6:
[Link]("Super Saturday");
break;
case 0:
[Link]("Sleepy Sunday");
break;
default:
[Link]("I'm looking forward to this
weekend!");
}
</script>

Control statements
The while loop
The while loop is used when you want the loop to execute and continue executing while
the specified condition is true.
while (condition)
{
code to be executed
}
Note: The <= could be any comparing statement.
Example
Explanation: The example below defines a loop that starts with i=0. The loop will
continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the
[Link] RAO Assistant Professor(SVIT) Page 14
Department of CSE(IOT)
loop runs.
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
The do...while Loop
The do...while loop is a variant of the while loop. This loop will always execute a block
of code ONCE, and then it will repeat the loop as long as the specified condition is true.
This loop will always be executed at least once, even if the condition is false, because
the code is executed before the condition is tested.

do
{
code to be executed
}
while (condition);

[Link] RAO Assistant Professor(SVIT) Page 15


Department of CSE(IOT)
Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>
Result
The number is 0

The FOR loop

A for loop will execute a code block for a number of times. Compared to other loops,
FOR is shorter and easy to debug as it contains initialization, condition and update exp..

Syntax:

for (initialize; condition; update)


{
//code block to be executed
}

With initialize, it starts the loop, here a declared variable is used. Then the exit condition
for the loop is checked in condition part. When this condition returns true, the code
block inside is executed. When, in case, if the condition returns false or fails, it goes to
increment/decrement part and the variable is assigned an updated value. Values are
updated until the condition is satisfied.
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.

[Link] RAO Assistant Professor(SVIT) Page 16


Department of CSE(IOT)
Syntax
for (variable in object)
{
code to be executed
}
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 mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
[Link](mycars[x] + "<br />");
}
</script>
</body>
</html>

JavaScript Functions

Function:-A function is a segment of code that performs, when called, a particular


“function”. In general a function takes zero or more inputs (called parameters) from
users, performs a particular task depending on the value of the parameters and
optionally returns a value to the caller. Parameters allows us to perform different
operations at different times using the same function.

A JavaScript function can be defined using function keyword.

Syntax

://defining a function

function <function-name>(parameters)

[Link] RAO Assistant Professor(SVIT) Page 17


Department of CSE(IOT)
{
// code to be executed
}

Parameter passing

JavaScript allows the passing of parameters to a function by value only. If a parameter


is passed to a function and the value of the parameter is changed within the function,
this change is not reflected outside the function.

The following example illustrates this

function halveIt(a)
{
a=a/2; //a=2;
}
var x=4;
halveIt(x);
[Link](“x=”+x); //x=4;

Program to print factorial of each number upto given number ‘n’( n=6).

<html>
<head>
<script language="javascript">
function fact(n)
{
prod=1;
for(var i=2;i<=n;i++)
prod*=i;
return prod;
}
for(var i=1;i<=6;i++)
[Link](i+"!="+fact(i)+",");
</script>
</head>
</html>

[Link] RAO Assistant Professor(SVIT) Page 18


Department of CSE(IOT)
Recursive function to calculate Fibbonacci numbers

<html>
<head>
<script language ="javascript">
function fib(n)
{
if (n==0 ||n==1) return 1;
else
{
var a=fib(n-1);
var b=fib(n-2);
return a+b;
}
}
[Link](fib(5));
</script>
</head>
</html>

Arrays in JavaScript

JavaScript arrays are different from arrays in other languages. Traditionally, an array is
considered to be a collection of homogeneous items. It means an array cannot contain
dissimilar items. JavaScript’s approach to arrays is a bit different. There isn’t a data type
called array in JavaScript. Instead, arrays are objects in JavaScript. A JavaScript Object
can hold different data types (string, integer, boolean) at once:

Arrays can be created in two different ways


1. Array Literal
2. Using constructor
Array Literal

An array variable may be created by assigning an array literal to it. An array literal is
written using square brackets with array elements separated by comma(,) as follows

var array=[element0 , element0, ….. elementn];


Here are some examples

[Link] RAO Assistant Professor(SVIT) Page 19


Department of CSE(IOT)
var odds=[1,3,5,7];
var vowels=[‘a’,’e’,’I’,’o’u’];
var bools=[true,f alse];
Elements are accessed using the array name and index( ordinal number) of the
element written within square brackets. for example odds[3,vowels[2] etc. the array
index starts with 0. So, odd[o] is 1, vowels[0] is ‘a’;

1. A JavaScript array literal contain undefined elements


var colors=[“red”, , ,”green”,”blue”];
This array has five elements, color[0] through color[4]. However ,the value of
color[1] and color[2] have not specified so far and hence are undefined. The
length of this array is 5(five).

2. The traditional for loop can used to iterate through an array. JavaScript arrays
are objects and provide several useful properties and methods to work with
it. The property length specifies the size of array of the array.
var odds=[1,3,5,7];
var sum=0;
for(i=0;I,[Link];i++)
[Link](sum);
as mentioned a JavaScript array may contain heterogeneous elements. One can
declare an array that contains various information about an employee such as name,
age, marital status and salary. The declaration of such an array will look like this

var employee[“john”,24,false,18000];

3. JavaScript arrays are dynamic in nature. It means that elements can be added
and deleted and when required. For efficient memory usage, an array should
contain those elements that are actually required. Determining array size in
advance during the creation of the array is also a major problem. JavaScript
dynamic arrays eliminate all theses problems.
var primes=[2,3,5,7]; //length 4
primes[4]=11; //length 5 adds an element at the end.
This code segment first creates an array of length4. It then adds an element to the
end of the array which changes array size to [Link] following statement also adds
an element at the end.

[Link] RAO Assistant Professor(SVIT) Page 20


Department of CSE(IOT)
Primes[primes. length]=13 ;// length 6 adds an element at the end.

Creating array using constructor

In JavaScript an array is an object. JavaScript provides constructors to create arrays.


There three versions of array constructors.
1. Array();
2. Array(number of elements);
3. Array(comma separated list of elements);

1. The first constructor does not take any argument and creates an empty array(i.e.
an array of length zero) elements may be added later as and when needed.
var colors=new Array(); // array of length zero
This code segment creates an array of length zero. Now consider the following
statement
colors[2]=”blue”; //length3

This statement not creates elements colors[2] but also the elements colors[0] and
colors[1]. The length of the array colors then becomes 3. Here the values of
colors[0] and colors[1] are yet undefined. However their values may be assigned
later.

2. Programmer may also specify the initial length of the array during creation as
follows
Colors=new Array(2);
This creates the array colors of initial length [Link] so far no values have been
assigned to the elements colors[0] and colors[1]. So these elements are yet
undefined. Elements may be assigned later as required.
Elements can be added dynamically on demand
Colors[3]=”violet”; //length 4

3. Programmers may also explicitly specify the elements of an array during its
creation. The length of the array will be the number of lelments specified.
var cars=new array[“Maruti”,”Tata”,”Ford”];

[Link] RAO Assistant Professor(SVIT) Page 21


Department of CSE(IOT)
An array created in this fashion is called a dense array, as each element in this
array is defined and has a value.
Associative arrays:-
Associative arrays are basically objects in JavaScript where indexes are replaced by user
defined keys. They do not have a length property like normal array and cannot be
traversed using normal for loop.

An associative array is declared or dynamically created

We can create it by assigning a literal to a variable.

var arr = { "one": 1, "two": 2, "three": 3 };

Unlike simple arrays, we use curly braces instead of square brackets.

the content is accessed by keys, whatever the method used to declare the array.

var y = arr["one"];

1. Methods of Array Object

[Link] RAO Assistant Professor(SVIT) Page 22


Department of CSE(IOT)
1) Concat() : joins two or more arrays, and returns a copy of the joined string.

demo program on Concat()


<html>
<head>
<script language="javascript">
arr=["abc","xyz","pqrs"];
arr1=[10,20,30];
arr2=[Link](arr1);
document .writeln(arr2);
</script>
</head>
<body>
</body>

2) indexOf()

The indexOf() method in JavaScript is a built-in function used to find the first
occurrence of a specified value within a string or an array. It returns the index
(position) of the first match, or -1 if the value is not found.
[Link] RAO Assistant Professor(SVIT) Page 23
Department of CSE(IOT)
/*Demo program on indexOf()*/

<html>
<head>
<script language="javascript">
fruits = ["Banana", "Orange", "Apple", "Mango"];
index = [Link]("Apple");
[Link]([Link]("Apple"));
</script>
</head>
<body>
</body>

3)join()
The join() method in JavaScript is an Array instance method used to create and
return a new string by concatenating all of the elements in an array.

[Link] RAO Assistant Professor(SVIT) Page 24


Department of CSE(IOT)
/* demo program on join*/

<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The join() Method</h2>
<p>join() returns an array as a string:</p>
<p id="demo"></p>
<script>
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = [Link]();
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

4) pop()
The pop() method in JavaScript is a built-in Array method used to remove the last
element from an array and return that removed element

[Link] RAO Assistant Professor(SVIT) Page 25


Department of CSE(IOT)
/* Demo program on pop()*/

<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The pop() Method</h2>

<p>pop() removes the last element of an array.</p>

<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
[Link]("demo").innerHTML = fruits;
</script>
</body>
</html>

5) reverse()
The reverse() method in JavaScript is a built-in Array method that reverses the
order of the elements in an array in place. This means it modifies the original array
directly, without creating a new one.

[Link] RAO Assistant Professor(SVIT) Page 26


Department of CSE(IOT)
/* demo program on reverse method */
<html>
<head><title>Demo on reverse method</title></head>
<body>
<script language="javascript">
var a=[1,7,3,5,9,4,2,6];
[Link]("Before Reverse");
for(i=0;i<[Link];i++)
[Link](a[i]);
[Link]();
[Link]("<br>After Reverse");
for(i=0;i<[Link];i++)
[Link](a[i]);
</script>
</body>
</html>

JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)
[Link] RAO Assistant Professor(SVIT) Page 27
Department of CSE(IOT)
1) By string literal

The string literal is created using double quotes. The syntax of creating string using
string literal is given below:

var stringname="string value";

Example program
<script>
var str="This is string literal";
[Link](str);
</script>

2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

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

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

<script>
var stringname=new String("hello javascript string");
[Link](stringname);
</script>

3. JavaScript String Methods

[Link] RAO Assistant Professor(SVIT) Page 28


Department of CSE(IOT)
Let's see the list of JavaScript string methods with examples.

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the


specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given


string.

lastIndexOf() It provides the position of a char value present in the given


string by searching a character from the last position.

search() It searches a specified regular expression in a given string and


returns its position if a match occurs.

match() It searches a specified regular expression in a given string and


returns that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substring() It is used to fetch the part of the given string on the basis of the
specified index.

slice() It is used to fetch the part of the given string. It allows us to


assign positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase( It converts the given string into lowercase letter on the basis of
) host?s current locale.

toString() It provides a string representing the particular object.

split() It splits a string into substring array, then returns that newly
created array.

trim() It trims the white space from the left and right side of the string.

1) JavaScript String charAt(index) Method

[Link] RAO Assistant Professor(SVIT) Page 29


Department of CSE(IOT)
The JavaScript String charAt() method returns the character at the given index.

Example
<script>
var str="javascript";
[Link]([Link](2));
</script>

2) JavaScript String concat(str) Method

The JavaScript String concat(str) method concatenates or joins two strings.

[Link] RAO Assistant Professor(SVIT) Page 30


Department of CSE(IOT)
Example
<script>
var s1="javascript ";
var s2="concat example";
var s3=[Link](s2);
[Link](s3);
</script>
3) JavaScript String indexOf(str) Method

The JavaScript String indexOf(str) method returns the index position of the given string.

[Link] RAO Assistant Professor(SVIT) Page 31


Department of CSE(IOT)
Example
<script>
var s1="javascript from javatpoint indexof";
var n=[Link]("from");
[Link](n);
</script>

4) JavaScript String lastIndexOf(str) Method

The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.

[Link] RAO Assistant Professor(SVIT) Page 32


Department of CSE(IOT)
Example

<script>
var s1="javascript from javatpoint indexof";
var n=[Link]("java");
[Link](n);
</script>

5) JavaScript String toLowerCase() Method

The JavaScript String toLowerCase() method returns the given string in lowercase
letters.

[Link] RAO Assistant Professor(SVIT) Page 33


Department of CSE(IOT)
<script>
var s1="JavaScript toLowerCase Example";
var s2=[Link]();
[Link](s2);
</script>
6) JavaScript String toUpperCase() Method

The JavaScript String toUpperCase() method returns the given string in uppercase letters.

<script>
var s1="JavaScript toUpperCase Example";

[Link] RAO Assistant Professor(SVIT) Page 34


Department of CSE(IOT)
var s2=[Link]();
[Link](s2);
</script>

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.

Syntax

[Link] RAO Assistant Professor(SVIT) Page 35


Department of CSE(IOT)
Example
<script>
var s1="abcdefgh";
var s2=[Link](2,5);
[Link](s2);
</script>

Output:

CdCde

8) JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing whitespaces from the
string.

Example

<script>
var s1=" javascript trim ";
var s2=[Link]();
[Link](s2);
</script>

Output:

javascript trim

[Link] RAO Assistant Professor(SVIT) Page 36


Department of CSE(IOT)
9) JavaScript String split() Method

Syntax

[Link](separator, limit)

Parameters

Paramete Description
r

separator Optional.
A string or regular expression to use for splitting.
If omitted, an array with the original string is returned.

limit Optional.
An integer that limits the number of splits.
Items after the limit are excluded.

Example
<script>
var str="This is JavaTpoint website";
[Link]([Link](" ")); //splits the given string.
</script>

4. JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

JavaScript Math Methods

[Link] RAO Assistant Professor(SVIT) Page 37


Department of CSE(IOT)
Let's see the list of JavaScript Math methods with description.

Methods Description

abs() It returns the absolute value of the given number.

It returns a smallest integer value, greater than or equal to the


ceil()
given number.

cos() It returns the cosine of the given number.

exp() It returns the exponential form of the given number.

It returns largest integer value, lower than or equal to the given


floor()
number.

max() It returns maximum value of the given numbers.

min() It returns minimum value of the given numbers.

pow() It returns value of base to the power of exponent.

It returns random number between 0 (inclusive) and 1


random()
(exclusive).

round() It returns closest integer value of the given number.

sign() It returns the sign of the given number

1) abs()
[Link] RAO Assistant Professor(SVIT) Page 38
Department of CSE(IOT)
The abs() method in JavaScript is a static method of the built-in Math object, used to
return the absolute value of a number.

Syntax

[Link](number)

Example

<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>
<p>[Link]() returns the absolute value of a number:</p>
<p id="demo"></p>
<script>
let a = [Link](7.25);
let b = [Link](-7.25);
let c = [Link](null);
let d = [Link]("Hello");
let e = [Link](2-3);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
</script>
</body>
</html>

Output

7.25
7.25
0
NaN
1

2) ceil()
[Link] RAO Assistant Professor(SVIT) Page 39
Department of CSE(IOT)
The [Link]() method in JavaScript is a static method of the built-in Math object. It is
used to round a number up to the nearest integer

Syntax

[Link](number)

Example

<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>
<p>[Link]() rounds a number UP to the nearest integer:</p>
<p id="demo"></p>
<script>
a = [Link](0.60);
b = [Link](0.40);
c = [Link](5);
d = [Link](5.1);
e = [Link](-5.1);
f = [Link](-5.9);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e + "<br>" + f;
</script>
</body>
</html>

EXample

[Link]() rounds a number UP to the nearest integer:

1
1
5
6
-5
-5

3) max()
[Link] RAO Assistant Professor(SVIT) Page 40
Department of CSE(IOT)
In JavaScript, the max() method refers to the static method [Link](). This method is
part of the built-in Math object and is used to determine the largest value among a set of
numbers.

Syntax

[Link](n1, n2,...), where n1,n2 …. Are numbers

Example

<html>
<body>

<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>

<p>Return the numbers with the highest value:</p>


<p id="demo"></p>

<script>
let a = [Link](5, 10);
let b = [Link](0, 150, 30, 20, 38);
let c = [Link](-5, 10);
let d = [Link](-5, -10);
let e = [Link](1.5, 2.5);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
</script>
</body>
</html>

4) min()

[Link] RAO Assistant Professor(SVIT) Page 41


Department of CSE(IOT)
The min() method in JavaScript refers to [Link](), which is a static method of the
built-in Math object. It is used to find the smallest number among a set of provided
arguments.

synatx
[Link](n1, n2,...)

<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>

<p>Return the numbers with the lowest value:</p>


<p id="demo"></p>
<script>
let a = [Link](5, 10);
let b = [Link](0, 150, 30, 20, 38);
let c = [Link](-5, 10);
let d = [Link](-5, -10);
let e = [Link](1.5, 2.5);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
</script>
</body>
</html>

output
The [Link]() Method
Return the numbers with the lowest value:
5
0
-5
-10
1.5

[Link] RAO Assistant Professor(SVIT) Page 42


Department of CSE(IOT)
Window object
The Window object is used to open a window in a browser to display the Web page.

The following figure shows the Window object in the hierarchy of Browsers objects.

JavaScript Window Object is an already available global object which represents the
currently opened window tab in the browser. It can be said that the window object is
nothing but the browser window which is opened in the browser. This Window object is
different from the normal object, a window is an object of browser. Every tab opened in
the browser will have its window object associated with it and it will be available in
every part of the application as it is global. It has multiple values and methods are
available with it and we can call these methods directly to perform multiple operations
over the browser window.

JavaScript Window Object Properties

All data and information about any browser is attached to the window object as
properties and the frames property in the window object returns all the frames in the
current window.

The table given below describes properties of the window object in JavaScript.

[Link] RAO Assistant Professor(SVIT) Page 43


Department of CSE(IOT)
Property Description

returns a boolean value that specifies whether a window has been


closed
closed or not
specifies the default message that has to be appeared in the
defaultStatus
statusbar of a window
document specifies a document object in the window
frames specifies an array of all the frames in the current window
history specifies a history object for the window
innerHeight specifies the inner height of a window's content area
innerWidth specifies the inner width of a window's content area
length specifies the number of frames contained in a window
location specifies a location object for the window
name specifies the name of a window
specifies the height of the outside boundary of a window in
outerHeight
pixels
outerWidth specifies the width of the outside boundary of a window in pixels
parent returns the parent frame or window of the current window
specifies the x coordinate of the window relative to a user's
screenLeft
monitor screen
specifies the y coordinate of the window relative to a user's
screenTop
monitor screen
specifies the x coordinate of the window relative to a user's
screenX
monitor screen
specifies the y coordinate of the window relative to a user's
screenY
monitor screen

self returns the reference of the current active frame or window

[Link] RAO Assistant Professor(SVIT) Page 44


Department of CSE(IOT)
specifies the message that is displayed in the status bar of a
status
window, when an activity is performed on the window
top specifies the reference of the topmost browser window

JavaScript Window Object Methods

The methods of the window object enable you to perform various tasks such as open a
url in a new window or to close a window. The following table describes the methods of
the Window object in JavaScript.

Method Description

alert() displays an alert box with a message and an OK button


blur() removes the focus from the current window
clearInterval() clears the timer, which is set by using the setInterval() method
clearTimeout() clears the timer, which is set by using the setTimeout() method
close() closes the current window
displays a dialog box with a message and two buttons, OK and
confirm()
Cancel
createPopup() creates a pop-up window
focus() sets focus on the current window
moveBy() moves a window relative to its current position
moveTo() moves a window to an specified position
open() opens a new browser window
print() sends a print command to print the content of the current window
prompt() prompts for input

[Link] RAO Assistant Professor(SVIT) Page 45


Department of CSE(IOT)
resizeBy() resizes a window with the specified pixels
resizeTo() resizes a window with the specified width and height
scrollBy() scrolls the content of a window by the specified number of pixels
scrollTo() scrolls the content of a window up to the specified coordinates
setInterval() evaluates an expression at specified time intervals in milliseconds
setTimeout() evaluates an expression after a specified number of milliseconds

Open a new window

To open a new window or tab, you use the [Link]() method:

[Link](url, windowName, [windowFeatures]);

The [Link]() method accepts three arguments: the URL to load, the window
target and a string of window features.

The third argument is a command-delimited string of settings specifying displaying


information for the new window such as width, height, menubar, and resizable.

JavaScript Date Object

The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.

Constructors
we can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

[Link] RAO Assistant Professor(SVIT) Page 46


Department of CSE(IOT)
JavaScript Date Methods

Methods Description

getDate() It returns the integer value between 1 and 31 that represents


the day for the specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.

getFullYears() It returns the integer value that represents the year on the basis
of local time.

getHours() It returns the integer value between 0 and 23 that represents


the hours on the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents
the milliseconds on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents


the minutes on the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents


the month on the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents


the seconds on the basis of local time.

setDate() It sets the day value for the specified date on the basis of local
time.

setDay() It sets the particular day of the week on the basis of local time.

setFullYears() It sets the year value for the specified date on the basis of local
time.

setHours() It sets the hour value for the specified date on the basis of
local time.

setMilliseconds() It sets the millisecond value for the specified date on the basis
of local time.

setMinutes() It sets the minute value for the specified date on the basis of

[Link] RAO Assistant Professor(SVIT) Page 47


Department of CSE(IOT)
local time.

setMonth() It sets the month value for the specified date on the basis of
local time.

setSeconds() It sets the second value for the specified date on the basis of
local time.

toString() It returns the date in the form of string.


/* Printing Date information using javascript*/

<html>
<head><title>Date object</title>
<script language=javascript>
var d=new Date();
[Link]("<html><body><h1>Date Object methods</h1>");
[Link]("<table border=1 cellspacing=0 cellpadding=0>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Today's date & Time");
[Link]("</td>");
[Link]("<td>");
[Link](d+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Date");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Day");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link] RAO Assistant Professor(SVIT) Page 48


Department of CSE(IOT)
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Month");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Year");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Time");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Hours");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Minutes");
[Link]("</td>");

[Link] RAO Assistant Professor(SVIT) Page 49


Department of CSE(IOT)
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("Only Seconds");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");

[Link]("<tr>");
[Link]("<td>");
[Link]("London Time");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("</html>");

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

[Link] RAO Assistant Professor(SVIT) Page 50


Department of CSE(IOT)
/* printing Digital clock*/
<html>
<head><title>Scrolling Text</title>
<script language=javascript>
var id=setInterval("abc()",1000);
function abc()
{
var d=new Date();
[Link]="Current time:"+[Link]()+":"+[Link]()+":"+[Link]();
}
</script>
</head>
<body>
<h1 align=center> Digital Clock</h1>
<hr size=2 color=red>
<p align=center id="k1"></p>

[Link] RAO Assistant Professor(SVIT) Page 51


Department of CSE(IOT)
</body>
</html>

javaScript prompt() dialog box

The prompt() method in JavaScript is used to display a prompt box that prompts the
user for the input. It is generally used to take the input from the user before entering the
page. It can be written without using the window prefix. When the prompt box pops up,
we have to click "OK" or "Cancel" to proceed.

The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the
default string, which displays in the textbox. The prompt box consists of two
buttons, OK and Cancel. It returns null or the string entered by the user. When the user
clicks "OK," the box returns the input value. Otherwise, it returns null on clicking
"Cancel".
[Link] RAO Assistant Professor(SVIT) Page 52
Department of CSE(IOT)
The prompt box takes the focus and forces the user to read the specified message. So, it
should avoid overusing this method because it stops the user from accessing the other
parts of the webpage until the box is closed.

Syntax
prompt(message, default)

javaScript confirm () dialog box

The confirm() method displays a dialog box with a specified message, along with an OK
and a Cancel button.

A confirm box is often used if you want the user to verify or accept something.

Note: The confirm box takes the focus away from the current window, and forces the
browser to read the message. Do not overuse this method, as it prevents the user from
accessing other parts of the page until the box is closed.

The confirm() method returns true if the user clicked "OK", and false otherwise.

Syntax
confirm(message)
javaScript Alert Box

An alert box is often used if you want to make sure information comes through to the
user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
[Link]("sometext");

The [Link]() method can be written without the window prefix.

Form Validation programs

[Link] RAO Assistant Professor(SVIT) Page 53


Department of CSE(IOT)
JavaScript Numbers Validation

You can use a JavaScript function named isNaN to validate a number object. Here is an
example shows how to validate numbers using JavaScript:

<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>JavaScript Number Validation</TITLE>
<SCRIPT type="text/javascript">
function validateNumber(this_form2)
{
var num2 = this_form2.[Link];
if(num2==null|| num2=="")
{
alert("Please enter a number.");
this_form2.[Link]();
return false;
}
if(isNaN(num2))
{
alert("It is not a valid number.");
this_form2.[Link]();
return false;
}
return true;
}
</SCRIPT>
</HEAD>
<BODY>

<FORM action="#" validateNumber(this)" method="Post">


Enter a Number: <INPUT type="text" name="num2"/><BR/>
<INPUT type="submit" value="Validate"/>
</FORM>

</BODY>
</HTML>

JavaScript Phone Number Validation

[Link] RAO Assistant Professor(SVIT) Page 54


Department of CSE(IOT)
You can also validate the Phone number entered by the user using JavaScript. To
validate phone number, you have to check the following three conditions:

user must enter a value


value must be an integer value
value must have at least of 10 digits

Here is an example shows how to validate phone number entered by the user using
JavaScript:

<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>JavaScript Phone Number Validation</TITLE>
<SCRIPT type="text/javascript">
function validatePhoneNumber(this_form4)
{
var phon=this_form4.[Link];
if(phon==null||phon=="")
{
alert("Please enter your phone number.");
this_form4.[Link]();
return false;
}
if(isNaN(phon))
{
alert("Sorry! You have entered an invalid phone number! Please try again.");
this_form4.[Link]();
return false;
}

if([Link]<10)
{
alert("Phone number must be at least of 10 digits.");
this_form4.[Link]();
return false;
}

return true;
}
</SCRIPT>
[Link] RAO Assistant Professor(SVIT) Page 55
Department of CSE(IOT)
</HEAD>
<BODY>

<FORM action="#" validatePhoneNumber(this)" method="Post">


Phone Number: <input type="text" name="phonnumbe"/><BR/>
<INPUT type="submit" value="Validate"/>
</FORM>

</BODY>
</HTML>

Login form validation

<HTML>
<HEAD>
<TITLE>JavaScript Username and Password Validation</TITLE>
<SCRIPT type="text/javascript">
function validateUsernamePassword(this_form3)
{
var userName = this_form3.user_name.value;
var pass1 = this_form3.[Link];
var pass2 = this_form3.[Link];
if(userName=="")
{
alert("Please enter your username.");
this_form3.user_name.focus();
return false;
}
if([Link]<6)
{
alert("Username must be at least of 6 characters.");
this_form3.user_name.focus();
return false;
}
if(pass1=="")
{
alert("Please enter your password.");
this_form3.[Link]();
return false;
}
if([Link]<8)

[Link] RAO Assistant Professor(SVIT) Page 56


Department of CSE(IOT)
{
alert("Password must contain at least of 8 digits");
this_form3.[Link]();
return false;
}
if(pass2=="")
{
alert("Please re-enter your password for confirmation.");
this_form3.[Link]();
return false;
}
if([Link]>=8 && [Link]>=8 )
{
if(pass1!=pass2)
{
alert("Sorry! Password mismatched! Please try again.");
return false;
}
}
return true;
}
</SCRIPT>
</HEAD>

<BODY>
<FORM action="#" validateUsernamePassword(this)"
method="Post">
Enter Username: <INPUT type="text" name="user_name"/><BR/>
Enter Password: <INPUT type="password" name="password1"/><BR/>
Re-enter Password: <INPUT type="password" name="password2"/><BR/>
<INPUT type="submit" value="Login"/>
</FORM>

</BODY>
</HTML>

Event Handling in HTML


Introduction
[Link] RAO Assistant Professor(SVIT) Page 57
Department of CSE(IOT)
Events are mechanism by which browsers respond to user actions. Every element on a
web page has certain event which can trigger invocation of event handlers.
Attributes are inserted into HTML tags to define events and event handlers.

For example :submitting an HTML form, moving mouse over a web page, clicking
the mouse button will generate an event informing the browser that an action has
occurred and that further relevant processing is required.

The browser waits for events to occur, and when they do, it performs whatever
processing is assigned to those events. The processing that is performed in response to
the occurrence of an event is known as event handling. The code that performs this
processing is called an event handler.

HTML event handlers can be divided into two types interactive and non–
interactive.

A interactive event handler depends on the user interaction with an HTML page.
For example onClick and onMouseOver event handlers are interactive event handlers.
This required the user to click a button object or move the mouse cursor over a web
page.

Non-interactive event handler does not need user interaction. For example “onLoad”
event handler is a non-interactive event handler as it is executed whenever a web
page is loaded in to the browser.

The handler eventHandler of the event evnt for some element ele is specified by
assigning it to the property of the element. The name of the property for the event evnt
takes the following form onEvnt.

For example, the name of the property for the evnt Click is onClick. Similarly
onMouseOver is the name of the property for the mouseOver.

There are many ways to add a handler to an event. The straightforward way is to
specify it in the tag as follows

[Link] RAO Assistant Professor(SVIT) Page 58


Department of CSE(IOT)
A list of common events along with their souce is given below

[Link] RAO Assistant Professor(SVIT) Page 59


Department of CSE(IOT)
[Link] RAO Assistant Professor(SVIT) Page 60
Department of CSE(IOT)
Program on onchange event
<html>
<head><title>Change event</title>
<script language=javascript>
function jsFunction(value)
{
if(value==1)
[Link]="red";
else if(value==2)
[Link]="green";
else
[Link]="yellow";

</script>
</head>
<body>
<h1> hai</h1>
<form name=f1>

<select ><option value=1>red</option>
<option value=2>green</option>
<option value=3>yellow</option>

</select>
</form>

</body>
</html>

Program to print coordinates of mouse

<html>
<head>
<title>mouse coordinates</title>
<script>
function callme()
{

[Link] RAO Assistant Professor(SVIT) Page 61


Department of CSE(IOT)
alert("You have Clicked at ("+[Link]+","+[Link]+")");
}
</script>
</head>
<body ></body>
</html>

Program on onChange event

<html>
<head><title>Change event</title>
<script language=javascript>

function callme()
{
var str=[Link];
[Link]=[Link]();
}
</script>
</head>
<body>
<form name=f1>
<table>
<tr>
<td> Enter ant Text</td>
<td><input type=text name=t1 ></tr>
<tr>
<td> converted Text is</td>
<td><input type=text name=t2></td>
</tr>
</table>
</form>
</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 62


Department of CSE(IOT)
Program on Onsubmit event

<html>
<head><title>validation</title>
<script language=javascript>
function validate()
{
if([Link]==0)
{
alert("Username can never be blank");
return false;
}
if([Link]==0)
{
alert("Password can never be blank");
return false;
}

return true;
}
</script>
</head>
<body>
<form name=f1 validate()">
<table>
<tr>
<td>Username</td>
<td><input type=text name=t1></td>
</tr>
<tr>
<td>password</td>
<td><input type=password name=t2></td>
</tr>
<tr>
<th colspan=2>
<input type=submit value=submit></th>
</tr>
</table>
</form>
</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 63


Department of CSE(IOT)
Program on key event

<html>
<head>
<title>Key Event</title>
<script>
function callme()
{
var str="key pressed: "+ [Link]([Link]);
str=str+ " ,key code :"+[Link];
alert(str);
}
</script>
</head>
<body ></body>
</html>

Program on mouse event

<html>
<head>
<title>Anchor</title>
<script language="javascript">
function callme(k,b,c)
{
[Link]=b;
[Link]=c;
}
</script>
</head>
<body>
<a href="[Link]" >>

</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 64


Department of CSE(IOT)
Built-in Functions
Java script provides few pre-defined functions which do not stick to a
particular object type but are global. Object in JavaScript are different from
global object. Using the new operator you cannot create global objects. It
comes into existence when the scripting engine is initialized. After it is
initialized the functions and constants are available for use. The global object
is also represented using the window keyword. The window object denotes the
global object. It contains several useful methods & properties.

1. isNaN()

in JavaScript, isNaN() is a built-in global function used to determine whether


a value is NaN (Not-a-Number). It returns true if the value
is NaN and false otherwise.
How isNaN() Works:
The isNaN() function attempts to convert the argument to a number before
performing the check.
 If the argument cannot be successfully converted into a valid
number, isNaN() returns true.
 If the argument can be converted into a valid number (even if
it's 0, Infinity, or -Infinity), isNaN() returns false.

Syntax
isNaN(value);

[Link] RAO Assistant Professor(SVIT) Page 65


Department of CSE(IOT)
Example 1:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Global Methods</h1>
<h2>The isNaN() Method</h2>
<p>isNaN() returns true if a value is NaN:</p>
<p id="demo"></p>
<script>
result =
"Is 123 NaN? " + isNaN(123) + "<br>" +
"Is -1.23 NaN? " + isNaN(-1.23) + "<br>" +
"Is 5-2 NaN? " + isNaN(5-2) + "<br>" +
"Is 0 NaN? " + isNaN(0);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 66


Department of CSE(IOT)
2. parseInt()

The parseInt() function in JavaScript is a global function used to parse a


string argument and return an integer.

Syntax:
parseInt(string, radix);

Parameters:
 string: The value to parse. If it's not a string, it will be converted to one.
 radix (optional): An integer between 2 and 36 representing the base of
the numeral system to be used. If omitted, it defaults to 10
(decimal). Common radix values include 2 (binary), 8 (octal), 10
(decimal), and 16 (hexadecimal).

Example 1:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Global Methods</h1>


<h2>The parseInt() Method</h2>
<p>parseInt() parses a string and returns the first integer:</p>

<p id="demo"></p>

<script>
[Link]("demo").innerHTML =
parseInt("10") + "<br>" +
parseInt("10.00") + "<br>" +
parseInt("10.33") + "<br>" +
parseInt("34 45 66") + "<br>" +
[Link] RAO Assistant Professor(SVIT) Page 67
Department of CSE(IOT)
parseInt(" 60 ") + "<br>" +
parseInt("40 years") + "<br>" +
parseInt("He was 40");
</script>
</body>
</html>

Example 2:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Global Methods</h1>


<h2>The parseInt() Method</h2>
<p>parseInt() parses a string and returns the first integer:</p>

<p id="demo"></p>

<script>
[Link]("demo").innerHTML =
parseInt("10", 10)+ "<br>" +
parseInt("010")+ "<br>" +
parseInt("10", 8)+ "<br>" +
[Link] RAO Assistant Professor(SVIT) Page 68
Department of CSE(IOT)
parseInt("0x10")+ "<br>" +
parseInt("10", 16);
</script>
</body>
</html>

2. eval()

eval() is a function property of the global object.


The argument of the eval() function is a string. If the string represents an
expression, eval() evaluates the expression. If the argument represents one or
more JavaScript statements, eval() evaluates the statements.

Example 1

// Using the eval function


var ans = eval("4+4");
[Link](ans);

[Link] RAO Assistant Professor(SVIT) Page 69


Department of CSE(IOT)
Example 2:
// Defining a function
function add(x, y) {
return (x + y);
}

// Using the eval() function


ans = eval("add(7, 4)");

// Displaying the result


[Link](ans);

Example 3

var marks = 93;


var state;

// If else condition inside the string


state = "if(marks >= 80 && marks <= 100) {'You got A grade';} else {'You
got B grade';}"

// Output
document. writeln(eval(state));

Disadvantages of using Eval

1. The eval function can execute any type of code, including malicious
code that can compromise the security of your system. For example,
attackers may steal sensitive data.
2. The eval function can be slow for large amounts of code.

[Link] RAO Assistant Professor(SVIT) Page 70


Department of CSE(IOT)
3. isFinite()
In JavaScript, isFinite() is a global function used to determine whether a
given value is a finite number. It accepts a single argument, value,
returns true if the passed argument is a finite number, and returns false if the
passed argument is either positive Infinity, negative Infinity, or NaN.

Example 1:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Global Methods</h1>
<h2>The isFinite() Method</h2>
<p>isFinite() returns false if a value is Infinity, -Infinity, or NaN, otherwise
true:</p>
<p id="demo"></p>
<script>
result =
isFinite(-1.23) + "<br>" +
isFinite(5-2) + "<br>" +
isFinite(0) + "<br>";
[Link]("demo").innerHTML = result;
</script>
</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 71


Department of CSE(IOT)
Example 2

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Global Methods</h1>
<h2>The isFinite() Method</h2>
<p>isFinite() returns false if a value is Infinity, -Infinity, or NaN, otherwise
true:</p>
<p id="demo"></p>
<script>
let result =
isFinite("Hello") + "<br>" +
isFinite("2005/12/12");
[Link]("demo").innerHTML = result;
</script>
</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 72


Department of CSE(IOT)
4. encodeURI()

The encodeURI() function in JavaScript is used to encode a Uniform


Resource Identifier (URI) by replacing certain characters with their UTF-8
escape sequences. This function is designed to encode an entire URI,
ensuring that it remains a valid URI structure.
 Encodes special characters:
It converts characters that are not permitted in URIs (like spaces) into their
corresponding percent-encoded format (e.g., a space becomes %20).
 Preserves URI structure:
It does not encode characters that are considered part of a URI's syntax, such
as :, /, ?, &, =, #. These characters are essential for defining the structure of a
URI (e.g., protocol, domain, path, query parameters, fragments) and are
intentionally left unencoded.

Syntax
encodeURI(uri)
Example 1:
!DOCTYPE html>

[Link] RAO Assistant Professor(SVIT) Page 73


Department of CSE(IOT)
<html>
<body>

<h1>JavaScript Global Methods</h1>


<h2>The decodeURI() Method</h2>

<p id="demo"></p>

<script>
uri = "my [Link]?name=ståle&car=saab";
lencoded = encodeURI(uri);
decoded = decodeURI(encoded);

[Link]("demo").innerHTML = "Encoded URI:<br>" +


encoded + "<br><br>" + "Decoded URI:<br>" + decoded;
</script>
</body>
</html>

[Link] RAO Assistant Professor(SVIT) Page 74


Department of CSE(IOT)

You might also like