0% found this document useful (0 votes)
11 views55 pages

FSD MODULE-2-JavaScript PDF

Javascript

Uploaded by

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

FSD MODULE-2-JavaScript PDF

Javascript

Uploaded by

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

MODULE – II NECN

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.

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.

Example

<html>

<body>

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

document.write("Hello World!")

</script>

</body>

</html>

1|Dept. of MCA
MODULE – II NECN

JavaScript Comment

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.

Types of JavaScript Comments

There are two types of comments 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.

<script>
// It is single line comment
document.write("hello javascript");
</script>

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:

/* your code here */

Example:

<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

2|Dept. of MCA
MODULE – II NECN

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

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

var x = 10;
var _value="sonoo";

Incorrect JavaScript variables

var 123=30;
var *aa=320;

example

<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>

JavaScript local variable

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

<script>
function abc(){
var x=10;//local variable
}
3|Dept. of MCA
MODULE – II NECN

</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
b();
</script>

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

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:

var a=40;//holding number


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

4|Dept. of MCA
MODULE – II NECN

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

1) Explain operators and expressions in java script with an example?


JavaScript Operators

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

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

5|Dept. of MCA
MODULE – II NECN

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

JavaScript Comparison Operators

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

Example

10==20 = false

10==20 = false

6|Dept. of MCA
MODULE – II NECN

!= 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

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

7|Dept. of MCA
MODULE – II NECN

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

/= 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.

8|Dept. of MCA
MODULE – II NECN

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

Expressions in JavaScript

An expression is a block of code that evaluates to a value. A statement is any block of code
that is performing some action.

The distinction between an expression and a statement is important because an expression


is a subset of a statement. You can use an expression wherever a statement is expected, but
this does not work vice versa.

Conceptually speaking, there are two kinds of expressions: those that perform some sort of
assignment and those that evaluate to a value.

For example, x = 10 is an expression that performs an assignment. This expression itself


evaluates to 10. Such expressions make use of the assignment operator.

On the flip side, the expression 10 + 9 simply evaluates to 19. These expressions make use of
simple operators.

There are five primary categories of expression in JavaScript:

 Arithmetic: uses arithmetic operators (+ - * / %).


 String: uses string operators and evaluates to a character string.
 Logical: evaluates to a boolean value of either True or False and uses boolean
operators.
 Primary expressions: Consists of basic keywords and expressions.

9|Dept. of MCA
MODULE – II NECN

Left-hand side expressions: Left-hand side values which are the destination for the
assignment operator

Primary expressions

Primary expressions consist of basic keywords in JavaScript.

this:

this is used to refer to the current object; it usually refers to the method or object that calls
it.

this is used either with the dot operator or the bracket operator.

this['element']
this.element

Grouping operator

The grouping operator ( ) is used to determine the evaluation precedence of expressions.


For example, the two expressions below evaluate to different results because the order of
operations is different in both of them.

a*b-c
a * (b - c)

a * b - c applies the multiplication operator first and then evaluates the result of the
multiplication with - b, while a * (b - c) evaluates the brackets first.

Left-hand side expressions

new

new creates an instance of the object specified by the user and has the following prototype.

var objectName = new objectType([param1, param2, ..., paramN]);

super

super calls on the current object’s parent and is useful in classes to call the parent object’s
constructor.

super([arguments]); // parent constructor


super.method(args...) // parent's method

Function arguments

The arguments of a function must be an expression, not statements. For example, we can
pass in a variable assignment expression as an argument, but we cannot declare a variable
10 | D e p t . o f M C A
MODULE – II NECN

in the argument as it is a statement.

Suppose we have the following function:


.

const function
myFunc(arg){ console.log(arg);
}

It is reasonable to pass an object or an expression, such as a ternary operator, in the


argument as follows:

myFunc("This is okay");
myFunc(true ? "This is okay" : None);

But we cannot pass in a statement here:

var x = 10
myFunc(if(x > 10){'This will not work'});

As a rule of thumb, any code snippet that can be passed on to the console.log function and
printed can be used as an argument for a function.

JavaScript If statement
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

JavaScript If statement

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

if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");

11 | D e p t . o f M C A
MODULE – II NECN

}
</script>
Output of the above example
value of a is greater than 10

