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

Javascript

The document provides an overview of JavaScript including: - What JavaScript is and its introduction in 1995 for adding programs to webpages - JavaScript allows for dynamic interactivity on webpages without reloading - JavaScript has no connection to Java but borrowed its name when Java was popular - JavaScript can be used for client-side validation, dynamic drop-down menus, displaying clocks and more - JavaScript code can be placed in <script> tags within <head> or <body> tags or in external .js files - Variables, comments, and functions are explained as basic JavaScript concepts

Uploaded by

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

Javascript

The document provides an overview of JavaScript including: - What JavaScript is and its introduction in 1995 for adding programs to webpages - JavaScript allows for dynamic interactivity on webpages without reloading - JavaScript has no connection to Java but borrowed its name when Java was popular - JavaScript can be used for client-side validation, dynamic drop-down menus, displaying clocks and more - JavaScript code can be placed in <script> tags within <head> or <body> tags or in external .js files - Variables, comments, and functions are explained as basic JavaScript concepts

Uploaded by

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

What is JavaScript

JavaScript (js) is a light-weight object-oriented programming language which is used


by several websites for scripting the webpages. It is an interpreted, full-fledged
programming language that enables dynamic interactivity on websites when applied
to an HTML document. It was introduced in the year 1995 for adding programs to the
webpages in the Netscape Navigator browser. Since then, it has been adopted by all
other graphical web browsers. With JavaScript, users can build modern web
applications to interact directly without reloading the page every time. The traditional
website uses js to provide several forms of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their
scripting and query language.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,

1
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.

<html>

<body>

<h2>Weline to JavaScript</h2>

<script>

document.write("Hello JavaScript by JavaScript");

</script>

</body>

</html>

JavaScript Example
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript
code: within body tag, within head tag and external JavaScript file.

Let’s create the first JavaScript example.

<html>

<body>

<script type="text/javascript">

document.write("JavaScript is a simple language for Digitinstitute learners");

</script>

</body>

</html>

The script tag specifies that we are using JavaScript.

2
The text/javascript is the content type that provides information to the browser
about the data.

The document.write() function is used to display dynamic content through


JavaScript. We will learn about document object in detail later.

3 Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag


In the above example, we have displayed the dynamic content using JavaScript. Let’s
see the simple example of JavaScript that displays alert dialog box.

<html>

<body>

<script type="text/javascript">

alert("Hello Digitinstitute");

</script>

</body>

</html>

2) JavaScript Example : code between the head tag


Let’s see the same example of displaying alert dialog box of JavaScript that is contained
inside the head tag.

In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call
msg() function

3
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Digitinstitute");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

External JavaScript file


We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html
pages.

An external JavaScript file must be saved by .js extension. It is reinmended to embed


all JavaScript files into a single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Digitinstitute in a alert dialog
box

message.js

1. function msg(){
2. alert("Hello Digitinstitute");
3. }

Let's include the JavaScript file into html page. It calls the JavaScript function on
button click.

index.html

4
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Weline to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Advantages of External JavaScript


There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
4. It enables both web designers and coders to work with html and js files parallelly
and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js
file.

JavaScript comment
1.

The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily
interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.

5
Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so


that end user can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be need to disable the code. In such case, it is better to
use inments.

Types of JavaScript comments


There are two types of inments in JavaScript.

1. Single-line comment
2. Multi-line comment

JavaScript Single line comment