12 | D e p t . o f M C A
MODULE – II NECN

JavaScript If...else Statement

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

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number

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

13 | D e p t . o f M C A
MODULE – II NECN

else{
//content to be evaluated if no expression is true
}

Let’s see the simple example of if else if statement in javascript.

<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>
Output of the above example
a is equal to 20

3) Write about if and switch statements in javascript with an example.

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;
14 | D e p t . o f M C A
MODULE – II NECN

case value2:
code to be executed;
break;
......

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

Let’s see the simple example of switch statement in javascript.

<script>
var grade='B';
var result;
switch(grade){ c
ase '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>
Output of the above example
B Grade

15 | D e p t . o f M C A
MODULE – II NECN

8) Explain about iterative control statements with an example?


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 compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in 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.

for (initialization; condition; increment)


{
code to be executed
}
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:
1
2
3
4
5

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.
16 | D e p t . o f M C A
MODULE – II NECN

while (condition)
{
code to be executed
}

<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15

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.

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

Let’s see the simple example of do while loop in javascript.

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);

17 | D e p t . o f M C A
MODULE – II NECN

</script>
Output:
21
22
23
24
25

4) JavaScript for in loop

The JavaScript for in loop is used to iterate the properties of an object.

For-in loop in JavaScript is used to iterate over the properties of an object. It can be a
great debugging tool if we want to show the contents of an object

Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}

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)

18 | D e p t . o f M C A
MODULE – II NECN

1) JavaScript Object by object literal

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

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

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

<script>
emp={id:102,name:"samuel",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
102 samuel 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
101 Ravi 50000

3) By using an Object constructor


19 | D e p t . o f M C A
MODULE – II NECN

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.

<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>
Output of the above example
103 VimalJaiswal 30000

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.

<script>
function
emp(id,name,salary){ this.id=id;
this.name=name;
this.salary=salary;

this.changeSalary=changeSalary;
function
changeSalary(otherSalary){ this.salary
=otherSalary;
}
}
20 | D e p t . o f M C A
MODULE – II NECN

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

21 | D e p t . o f M C A
MODULE – II NECN

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>
Output of the above example
103 SonooJaiswal 30000
103 SonooJaiswal 45000

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy


enumerable and own properties from
a source object to a target object

2 Object.create() This method is used to create a new


object with the specified prototype
object and properties.

3 Object.defineProperty() This method is used to describe some


behavioral attributes of the property.

4 Object.defineProperties() This method is used to create or


configure multiple object properties.

5 Object.entries() This method returns an array with


arrays of the key, value pairs.

6 Object.freeze() This method prevents existing


properties from being removed.

7 Object.getOwnPropertyDescriptor() This method returns a property


descriptor for the specified property of
the specified object.

22 | D e p t . o f M C A
MODULE – II NECN

8 Object.getOwnPropertyDescriptors() This method returns all own property

descriptors of a given object.

9 Object.getOwnPropertyNames() This method returns an array of all


properties (enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all


own symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of


the specified object.

12 Object.is() This method determines whether two


values are the same value.

13 Object.isExtensible() This method determines if an object is


extensible

14 Object.isFrozen() This method determines if an object


was frozen.

15 Object.isSealed() This method determines if an object is


sealed.

16 Object.keys() This method returns an array of a given


object's own property names.

17 Object.preventExtensions() This method is used to prevent any


extensions of an object.

18 Object.seal() This method prevents new properties


from being added and marks all
existing properties as non-
configurable.

19 Object.setPrototypeOf() This method sets the prototype of a


specified object to another object.

23 | D e p t . o f M C A
MODULE – II NECN

20 Object.values() This method returns an array of values.

2) Demonstrate the usage of array in JavaScript with an example?

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];

As you can see, values are contained inside [ ] and separated by , (comma).

<script>

var emp=["Sonoo","Vimal","Ratan"];
for
(i=0;i<emp.length;i++){ document.wri
te(emp[i] + "<br/>");
}
</script>

The length property returns the length of an array.

Output of the above example

Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:


24 | D e p t . o f M C A
MODULE – II NECN

var arrayname=new Array();

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


Let's see the example of creating array directly.

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

Output of the above example

Arun
Varun
John

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.

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

<script>
var emp=new Array("Jai","Vijay","Smith");
for
(i=0;i<emp.length;i++){ document.write(em
p[i] + "<br>");
}
</script>

Output of the above example

25 | D e p t . o f M C A
MODULE – II NECN

Jai
Vijay
Smith

7 a) Define functions with an example?


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 compact. We don’t need to write many lines of
code each time to perform a common task.

JavaScript Function Syntax

The syntax of declaring function is given below.

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


//code to be executed
}

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example

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

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Output of the above example

JavaScript Function Arguments

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

26 | D e p t . o f M C A
MODULE – II NECN

<script>
function getcube(number){

alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Output of the above example

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.

<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello javatpoint! How r u?

7 b) Explain about Constructors?

Constructor in JavaScript
A constructor is a function that creates an instance of a class which is typically called an
“object”. In JavaScript, a constructor gets called when you declare an object using
the new keyword.

The purpose of a constructor is to create an object and set values if there are any object
properties present. It’s a neat way to create an object because you do not need to explicitly
state what to return as the constructor function, by default, returns the object that gets
created within it.

Example

Let’s say there is an object, User, which has two properties: firstname and lastname.
27 | D e p t . o f M C A
MODULE – II NECN

To initialize two instances with different names, you will use the same constructor function,
as shown in the figure below:

What happens when a constructor gets called?


In JavaScript, here’s what happens when a constructor is invoked:

 A new empty object is created


 this keyword starts referring to that newly created object and hence it becomes
the current instance object
 The newly created object is then returned as the constructor’s returned value
Given below is the code to initialize two user instances just as shown in the above
illustration:

Function User(first,

last){ this.firstName = first

this.lastName = last

}
Var user1 = new User("Jon","Snow")

console.log(user1)

var user2 = new User("Ned", "Stark")

console.log(user2)

Output
User { firstName: 'Jon', lastName: 'Snow' } User { firstName: 'Ned', lastName: 'Stark' }

Default constructors

In JavaScript, if you don’t specify any constructor, a default constructor is automatically


created which has no parameters:

constructor()

Note: Constructors have the same name as that of the object which is being created. As a
convention, the first alphabet is kept capital in the constructor function.

28 | D e p t . o f M C A
MODULE – II NECN

5) Explain about pattern matching using regular expressions with an example.


Regular Expressions
A regular expression is a sequence of characters that forms a search pattern. The search
pattern can be used for text search and text to replace operations. A regular expression
can be a single character or a more complicated pattern. Regular expressions can be used
to perform all types of text search and text replaces operations.

Syntax:
/pattern/modifiers;

Example:
var patt = /Java script/i;

Regular Expression Modifiers:


Modifiers can be used to perform multiline searches:

Examples:
Expressions Description

[abc] Find any of the character inside the brackets

[0-9] Find any of the digits between the brackets 0 to 9

(x | y) Find any of the alternatives between x or y separated with |

Regular Expression Patterns :


Metacharacters are characters with a special meaning:

Examples:
Metacharacter Description

\d Used to find a digit

\s Used to find a whitespace character

\b Used to find a match at beginning or at the end of a word

Used to find the Unicode character specified by the hexadecimal number


\uxxxx xxxxx

29 | D e p t . o f M C A
MODULE – II NECN

Quantifiers define quantities:

Examples:
Quantifier Description

n+ Used to match any string that contains at least one n

n* Used to match any string that contains zero or more occurrences of n

n? Used to matches any string that contains zero or one occurrences of n

Using String Methods:


regular expressions are often used with the two string methods:
1. search()
2. replace().

The search() method uses an expression to search for a match, and returns the position of
the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression :
Use a regular expression to do a case-insensitive search for “java script” in a string:
Example:

function myFunction() {
// input string
var str = " JavaScript follows the syntax and structure of the C programming!";
// searching string with modifier i
var n = str.search(/JavaScript /i);
document.write(n + '<br>');
// searching string without modifier i
var n = str.search(/JavaScript /);
document.write(n);
}
myFunction();
Output:
6
-1

30 | D e p t . o f M C A
MODULE – II NECN