It is represented by double forward slashes (//). It can be used before and after the
statement.

Let’s see the example of single-line comment i.e. added before the statement.

<html>

<body>

<script>

// It is single line comment

document.write("hello javascript");

</script>

</body>

</html>

Let’s see the example of single-line comment i.e. added after the statement.

6
<html>

<body>

<script>

var a=10;

var b=20;

var c=a+b;//It adds values of a and b variable

document.write(c);//prints sum of 10 and 20

</script>

</body>

</html>

JavaScript Multi line comment


It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash. For
example:

<html>

<body>

<script>

/* It is multi line comment.

It will not be displayed */

document.write("example of javascript multiline comment");

</script>

</body>

</html>

JavaScript Variable

A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

7
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables

1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables

1. var 123=30;
2. var *aa=320;

Example of JavaScript variable


Let’s see a simple example of JavaScript variable.

<html>

<body>

<script>

var x = 10;

var y = 20;

var z=x+y;

document.write(z);

</script>

</body>

</html>

8
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within
the function or block only. For example:

1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>

Or,

1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>

JavaScript 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:

<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function

9
b();
</script>

JavaScript Global Variable


A JavaScript global variable is declared outside the function or declared with window
object. It can be accessed from any function.

Let’s see the simple example of global variable in JavaScript.

<html>

<body>

<script>

var value=50;//global variable

function a(){

alert(value);

function b(){

alert(value);

a();

</script>

</body>

</html>

Declaring JavaScript global variable within


function
To declare JavaScript global variables inside function, you need to use window object.
For example:

1. window.value=90;

Now it can be declared inside any function and can be accessed from any function. For
exampl

10
<html>

<body>

<script>

function m(){

window.value=100;//declaring global variable by window object

function n(){

alert(window.value);//accessing global variable from other function

m();

n();

</script>

</body>

</html>

Internals of global variable in JavaScript


When you declare a variable outside the function, it is added in the window object
internally. You can access it through window object also. For example:

1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

11
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc.
For example:

1. var a=40;//holding number


2. var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

12
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

13
JavaScript comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

14
~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

15
/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true
or false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

16
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.

1. if(expression){
2. //content to be evaluated
3. }

<html>

<body>

<script>

var a=20;

if(a>10){

document.write("value of a is greater than 10");

</script>

</body>

</html>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }

17
<html>

<body>

<script>

var a=20;

if(a%2==0){

document.write("a is even number");

else{

document.write("a is odd number");

</script>

</body>

</html>

JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

18
<html>

<body>

<script>

var a=20;

if(a==10){

document.write("a is equal to 10");

else if(a==15){

document.write("a is equal to 15");

else if(a==20){

document.write("a is equal to 20");

else{

document.write("a is not equal to 10, 15 or 20");

</script>

</body>

</html>

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page. But
it is convenient than if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

switch(expression){
case value1:
code to be executed;
break;
case value2:
19
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}

<html>

<body>

<script>

var grade='B';

var result;

switch(grade){

case 'A':

result="A Grade";

break;

case 'B':

result="B Grade";

break;

case 'C':

result="C Grade";

break;

default:

result="No Grade";

document.write(result);

</script>

</body>

</html>

20
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code inpact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should
be used if number of iteration is known. The syntax of for loop is given below.

1. for (initialization; condition; increment)


2. {
3. code to be executed
4. }

<!DOCTYPE html>

<html>

<body>

<script>

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

document.write(i + "<br/>")

</script>

</body>

</html>

21
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.

1. while (condition)
2. {
3. code to be executed
4. }

<html>

<body>

<script>

var i=11;

while (i<=15)

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

i++;

</script>

</body>

</html>

3) JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given below.

1. do{
2. code to be executed
3. }while (condition);

22
<html>

<body>

<script>

var i=21;

do{

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

i++;

}while (i<=25);

</script>

</body>

</html>

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program inpact. We don’t need to write many lines of code
each time to perform a inmon task.

JavaScript Function Syntax


The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){


2. //code to be executed
3. }

23
JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.

<html>

<body>

<script>

function msg(){

alert("hello! this is message");

</script>

<input type="button" onclick="msg()" value="call function"/>

</body>

</html>

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function that has
one argument.

<html>

<body>

<script>

function getcube(number){

alert(number*number*number);

</script>

<form>

<input type="button" value="click" onclick="getcube(4)"/>

</form>

</body>

</html>

24
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.

<html>

<body>

<script>

function getInfo(){

return "hello Digitinstitute! How r u?";

</script>

<script>

document.write(getInfo());

</script>

</body>

</html>

JavaScript Function Methods


Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

25
JavaScript Function Object Examples
<html>

<body>

<script>

var add=new Function("num1","num2","return num1+num2");

document.writeln(add(2,5));

</script>

</body>

</html>

Example 2

<html>

<body>

<script>

var pow=new Function("num1","num2","return Math.pow(num1,num2)");

document.writeln(pow(2,3));

</script>

</body>

</html>

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

26
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2.....propertyN:valueN}

<html>

<body>

<script>

emp={id:102,name:"Shyam Kumar",salary:40000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

</body>

</html>

2) By creating instance of Object


The syntax of creating object directly is given below:

27
1. var objectname=new Object();

<html>

<body>

<script>

var emp=new Object();

emp.id=101;

emp.name="Ravi Malik";

emp.salary=50000;

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

</body>

</html>

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

e=new emp(103,"Vimal Jaiswal",30000);

28
document.write(e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>

Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to
add property in the function with same name as method.

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

this.changeSalary=changeSalary;

function changeSalary(otherSalary){

this.salary=otherSalary;

e=new emp(103,"Sonoo Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

e.changeSalary(45000);

document.write("<br>"+e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>

29
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

<html>

<body>

<script>

var emp=["Sonoo","Vimal","Ratan"];

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br/>");

</script>

</body>

</html>

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

1. var arrayname=new Array();

<html>

<body>

30
<script>

var i;

var emp = new Array();

emp[0] = "Arun";

emp[1] = "Varun";

emp[2] = "John";

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

</body>

</html>

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.

<html>

<body>

<script>

var emp=new Array("Jai","Vijay","Smith");

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

</body>

</html>

31
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)

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

1. var stringname="string value";

<html>

<body>

<script>

var str="This is string literal";

document.write(str);

</script>

</body>

</html>

2) By string object (using new keyword)


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

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

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

<!DOCTYPE html>

<html>

<body>

<script>

32
var stringname=new String("hello javascript string");

document.write(stringname);

</script>

</body>

</html>

JavaScript String Methods


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 inbination 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.

substr() It is used to fetch the part of the given string on the basis of the specified starting position
and length.

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

33
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.

toUpperCase() It converts the given string into uppercase letter.

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

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

valueOf() It provides the primitive value of string 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


The JavaScript String charAt() method returns the character at the given index.

<html>

<body>

<script>

var str="javascript";

document.write(str.charAt(2));

</script>

</body>

</html>

2) JavaScript String concat(str) Method


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

34
<html>

<body>

<script>

var s1="javascript ";

var s2="concat example";

var s3=s1+s2;

document.write(s3);

</script>

</body>

</html>

3) JavaScript String indexOf(str) Method


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

<!DOCTYPE html>

<html>

<body>

<script>

var s1="javascript from Digitinstitute indexof";

var n=s1.indexOf("from");

document.write(n);

</script>

</body>

</html>

JavaScript String toLowerCase() Method


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

<html>

<body>

35
<script>

var s1="JavaScript toLowerCase Example";

var s2=s1.toLowerCase();

document.write(s2);

</script>

</body>

</html>

JavaScript String toUpperCase() Method


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

<html>

<body>

<script>

var s1="JavaScript toUpperCase Example";

var s2=s1.toUpperCase();

document.write(s2);

</script>

</body>

</html>

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.

<html>

<body>

<script>

var s1="abcdefgh";

var s2=s1.slice(2,5);

36
document.write(s2);

</script>

</body>

</html>

JavaScript String trim() Method


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

<html>

<body>

<script>

var s1=" javascript trim ";

var s2=s1.trim();

document.write(s2);

</script>

</body>

</html>

JavaScript String split() Method

1. <script>
2. var str="This is Digitinstitute website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>

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.

Constructor
37
You 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)

JavaScript Date Methods


Let's see the list of JavaScript date methods with their description

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.

38
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.

JavaScript Date Example


Let's see the simple example to print date object. It prints date and time both.

<html>

<body>

Current Date and Time: <span id="txt"></span>

<script>

var today=new Date();

document.getElementById('txt').innerHTML=today;

</script>

</body>

</html>

JavaScript Current Time Example


Let's see the simple example to print current time of system.

<html>

<body>

Current Time: <span id="txt"></span>

<script>

var today=new Date();

var h=today.getHours();

var m=today.getMinutes();

var s=today.getSeconds();

document.getElementById('txt').innerHTML=h+":"+m+":"+s;

39
</script>

</body>

</html>

JavaScript Digital Clock Example


Let's see the simple example to display digital clock using JavaScript date object.

There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.

<html>

<body>

Current Time: <span id="txt"></span>

<script>

window.onload=function(){getTime();}

function getTime(){

var today=new Date();

var h=today.getHours();

var m=today.getMinutes();

var s=today.getSeconds();

// add a zero in front of numbers<10

m=checkTime(m);

s=checkTime(s);

document.getElementById('txt').innerHTML=h+":"+m+":"+s;

setTimeout(function(){getTime()},1000);

//setInterval("getTime()",1000);//another way

function checkTime(i){

if (i<10){

i="0" + i;

return i;

40
}

</script>

</body>

</html>

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


Let's see the list of JavaScript Math methods with description.

Methods Description

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

acos() It returns the arccosine of the given number in radians.

asin() It returns the arcsine of the given number in radians.

atan() It returns the arc-tangent of the given number in radians.

cbrt() It returns the cube root of the given number.

ceil() It returns a smallest integer value, greater than or equal to the given number.

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

cosh() It returns the hyperbolic cosine of the given number.

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

floor() It returns largest integer value, lower than or equal to the given number.

41
hypot() It returns square root of sum of the squares of given numbers.

log() It returns natural logarithm of a 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.

random() It returns random number between 0 (inclusive) and 1 (exclusive).

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

sign() It returns the sign of the given number

sin() It returns the sine of the given number.

sinh() It returns the hyperbolic sine of the given number.

sqrt() It returns the square root of the given number

Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.

<html>

<body>

Square Root of 17 is: <span id="p1"></span>

<script>

document.getElementById('p1').innerHTML=Math.sqrt(17);

</script>

</body>

42
</html>

Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.

<html>

<body>

Random Number is: <span id="p2"></span>

<script>

document.getElementById('p2').innerHTML=Math.random();

</script>

</body>

</html>

Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.

<html>

<body>

3 to the power of 4 is: <span id="p3"></span>

<script>

document.getElementById('p3').innerHTML=Math.pow(3,4);

</script>

</body>

</html>

Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.

43
<html>

<body>

Floor of 4.6 is: <span id="p4"></span>

<script>

document.getElementById('p4').innerHTML=Math.floor(4.6);

</script>

</body>

</html>

Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number.
For example 4 for 3.7, 6 for 5.9 etc.

<html>

<body>

Ceil of 4.6 is: <span id="p5"></span>

<script>

document.getElementById('p5').innerHTML=Math.ceil(4.6);

</script>

</body>

</html>

Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the
given number. If fractional part is equal or greater than 0.5, it goes to upper value 1
otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.

44
<html>

<body>

Round of 4.3 is: <span id="p6"></span><br>

Round of 4.7 is: <span id="p7"></span>

<script>

document.getElementById('p6').innerHTML=Math.round(4.3);

document.getElementById('p7').innerHTML=Math.round(4.7);

</script>

</body>

</html>

JavaScript Number Object


The JavaScript number object enables you to represent a numeric value. It may be
integer or floating-point. JavaScript number object follows IEEE standard to represent
the floating-point numbers.

By the help of Number() constructor, you can create number object in JavaScript. For
example:

1. var n=new Number(value);

If value can't be converted to number, it returns NaN(Not a Number) that can be


checked by isNaN() method.

<html>

<body>

<script>

var x=102;//integer value

var y=102.7;//floating point value

var z=13e4;//exponent value, output: 130000

var n=new Number(16);//integer value by number object

45
document.write(x+" "+y+" "+z+" "+n);

</script>

</body>

</html>

JavaScript Number Constants


Let's see the list of JavaScript number constants with description.

Constant Description

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.

JavaScript Number Methods


Let's see the list of JavaScript number methods with their description.

Methods Description

isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.

46
toExponential() It returns the string that represents exponential notation of the given number.

toFixed() It returns the string that represents a number with exact digits after a decimal point.

toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.

JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.

1. Boolean b=new Boolean(value);

The default value of JavaScript Boolean object is false.

JavaScript Boolean Example

1. <script>
2. document.write(10<20);//true
3. document.write(10<5);//false
4. </script>

JavaScript Boolean Properties

Property Description

constructor returns the reference of Boolean function that created Boolean object.

47
prototype enables you to add properties and methods in Boolean prototype.

JavaScript Boolean Methods

Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

Browser Object Model


The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:

1. window.alert("hello Digitinstitute");

is same as:

1. alert("hello Digitinstitute");

You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,

48
Window Object

The window object represents a window in browser. An object of window is created


automatically by the browser.

Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.

Methods of window object


The important methods of window object are as follows:

Method Description

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating expressions etc.

Example of alert() in javascript


It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

49
Example of confirm() in javascript

It displays the confirm dialog box. It has message with ok and cancel buttons.

1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>

Example of prompt() in javascript

It displays prompt dialog box for input. It has message and textfield.

1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>

50
8. <input type="button" value="click" onclick="msg()"/>

Example of open() in javascript

It displays the content in a new window.

1. <script type="text/javascript">
2. function msg(){
3. open("http://www.Digitinstitute.in");
4. }
5. </script>
6. <input type="button" value="Digitinstitute" onclick="msg()"/>

Example of setTimeout() in javascript

It performs its task after the given milliseconds.

1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Weline to Digitinstitute after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>

51
JavaScript History Object

The JavaScript history object represents an array of URLs visited by the user. By using
this object, you can load previous, forward or any particular page.

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

1. window.history

Or,

1. history

No. Property Description

1 length returns the length of the history URLs.

Methods of JavaScript history object


There are only 3 methods of history object.

No. Method Description

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

52
Example of history object
Let’s see the different usage of history object.

1. history.back();//for previous page


2. history.forward();//for next page
3. history.go(2);//for next 2nd page
4. history.go(-2);//for previous 2nd page

JavaScript Navigator Object


The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.

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

window.navigator

Or,

navigator

Property of JavaScript navigator object


There are many properties of navigator object that returns information of the browser.

No. Property Description

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false

5 userAgent returns the user agent

6 language returns the language. It is supported in Netscape and Firefox only.

53
7 userLanguage returns the user language. It is supported in IE only.

8 platform returns the platform e.g. Win32.

9 online returns true if browser is online otherwise false.

Methods of JavaScript navigator object


The methods of navigator object are given below.

No. Method Description

1 javaEnabled() checks if java is enabled.

2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript 1.2.

<html>

<body>

<h2>JavaScript Navigator Object</h2>

<script>

document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);

document.writeln("<br/>navigator.appName: "+navigator.appName);

document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);

document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);

document.writeln("<br/>navigator.language: "+navigator.language);

document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);

document.writeln("<br/>navigator.platform: "+navigator.platform);

document.writeln("<br/>navigator.onLine: "+navigator.onLine);

</script>

</body>

</html>

54
JavaScript Screen Object
The JavaScript screen object holds information of browser screen. It can be used to
display screen width, height, colorDepth, pixelDepth etc.

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

window.screen

Or,

screen

Property of JavaScript Screen Object


There are many properties of screen object that returns information of the browser.

No. Property Description

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.

<html>

<body>

<script>

document.writeln("<br/>screen.width: "+screen.width);

document.writeln("<br/>screen.height: "+screen.height);

document.writeln("<br/>screen.availWidth: "+screen.availWidth);

document.writeln("<br/>screen.availHeight: "+screen.availHeight);

55
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);

document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);

</script>

</body>

</html>

Document Object Model

The document object represents the whole html document.

When html document is loaded in the browser, it beines a document object. It is


the root element that represents the html document. It has properties and methods.
By the help of document object, we can add dynamic content to our web page.

As mentioned earlier, it is the object of window. So

window.document
or

document

Properties of document object


Let's see the properties of document object that can be accessed and modified by the
document object.

56
Methods of document object
We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

57
getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with weline
message.

<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

58
Javascript - document.getElementById()
method
The document.getElementById() method returns the element of specified id.

In the previous page, we have used document.form1.name.value to get the value of


the input value. Instead of this, we can use document.getElementById() method to get
value of the input text. But we need to define id for the input field.

Let's see the simple example of document.getElementById() method that prints cube
of the given number.

<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

Javascript -
document.getElementsByName() method
The document.getElementsByName() method returns all the element of specified
name.

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")

Here, name is required.

59
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.

<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>

Javascript -
document.getElementsByTagName()
method
The document.getElementsByTagName() method returns all the element of
specified tag name.

The syntax of the getElementsByTagName() method is given below:

1. document.getElementsByTagName("name")

Here, name is required.

60
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the document.
To do this, we have called the document.getElementsByTagName("p") method that
returns the total paragraphs.

<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);

}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>

Another example of document.getElementsByTagName() method

In this example, we going to count total number of h2 and h3 tags used in the
document.

<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>

61
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>

Javascript - innerHTML

The innerHTML property can be used to write the dynamic html on the html
document.

It is used mostly in the web pages to generate the dynamic html such as registration
form, inment form, links etc.

Example of innerHTML property


In this example, we are going to create the html form when user clicks on the button

In this example, we are dynamically writing the html form inside the div name having
the id mylocation. We are identifing this position by calling the
document.getElementById() method.

<html>

<body>

<script type="text/javascript" >

function showcommentform() {

var data="Name:<br><input type='text' name='name'><br>comment:<br><textarea rows='5'


cols='50'></textarea><br><input type='submit' value='comment'>";

document.getElementById('mylocation').innerHTML=data;

62
</script>

<form name="myForm">

<input type="button" value="comment" onclick="showcommentform()">

<div id="mylocation"></div>

</form>

</body>

</html>

Show/Hide Inment Form Example using


innerHTML

<html>
<head>
<title>First JS</title>
<script>
var flag=true;
function commentform(){
var cform="<form action='comment'>Enter Name:<br><input type='text' name='nam
e'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter comment:<br/>
<textarea rows='5' cols='70'></textarea><br>
<input type='submit' value='Post comment'/></form>";
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}else{
document.getElementById("mylocation").innerHTML="";
flag=true;
}
}
</script>
</head>
<body>
<button onclick="commentform()">comment</button>
<div id="mylocation"></div>

63
</body>
</html>

Javascript - innerText
The innerText property can be used to write the dynamic text on the html document.
Here, text will not be interpreted as html text but a normal text.

It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.

Javascript innerText Example


In this example, we are going to display the password strength when releases the key
after press.

<html>

<body>

<script type="text/javascript" >

function validate() {

var msg;

if(document.myForm.userPass.value.length>5){

msg="good";

else{

msg="poor";

document.getElementById('mylocation').innerText=msg;

</script>

<form name="myForm">

<input type="password" value="" name="userPass" onkeyup="validate()">

Strength:<span id="mylocation">no strength</span>

</form>

64
</body>

</html>

DropDownList Example
<html>

<head>

<title>dropdown menu using select tab</title>

</head>

<script>

function location()

var a = document.getElementById("myList");

document.getElementById("loc").value = a.options[mylist.selectedIndex].text;

</script>

<body>

<form>

<b> Select you favourite tutorial site using dropdown list </b>

<select id = "myList" onchange = "location()" >

<option> ---Choose Location--- </option>

<option> Hyderabad </option>

<option> chennai</option>

<option> Banglore</option>

<option> Mumbai </option>

</select>

<p> Your selected tutorial site is:

<input type = "text" id = "loc" size = "20" </p>

</form>

65
</body>

</html>

Create checkbox syntax


To create a checkbox use HTML <input> tab and type="checkbox" inside the tab as
shown below

Syntax: <input type="checkbox" id="c1" value="on" name="cb1">Yes

<html>
<body>

<h2 style="color:green">Create a checkbox and get its value</h2>


<h3> Are you a web developer? </h3>
Yes: <input type="checkbox" id="myCheck1" value="Yes, I'm a web developer">

No: <input type="checkbox" id="myCheck2" value="No, I'm not a web develope


r">
<br> <br>
<button onclick="checkCheckbox()">Submit</button> <br>

<h4 style="color:green" id="result"></h3>


<h4 style="color:red" id="error"></h3>

<script>
function checkCheckbox() {
var yes = document.getElementById("myCheck1");
var no = document.getElementById("myCheck2");
if (yes.checked == true && no.checked == true){
return document.getElementById("error").innerHTML = "Please mark only one c
heckbox either Yes or No";
}
else if (yes.checked == true){
var y = document.getElementById("myCheck1").value;

66
return document.getElementById("result").innerHTML = y;
}
else if (no.checked == true){
var n = document.getElementById("myCheck2").value;
return document.getElementById("result").innerHTML = n;
}
else {
return document.getElementById("error").innerHTML = "*Please mark any of ch
eckbox";
}
}
</script>

</body>

Radio button:
A radio button is an icon that is used in forms to take input from the user. It allows the
users to choose one value from the group of radio buttons. Radio buttons are basically
used for the single selection from multiple ones, which is mostly used in GUI forms.

You can mark/check only one radio button between two or more radio buttons. In this
chapter, we will guide you on how to check a radio button using the JavaScript
programming language

using HTML, and then we will use JavaScript programming to check the radio button. We
will also check which radio button value is selected.

Create a radio button


Following is a simple code for creating a group of radio buttons.

<html>

<body>

<p> Choose your favroite season: </p>

<input type="radio" name="JTP" id="summer" value="summer">Summer<br>

67
<input type="radio" name="JTP" id="winter" value="winter">Winter<br>

<input type="radio" name="JTP" id="rainy" value="rainy">Rainy<br>

<input type="radio" name="JTP" id="autumn" value="autumn">Autumn<br>

</body>

</html>

Check a radio button


We do not need to write any specific code to check the radio button. They can be
checked once they are created or specified in HTML form

However, we have to write the JavaScript code to get the value of the checked radio
button, which we will see in the chapter below:

Check the radio button is selected or not


There are two ways in JavaScript to check the marked radio button or to identify which
radio button is selected. JavaScript offers two DOM methods for this.

1. getElementById
2. querySelector

o The input radio checked property is used to check whether the checkbox is selected or
not. Use document.getElementById('id').checked method for this. It will return
the checked status of the radio button as a Boolean value. It can be either true or false.
o True - If radio button is selected.
o False - If radio button is not selected/ checked.
o See the JavaScript code below to know how it works:

if(document.getElementById('summer').checked == true) {
document.write("Summer radio button is selected");
68
} else {
document.write("Summer radio button is not selected");
}
querySelector()
The querySelector() function is a DOM method of JavaScript. It uses the common name
property of radio buttons inside it. This method is used as given below to check which
radio button is selected.

Example
For example, we have a radio button named Summer and id = 'summer'. Now, we will
check using this button id that the radio button is marked or not.

document.querySelector('input[name="JTP"]:checked')

Example
For example, we have a group of radio buttons having the name property name =
'season' for all buttons. Now, between these buttons named season we will check
which one is selected.

var getSelectedValue = document.querySelector( 'input[name="season"]:checked');


if(getSelectedValue != null) {
document.write("Radio button is selected");
else {
document.write("Nothing has been selected");

Get the value of checked radio button:

Using getElementById ()

69
if(document.getElementById('summer').checked) {
var selectedValue = document.getElementById('summer').value;
alert("Selected Radio Button is: " + selectedValue);
}

Using querySelector()
Following is the code to get the value of checked radio button using querySelector()
method:

var getSelectedValue = document.querySelector( 'input[name="season"]:checked');


if(getSelectedValue != null) {
alert("Selected radio button values is: " + getSelectedValue.value);
}

<html>

<body>

<br><b> Choose your favroite season: </b><br>

<input type="radio" id="summer" value="Summer">Summer<br>

<input type="radio" id="winter" value="Winter">Winter<br>

<input type="radio" id="rainy" value="Rainy">Rainy<br>

<input type="radio" id="autumn" value="Autumn">Autumn<br><br>

<button type="button" onclick=" checkButton()"> Submit </button>

<h3 id="disp" style= "color:green"> </h3>

<h4 id="error" style= "color:red"> </h4>

</body>

<script>

function checkButton() {

if(document.getElementById('summer').checked) {

70
document.getElementById("disp").innerHTML

= document.getElementById("summer").value

+ " radio button is checked";

else if(document.getElementById('winter').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("winter").value

+ " radio button is checked";

else if(document.getElementById('rainy').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("rainy").value

+ " radio button is checked";

else if(document.getElementById('autumn').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("autumn").value

+ " radio button is checked";

else {

document.getElementById("error").innerHTML

= "You have not selected any season";

</script>

</html>

71
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer JavaScript
form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.

<html>

<body>

<script>

function validateform(){

var name=document.myform.name.value;

var password=document.myform.password.value;

if (name==null || name==""){

alert("Name can't be blank");

return false;

}else if(password.length<6){

alert("Password must be at least 6 characters long.");

return false;

72
</script>

<body>

<form name="myform" >

Name: <input type="text" name="name"><br/>

Password: <input type="password" name="password"><br/>

<input type="submit" value="register">

</form>

</body>

</html>

JavaScript Retype Password Validation


<html>

<head>

<script type="text/javascript">

function matchpass(){

var firstpassword=document.f1.password.value;

var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){

return true;

else{

alert("password must be same!");

return false;

</script>

</head>

<body>

73
<form name="f1" >

Password:<input type="password" name="password" /><br/>

Re-enter Password:<input type="password" name="password2"/><br/>

<input type="submit">

</form>

</body>

</html>

JavaScript email validation


We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

o email id must contain the @ and . character


o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.

<html>

<body>

<script>

function validateemail()

var x=document.myform.email.value;

var atposition=x.indexOf("@");

var dotposition=x.lastIndexOf(".");

if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){

alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);

return false;

74
}

</script>

<body>

<form name="myform" >

Email: <input type="text" name="email"><br/>

<input type="submit" value="register">

</form>

</body>

</html>

JavaScript Classes
In JavaScript, classes are the special type of functions. We can define the class just like
function declarations and function expressions.

The JavaScript class contains various class members within a body including methods
or constructor. The class is executed in strict mode. So, the code containing the silent
error or mistake throws an error.

The class syntax contains two inponents:

o Class declarations
o Class expressions

Class Declarations
A class can be defined by using a class declaration. A class keyword is used to declare
a class with any particular name. According to JavaScript naming conventions, the
name of the class always starts with an uppercase letter.

15.8M
317
History of Java

Class Declarations Example


Let's see a simple example of declaring the class.

<html>

75
<body>

<script>

//Declaring class

class Employee

//Initializing an object

constructor(id,name)

this.id=id;

this.name=name;

//Declaring method

detail()

document.writeln(this.id+" "+this.name+"<br>")

//passing object to a variable

var e1=new Employee(101,"Martin Roy");

var e2=new Employee(102,"Duke William");

e1.detail(); //calling method

e2.detail();

</script>

</body>

</html>

Class Declarations Example: Hoisting


Unlike function declaration, the class declaration is not a part of JavaScript hoisting.
So, it is required to declare the class before invoking it.

76
Let's see an example.

<html>

<body>

<script>

//Here, we are invoking the class before declaring it.

var e1=new Employee(101,"Martin Roy");

var e2=new Employee(102,"Duke William");

e1.detail(); //calling method

e2.detail();

//Declaring class

class Employee

//Initializing an object

constructor(id,name)

this.id=id;

this.name=name;

detail()

document.writeln(this.id+" "+this.name+"<br>")

</script>

</body>

</html>

77
Class expressions
Another way to define a class is by using a class expression. Here, it is not mandatory
to assign the name of the class. So, the class expression can be named or unnamed.
The class expression allows us to fetch the class name. However, this will not be
possible with class declaration.

Unnamed Class Expression


The class can be expressed without assigning any name to it.

<html>

<body>

<script>

var emp = class {

constructor(id, name) {

this.id = id;

this.name = name;

};

document.writeln(emp.name);

</script>

</body>

</html>

Class Expression Example: Re-declaring Class


Unlike class declaration, the class expression allows us to re-declare the same class. So,
if we try to declare the class more than one time, it throws an error.

<html>

<body>

78
<script>

//Declaring class

var emp=class

//Initializing an object

constructor(id,name)

this.id=id;

this.name=name;

//Declaring method

detail()

document.writeln(this.id+" "+this.name+"<br>")

//passing object to a variable

var e1=new emp(101,"Martin Roy");

var e2=new emp(102,"Duke William");

e1.detail(); //calling method

e2.detail();

//Re-declaring class

var emp=class

//Initializing an object

constructor(id,name)

this.id=id;

this.name=name;

79
}

detail()

document.writeln(this.id+" "+this.name+"<br>")

//passing object to a variable

var e1=new emp(103,"James Bella");

var e2=new emp(104,"Nick Johnson");

e1.detail(); //calling method

e2.detail();

</script>

</body>

</html>

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

80
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2.....propertyN:valueN

example of creating object in JavaScript.

<html>

<body>

<script>

emp={id:102,name:"Shyam Kumar",salary:40000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

</body>

</html>

2) By creating instance of Object


The syntax of creating object directly is given below:

1. var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<body>

<script>

var emp=new Object();

emp.id=101;

emp.name="Ravi Malik";

emp.salary=50000;

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

81
</body>

</html>

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>

Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to
add property in the function with same name as method.

The example of defining method in object is given below.

<html>

82
<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

this.changeSalary=changeSalary;

function changeSalary(otherSalary){

this.salary=otherSalary;

e=new emp(103,"Sonoo Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

e.changeSalary(45000);

document.write("<br>"+e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>

JavaScript Constructor Method


A JavaScript constructor method is a special type of method which is used to initialize
and create an object. It is called when memory is allocated for an object.

Points to remember
o The constructor keyword is used to declare a constructor method.
o The class can contain one constructor method only.
o JavaScript allows us to use parent class constructor through super keyword.

Constructor Method Example


Let's see a simple example of a constructor method.

83
<html>

<body>

<script>

class Employee {

constructor() {

this.id=101;

this.name = "Martin Roy";

var emp = new Employee();

document.writeln(emp.id+" "+emp.name);

</script>

</body>

</html>

Constructor Method Example: super keyword


The super keyword is used to call the parent class constructor. Let's see an example.

<html>

<body>

<script>

class InpanyName

constructor()

this.inpany="Digitinstitute";

84
class Employee extends InpanyName {

constructor(id,name) {

super();

this.id=id;

this.name=name;

var emp = new Employee(1,"John");

document.writeln(emp.id+" "+emp.name+" "+emp.inpany);

</script>

</body>

</html>

JavaScript static Method


The JavaScript provides static methods that belong to the class instead of an instance
of that class. So, an instance is not required to call the static method. These methods
are called directly on the class itself.

Points to remember
o The static keyword is used to declare a static method.
o The static method can be of any name.
o A class can contain more than one static method.
o If we declare more than one static method with a similar name, the JavaScript always
invokes the last one.
o The static method can be used to create utility functions.
o We can use this keyword to call a static method within another static method.
o We cannot use this keyword directly to call a static method within the non-static
method. In such case, we can call the static method either using the class name or as
the property of the constructor.

<html>

<body>

85
<script>

class Test

static display()

return "static method is invoked"

document.writeln(Test.display());

</script>

</body>

</html>

Example 2
Le's see an example to invoke more than one static method.

<html>

<body>

<script>

class Test

static display1()

return "static method is invoked"

static display2()

86
{

return "static method is invoked again"

document.writeln(Test.display1()+"<br>");

document.writeln(Test.display2());

</script>

</body>

</html>

Example 3
Let's see an example to invoke a static method within the constructor.

<html>

<body>

<script>

class Test {

constructor() {

document.writeln(Test.display()+"<br>");

document.writeln(this.constructor.display());

static display() {

return "static method is invoked"

var t=new Test();

</script>

87
</body>

</html>

JavaScript Encapsulation
The JavaScript Encapsulation is a process of binding the data (i.e. variables) with the
functions acting on that data. It allows us to control the data and validate it. To achieve
an encapsulation in JavaScript: -

o Use var keyword to make data members private.


o Use setter methods to set the data and getter methods to get that data.

The encapsulation allows us to handle an object using the following properties:

Read/Write - Here, we use setter methods to write the data and getter methods read
that data.

Read Only - In this case, we use getter methods only.

Write Only - In this case, we use setter methods only.

JavaScript Encapsulation Example


Let's see a simple example of encapsulation that contains two data members with its
setter and getter methods.

<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)

88
{
this.name=name;
}

getMarks()
{
return this.marks;
}
setMarks(marks)
{
this.marks=marks;
}

}
var stud=new Student();
stud.setName("John");
stud.setMarks(80);
document.writeln(stud.getName()+" "+stud.getMarks());
</script>

JavaScript Inheritance
The JavaScript inheritance is a mechanism that allows us to create new classes on the
basis of already existing classes. It provides flexibility to the child class to reuse the
methods and variables of a parent class.

The JavaScript extends keyword is used to create a child class on the basis of a parent
class. It facilitates child class to acquire all the properties and behavior of its parent
class.

Points to remember
o It maintains an IS-A relationship.
o The extends keyword is used in class expressions or class declarations.
o Using extends keyword, we can acquire all the properties and behavior of the inbuilt
object as well as custom classes.
o We can also use a prototype-based approach to achieve inheritance.

89
JavaScript extends Example: inbuilt object

<html>

<body>

<script>

class Moment extends Date {

constructor() {

super();

}}

var m=new Moment();

document.writeln("Current date:")

document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear());

</script>

</body>

</html>

example to display the year value from the given date.

<html>

<body>

<script>

class Moment extends Date {

constructor(year) {

super(year);

}}

var m=new Moment("August 15, 1947 20:22:10");

document.writeln("Year value:")

document.writeln(m.getFullYear());

</script>

90
</body>

</html>

JavaScript extends Example: Custom class


In this example, we declare sub-class that extends the properties of its parent class.

<html>

<body>

<script>

class Bike

constructor()

this.inpany="Honda";

class Vehicle extends Bike {

constructor(name,price) {

super();

this.name=name;

this.price=price;

var v = new Vehicle("Shine","70000");

document.writeln(v.inpany+" "+v.name+" "+v.price);

</script>

</body>

91
</html>

JavaScript Polymorphism
The polymorphism is a core concept of an object-oriented paradigm that provides a
way to perform a single action in different forms. It provides an ability to call the same
method on different JavaScript objects. As JavaScript is not a type-safe language, we
can pass any type of data members with the methods.

<html>

<body>

<script>

class A

display()

document.writeln("A is invoked");

class B extends A

var b=new B();

b.display();

</script>

</body>

</html>

Example 2
Let's see an example where a child and parent class contains the same method. Here,
the object of child class invokes both classes method.

<html>

92
<body>

<script>

class A

display()

document.writeln("A is invoked<br>");

class B extends A

display()

document.writeln("B is invoked");

var a=[new A(), new B()]

a.forEach(function(msg)

msg.display();

});

</script>

</body>

</html>

JavaScript Abstraction
An abstraction is a way of hiding the implementation details and showing only the
functionality to the users. In other words, it ignores the irrelevant details and shows
only the required one.

93
Points to remember
o We cannot create an instance of Abstract Class.
o It reduces the duplication of code.

JavaScript Abstraction Example


Example 1
Let's check whether we can create an instance of Abstract class or not.

<html>

<body>

<script>

//Creating a constructor function

function Vehicle()

this.vehicleName="vehicleName";

throw new Error("You cannot create an instance of Abstract Class");

Vehicle.prototype.display=function()

return "Vehicle is: "+this.vehicleName;

//Creating a constructor function

function Bike(vehicleName)

this.vehicleName=vehicleName;

//Creating object without using the function constructor

Bike.prototype=Object.create(Vehicle.prototype);

var bike=new Bike("Honda");

document.writeln(bike.display());

94
</script>

</body>

</html>

JavaScript Events
The change in the state of an object is known as an Event. In html, there
are various events which represents that some activity is performed by the
user or by the browser. When javascript code is included in HTML, js react
over these events and allow the execution. This process of reacting over the events
is called Event Handling. Thus, js handles the HTML events via Event
Handlers.

For example, when a user clicks over the browser, add js code, which will execute the
task to be performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse moves over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

95
Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form element

Click Event
<html>

<head> Javascript Events </head>

<body>

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

<!--

function clickevent()

document.write("This is Digitinstitute");

//-->

</script>

<form>

<input type="button" onclick="clickevent()" value="Who's this?"/>

</form>

</body>

</html>

96
MouseOver Event

<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is Digitinstitute");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

Focus Event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>

97
Keydown Event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>

Load event

<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>

98
JavaScript onclick event
The onclick event generally occurs when the user clicks on an element. It allows the
programmer to execute a JavaScript's function when an element gets clicked. This
event can be used for validating a form, warning messages and many more.

Using JavaScript, this event can be dynamically added to any element. It supports all
HTML elements except <html>

In HTML

1. <element onclick = "fun()">


In JavaScript

1. object.onclick = function() { myScript };

Example1 - Using onclick attribute in HTML


In this example, we are using the HTML onclick

attribute and assigning a JavaScript's function to it. When the user clicks the given button, the
corresponding function will get executed, and an alert dialog box will be displayed on the scree

<html>
<head>
<script>
function fun() {
alert("Welcome to the Digitinstitute.in");
}
</script>
</head>

99
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">Click me</button>
</body>
</html>

Example2 - Using JavaScript


In this example, we are using JavaScript's onclick event. Here we are using
the onclick event with the paragraph element.

When the user clicks on the paragraph

element, the corresponding function will get executed, and the text of the paragraph gets changed.
On clicking the <p> element, the background color

, size, border, and color of the text will also get change.

<html>
<head>
<title> onclick event </title>
</head>
<body>
<h3> This is an example of using onclick event. </h3>
<p> Click the following text to see the effect. </p>
<p id = "para">Click me</p>
<script>
document.getElementById("para").onclick = function() {
fun()
};
function fun() {
document.getElementById("para").innerHTML = "Welcome to the Digitinstitute.in";
document.getElementById("para").style.color = "blue";
document.getElementById("para").style.backgroundColor = "yellow";
document.getElementById("para").style.fontSize = "25px";
document.getElementById("para").style.border = "4px solid red";
}
</script>

100
</body>
</html>

JavaScript dblclick event


The dblclick event generates an event on double click the element. The event fires
when an element is clicked twice in a very short span of time. We can also use the
JavaScript's addEventListener() method to fire the double click event.

In HTML, we can use the ondblclick attribute to create a double click event.

Syntax
Now, we see the syntax of creating double click event in HTML and
in javascript (without using addEventListener() method or by using
the addEventListener() method).

In HTML
1. <element ondblclick = "fun()">

In JavaScript
1. object.ondblclick = function() { myScript };

Example - Using ondblclick attribute in HTML


In this example, we are creating the double click event using the
HTML ondblclick attribute.

<!DOCTYPE html>
<html>
<head>
</head>

<body>
<h1 id = "heading" ondblclick = "fun()"> Hello world :):) </h1>
<h2> Double Click the text "Hello world" to see the effect. </h2>

101
<p> This is an example of using the <b> ondblclick </b> attribute. </p>
<script>
function fun() {
document.getElementById("heading").innerHTML = " Welcome to the Digitinstitute.in";
}
</script>
</body>
</html>

Example - Using JavaScript


<!DOCTYPE html>
<html>
<head>
</head>

<body>
<h1 id = "heading"> Hello world :):) </h1>
<h2> Double Click the text "Hello world" to see the effect. </h2>
<p> This is an example of creating the double click event using JavaScript. </p>
<script>
document.getElementById("heading").ondblclick = function() { fun() };
function fun() {
document.getElementById("heading").innerHTML = " Welcome to the Digitinstitute.in";
}
</script>
</body>

</html>

Example - Using JavaScript's addEventListener() method


<!DOCTYPE html>
<html>
<head>
</head>

<body>

102
<h1 id = "heading"> Hello world :):) </h1>
<h2> Double Click the text "Hello world" to see the effect. </h2>
<p> This is an example of creating the double click event using the <b> addEventListen
er() method </b>. </p>
<script>
document.getElementById("heading").addEventListener("dblclick", fun);
function fun() {
document.getElementById("heading").innerHTML = " Welcome to the Digitinstitute.in";
}
</script>
</body>

</html>

JavaScript onload
In JavaScript, this event can apply to launch a particular function when the page is fully
displayed. It can also be used to verify the type and version of the visitor's browser. We can
check what cookies a page uses by using the onload attribute.

In HTML, the onload attribute fires when an object has been loaded. The purpose of this
attribute is to execute a script when the associated element loads.

In HTML, the onload attribute is generally used with the <body> element to execute a
script once the content (including CSS files, images, scripts, etc.) of the webpage is
completely loaded. It is not necessary to use it only with <body> tag, as it can be used with
other HTML elements.

The difference between


the document.onload and window.onload is: document.onload triggers before
the loading of images and other external content. It is fired before
the window.onload. While the window.onload triggers when the entire page loads,
including CSS files, script files, images, etc.

Syntax
1. window.onload = fun()

Let's understand this event by using some examples.

103
Example1
In this example, there is a div element with a height of 200px and a width of 200px.
Here, we are using the window.onload() to change the background color, width, and
height of the div element after loading the web page.

The background color is set to 'red', and width and height are set to 300px each.

<html>
<head>
<meta charset = " utf-8">
<title> window.onload() </title>
<style type = "text/css">
#bg{
width: 200px;
height: 200px;
border: 4px solid blue;
}
</style>
<script type = "text/javascript">
window.onload = function(){
document.getElementById("bg").style.backgroundColor = "red";
document.getElementById("bg").style.width = "300px";
document.getElementById("bg").style.height = "300px";
}
</script>
</head>
<body>
<h2> This is an example of window.onload() </h2>
<div id = "bg"></div>
</body>
</html>

JavaScript onresize event


The onresize event in JavaScript generally occurs when the window has been resized.
To get the size of the window, we can use the

104
JavaScript's window.outerWidth and window.outerHeight events. We can also use
the JavaScript's properties such as innerWidth, innerHeight, clientWidth,
ClientHeight, offsetWidth, offsetHeight to get the size of an element.

In HTML, we can use the onresize attribute and assign a JavaScript function to it. We
can also use the JavaScript's addEventListener()

method and pass a resize event to it for greater flexibility.

Syntax

In HTML

1. <element onresize = "fun()">


In JavaScript

1. object.onresize = function() { myScript };

Example
In this example, we are using the HTML onresize attribute. Here, we are using
the window.outerWidth and window.outerHeight events of JavaScript to get the
height and width of the window.

When the user resizes the window, the updated width and height of the window will
be displayed on the screen. It will also display how many times the user tried to resize
the window. When we change the height of the window, the updated height will
change accordingly. Similarly, when we change the width of the window, the updated
width will change accordingly.

105
<!DOCTYPE html>
<html>
<head>
<script>
var i = 0;

function fun() {
var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;
document.getElementById("para").innerHTML = res;

var res1 = i += 1;
document.getElementById("s1").innerHTML = res1;
}
</script>
</head>
<body onresize = "fun()">
<h3> This is an example of using onresize attribute. </h3>
<p> Try to resize the browser's window to see the effect. </p>

<p id = "para"> </p>


<p> You have resized the window <span id = "s1"> 0 </span> times.</p>
</body>
</html>

Example - Using JavaScript


In this example, we are using JavaScript's onresize event.

<!DOCTYPE html>
<html>

106
<head>
</head>
<body>
<h3> This is an example of using JavaScript's onresize event. </h3>
<p> Try to resize the browser's window to see the effect. </p>

<p id = "para"> </p>


<p> You have resized the window <span id = "s1"> 0 </span> times.</p>
<script>
document.getElementsByTagName("BODY")[0].onresize = function() {fun()};
var i = 0;

function fun() {
var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;
document.getElementById("para").innerHTML = res;

var res1 = i += 1;
document.getElementById("s1").innerHTML = res1;
}
</script>
</body>
</html>

Exception Handling in JavaScript


An exception signifies the presence of an abnormal condition which requires special operable
techniques. In programming terms, an exception is the anomalous code that breaks the
normal flow of the code. Such exceptions require specialized programming constructs for its
execution.

What is Exception Handling


In programming, exception handling is a process or method used for handling the abnormal
statements in the code and executing them. It also enables to handle the flow control of the
code/program. For handling the code, various handlers are used that process the exception
and execute the code. For example, the Division of a non-zero value with zero will result
into infinity always, and it is an exception. Thus, with the help of exception handling, it can
be executed and handled.

In exception handling:

107
A throw statement is used to raise an exception. It means when an abnormal condition occurs,
an exception is thrown using throw.

The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will get
executed.

Thus, in a programming language, there can be different types of errors which may
disturb the proper execution of the program.

Types of Errors
While coding, there can be three types of errors in the code:

1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a


programming language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program,
such an error is known as Runtime error. The codes which create runtime errors
are known as Exceptions. Thus, exception handlers are used for handling
runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the
program that may not produce the desired output, and may terminate
abnormally. Such an error is known as Logical error.

Error Object
When a runtime error occurs, it creates and throws an Error object. Such an object can
be used as a base for the user-defined exceptions too. An error object has two
properties:

1. name: This is an object property that sets or returns an error name.


2. message: This property returns an error message in the string form.

Although Error is a generic constructor, there are following standard built-in error
types or error constructors beside it:

1. EvalError: It creates an instance for the error that occurred in the eval(), which is a
global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.

108
4. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an error.
7. URIError: An instance is created for the error that occurs when invalid parameters are
passed in encodeURI() or decodeURI().

Exception Handling Statements

There are following statements that handle if any exception occurs:

o throw statements
o try…catch statements
o try…catch…finally statements.

These exception handling statements are discussed in the next section.

JavaScript try…catch
A try…catch is a commonly used statement in various programming languages.
Basically, it is used to handle the error-prone part of the code. It initially tests the code
for all possible errors it may contain, then it implements actions to tackle those errors
(if occur). A good programming approach is to keep the complex code within the
try…catch statements.

try{} statement: Here, the code which needs possible error testing is kept within the
try block. In case any error occur, it passes to the catch{} block for taking suitable
actions and handle the error. Otherwise, it executes the code written within.

catch{} statement: This block handles the error of the code by executing the set of
statements written within the block. This block contains either the user-defined
exception handler or the built-in handler. This block executes only when any error-
prone code needs to be handled in the try block. Otherwise, the catch block is skipped.

109
Syntax:

try{
expression; } //code to be written.
catch(error){
expression; } // code for handling the error.

Throw Statement
Throw statements are used for throwing user-defined errors. User can define and
throw their own custom errors. When throw statement is executed, the statements
present after it will not execute. The control will directly pass to the catch block.

Syntax:

1. throw exception;

try…catch…throw syntax

try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.

The exception can be a string, number, object, or boolean value.

throw example with try…catch

110
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>

With the help of throw statement, users can create their own errors.

try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try
and catch statements. Finally block does not hold for the exception to be thrown. Any
exception is thrown or not, finally block code, if present, will definitely execute. It does
not care for the output too.

Syntax:

try{
expression;
}
catch(error){

111
expression;
}
finally{
expression; } //Executable code

try…catch…finally example

<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>

JavaScript this keyword


The this keyword is a reference variable that refers to the current object. Here, we will
learn about this keyword with help of different examples.

JavaScript this Keyword Example


Let's see a simple example of this keyword.

<script>
var address=
{

112
company:"Digitinstitute",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
}
};

var fetch=address.fullAddress();
document.writeln(fetch);

</script>

113

You might also like