Use String replace() With a Regular Expression :


Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:
Example:
function myFunction() {

// input string

var str = " JavaScript follows the syntax and structure of the C programming!";

// replacing with modifier i

var txt = str.replace(/C programming /i, " C programming language");

document.write(txt);

myFunction();

Output:
JavaScript follows the syntax and structure of the C programming language!

31 | D e p t . o f M C A
MODULE – II NECN

Exception Handling in JavaScript


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.

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.

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.

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.

Let's discuss each block of statement individually:

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.

32 | D e p t . o f M C A
MODULE – II NECN

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.

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

try…catch example
<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be
invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html>

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:
throw exception;

try…catch…throw syntax
try{
throw exception; // user can define their own exception
33 | D e p t . o f M C A
MODULE – II NECN

}
catch(error){
expression; } // code for handling exception.

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

throw example with try…catch


<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{ expressio
n;
}
catch(error){ e
xpression;
}
finally{
expression; } //Executable code

34 | D e p t . o f M C A
MODULE – II NECN

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>

35 | D e p t . o f M C A
MODULE – II NECN

Built-in Objects

 Built-in objects are not related to any Window or DOM object model.
 These objects are used for simple data processing in the JavaScript.

1. Math Object

 Math object is a built-in static object.


 It is used for performing complex math operations.
Math Properties

Math Property Description

SQRT2 Returns square root of 2.

PI Returns Π value.

E\ Returns Euler's Constant.

LN2 Returns natural logarithm of 2.

LN10 Returns natural logarithm of 10.

LOG2E Returns base 2 logarithm of E.

LOG10E Returns 10 logarithm of E.

Math Methods

Methods Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns cosine of a number.

floor() Returns the largest integer less than or equal to a number.

36 | D e p t . o f M C A
MODULE – II NECN

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is base exponent.

Example: Simple Program on Math Object Methods

<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">

var value = Math.abs(20);


document.write("ABS Test Value : " + value +"<br>");

var value = Math.acos(-1);


document.write("ACOS Test Value : " + value +"<br>");

var value = Math.asin(1);


document.write("ASIN Test Value : " + value +"<br>");

var value = Math.atan(.5);


document.write("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>

2. Date Object

 Date is a data type.


 Date object manipulates date and time.
 Date() constructor takes no arguments.
37 | D e p t . o f M C A
MODULE – II NECN

 Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.
Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.

setMilliseconds() Sets the milliseconds.

setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.

setMonth() Sets the month.

toDateString() Returns the date portion of the Date as a human-readable string.

38 | D e p t . o f M C A
MODULE – II NECN

toLocaleString() Returns the Date object as a string.

toGMTString() Returns the Date object as a string in GMT timezone.

valueOf() Returns the primitive value of a Date object.

Example : JavaScript Date() Methods Program

<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>

3. String Object

 String objects are used to work with text.


 It works with a series of characters.
Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Properties

39 | D e p t . o f M C A
MODULE – II NECN

Properties Description

length It returns the length of the string.

prototype It allows you to add properties and methods to an object.

constructor It returns the reference to the String function that created the object.

String Methods

Methods Description

charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the specified position.

concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.

replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between a regular expression.

slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by separating the string into the
substrings.

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.

Example : JavaScript String() Methods Program

<html>
<body>
40 | D e p t . o f M C A
MODULE – II NECN

<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>

41 | D e p t . o f M C A
MODULE – II NECN

4) Explain uses of JavaScript for FORM validations with an example.

(or)

11) Explain Form Submission with example?

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.

<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;
}
}
</script>
<body>
42 | D e p t . o f M C A
MODULE – II NECN

<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()"


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

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


</form>

JavaScript Retype Password Validation

<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){ retur
n true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.jsp" onsubmit="return matchpass()">


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

JavaScript Number Validation

<script>
function validate(){
var num=document.myform.num.value;

43 | D e p t . o f M C A
MODULE – II NECN

if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

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

<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;
}
}
</script>
<body>
44 | D e p t . o f M C A
MODULE – II NECN

<form name="myform" method="post" action="#" onsubmit="return validateemail();">


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

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

</form>

45 | D e p t . o f M C A
MODULE – II NECN

6 Explain Event handling in JavaScript with suitable example.


(or)
12 Explain various events in javascript.

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:

Event Event Description


Performed Handler

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes 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 Event Handler Description


Performed

Keydown & Keyup onkeydown & When the user press and then release the
onkeyup key
46 | D e p t . o f M C A
MODULE – II NECN

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

Window/Document events

Event Event Description


Performed Handler

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the
browser unloads it

resize onresize When the visitor resizes the window of the browser

Examples:

Click Event

<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaScript on Clickevent");
}
//-->
47 | D e p t . o f M C A
MODULE – II NECN

</script>
<form>

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


</form>
</body>
</html>

MouseOver Event

<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is on mouseoverevent");
}
//-->
</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";
48 | D e p t . o f M C A
MODULE – II NECN

}
//-->

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

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>
49 | D e p t . o f M C A
MODULE – II NECN

DHTML JavaScript
DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user.
In earlier times, HTML was used to create a static page. It only defined the structure of the
content that was displayed on the page. With the help of CSS, we can beautify the HTML
page by changing various properties like text size, background color etc.

DHTML came into existence. DHTML included JavaScript along with HTML and CSS to make
the page dynamic. This combo made the web pages dynamic and eliminated this problem of
creating static page for each user. To integrate JavaScript into HTML, a Document Object
Model (DOM) is made for the HTML document. In DOM, the document is represented as
nodes and objects which are accessed by different languages like JavaScript to manipulate
the document.

HTML document include JavaScript:: The JavaScript document is included in our html
page using the html tag. <src> tag is used to specify the source of external JavaScript file.
Following are some of the tasks that can be performed with JavaScript:
 Performing html tasks
 Performing CSS tasks
 Handling events
 Validating inputs
Example 1: Example to understand how to use JavaScript in DHTML.
<html>
<head>
<title>DOM programming</title>
</head>
<body>
<h1>DHTML With JavaScript</h1>
<p id = "DH">Hello DHTML!</p>

50 | D e p t . o f M C A
MODULE – II NECN

<script style = "text/javascript">


document.getElementById("geeks").innerHTML =
"A computer science portal for DHTML with JavaScript";
</script>
</body>
</html>
Output:
Example 2: Creating an alert on click of a button.
<html>
<head>
<title>Create an alert</title>
</head>
<body>
<h1 id = "para1"> DHTML With Javascript </h1>
<input type = "Submit" onclick = "Click()"/>
<script style = "text/javascript">
function Click() {
document.getElementById("para1").style.color = "#009900";
window.alert("Color changed to green");
}
</script>
</body>
</html>

Example 3: Validate input data using JavaScript.


<html>
<head>
<title>Validate input data</title>
</head>
<body>
<p>Enter graduation percentage:</p>
<input id="perc">
<button type="button" onclick="Validate()">Submit</button>
<p id="demo"></p>
<script>
function Validate()
{ var x, text;
x = document.getElementById("perc").value;
if (isNaN(x) || x < 60) {
window.alert("You are not selected ");
} else
{ document.getElementById("demo").innerHTML =
"Selected: Welcome! ";
document.getElementById("demo").style.color = "#009900";
51 | D e p t . o f M C A
MODULE – II NECN

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

DHTML CSS

We can easily use the CSS with the DHTML page with the help of JavaScript and HTML DOM.
With the help of this.style.property=new style statement, we can change the style of the
currently used HTML element. Or, we can also update the style of any particular HTML
element by document.getElementById(id).style.property = new_style statement.

Example 1: The following example uses the DHTML CSS for changing the style of current
element:

<html>
<head>
<title>
Changes current HTML element
</title>
</head>
<body>
<center>
<h1 onclick="this.style.color='blue'"> This is a JavaTpoint Site </h1>
<center>
</body>
</html>

52 | D e p t . o f M C A
MODULE – II NECN

Example 2: The following example uses the DHTML CSS for changing the style of the
HTML element:

<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </
p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">

function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>

53 | D e p t . o f M C A
MODULE – II NECN

Document Object Model


The document object represents the whole html document.

When html document is loaded in the browser, it becomes 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

document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."

Properties of document object

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:

54 | D e p t . o f M C A
MODULE – II NECN

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.

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.

Let's see the simple example of document object that prints name with welcome 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>

55 | D e p t . o f M C A

You might also like