Ubit - Iii WT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

UNIT – III

CLIENT SIDE VALIDATION


Introduction to JavaScript - What is DHTML, JavaScript, basics, variables, string
manipulations, mathematical functions, statements, operators, arrays, functions. Objects in
JavaScript - Data and objects in JavaScript, regular expressions, exception handling. DHTML
with JavaScript - Data validation, opening a new window, messages and confirmations, the
status bar, different frames, rollover buttons, moving images

Introduction

 JavaScript is an Object-oriented Computer Programming Language.


 It is an Interpreted programming or script language from Netscape.
 The scripting languages are easier and faster to code.
 Its first appearance was in Netscape 2.0 in 1995 with the name 'LiveScript'.

Features of JavaScript

 JavaScript is an open source scripting language.


 It is lightweight.
 It creates network-centric applications.
 It is platform independent.
 It validates form data.
 It reduces server load.

Advantages of JavaScript

 JavaScript saves server traffic.


 It performs the operations very fast.
 It is simple to learn and implement.
 It is versatile.
 JavaScript pages are executed on the client side.
 JavaScript extends its functionality to the web pages.
Disadvantages of JavaScript

 JavaScript cannot be used for networking applications.


 It doesn't have any multithreading or multiprocessor capabilities.
 It has security issues being a client-side scripting language.

 gadgets such as calculators, clocks etc.


 It enables interaction within a web page.
 It is affected by the processing speed of the user's computer.
Operation of Client-Side Scripting

In the above diagram,


 The user requests a web page from the server.
 The server finds the page and sends it to the user.
 The page is displayed on the browser with any scripts running during or after the display.
 Client-Side scripting is used to make web page changes after they arrive at the browser.
 These scripts rely on the user's computer. If the computer is slow, then they may run slow.
 These scripts may not run at all if the browser does not understand the scripting language.
2. Server-Side Scripting
 Server-Side Scripting is used in web development.
 The server-side environment runs a scripting language which is called a web server.
 Server-Side Scripting is used to provide interactive web sites.
 It is different from Client-Side Scripting where the scripts are run by viewing the web
browser, usually in JavaScript.
 It is used for allowing the users to have individual accounts and providing data from
databases.
 It allows a level of privacy, personalization and provision of information that is very useful.
 It includes ASP.NET and PHP.
 It does not rely on the user having specific browser or plug-in.
 It is affected by the processing speed of the host server.
Operation of Server-Side Scripting

In the above diagram,


 The client requests a web page from the server.
 The script in the page is interpreted by the server, creating or changing the page content to
suit the user (client) and the passing data around.
 The page in its final form is sent to the user(client) and then cannot be changed using Server-
Side Scripting.
 Server-Side Scripting tends to be used for allowing the users to have individual accounts and
provides data from the databases.
 These scripts are never seen by the user.
 Server-Side script runs on the server and generate results which are sent to the user.
 Running all the scripts puts a lot of load onto a server but not on the user's system.

DHTML :

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.

The DHTML application was introduced by Microsoft with the release of the 4 th version of IE
(Internet Explorer) in 1997.
Components of Dynamic HTML

DHTML consists of the following four components or languages:

o HTML 4.0
o CSS
o JavaScript
o DOM.

HTML 4.0

HTML is a client-side markup language, which is a core component of the DHTML. It defines
the structure of a web page with various defined basic elements or tags.

CSS

CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.

JavaScript

JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell
the browser for performing an action.

DOM

DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all
elements in HTML.

Uses of DHTML

Following are the uses of DHTML (Dynamic HTML):

o It is used for designing the animated and interactive web pages that are developed in
real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their content
automatically.

Features of DHTML

Following are the various characteristics or features of DHTML (Dynamic HTML):

o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
o It provides the facility for using the events, methods, and properties. And, also provides
the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or web pages.
o With the help of DHTML, users can easily change the tags and their properties.

Difference between HTML and DHTML

Following table describes the differences between HTML and DHTML:

HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup


language)

1. HTML is simply a markup language. 1. DHTML is not a language, but it is a set of


technologies of web development.

2. It is used for developing and creating web 2. It is used for creating and designing the animated
pages. and interactive web sites or pages.
3. This markup language creates static web 3. This concept creates dynamic web pages.
pages.

4. It does not contain any server-side scripting 4. It may contain the code of server-side scripting.
code.

5. The files of HTML are stored with the .html 5. The files of DHTML are stored with the .dhtm
or .htm extension in a system. extension in a system.

6. A simple page which is created by a user 6. A page which is created by a user using the
without using the scripts or styles called as an HTML, CSS, DOM, and JavaScript technologies
HTML page. called a DHTML page.

7. This markup language does not need 7. This concept needs database connectivity because
database connectivity. it interacts with users.

o The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.

DHTML JavaScript

JavaScript can be included in HTML pages, which creates the content of the page as dynamic.
We can easily type the JavaScript code within the <head> or <body> tag of a HTML page. If
we want to add the external source file of JavaScript, we can easily add using the <src>
attribute.

Following are the various examples, which describes how to use the JavaScript technology
with the DHTML:

Document.write() Method

The document.write() method of JavaScript, writes the output to a web page.

Example 1: The following example simply uses the document.write() method of JavaScript
in the DHTML. In this example, we type the JavaScript code in the <body> tag.
1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>
13. Output:

JavaScript Variables

 JavaScript uses variables which can be thought of as Named Containers.


 Variables are declared with the 'var' keyword.

Example:
var a;
var b;

 Variable names are case sensitive.


 You can declare multiple variables with the same 'var' keyword.

Example: var a, b;
Variable initialization

Example : Variable initialization

var a = 10;
var b = 20;

Variable Scope

1. Global Variable

 Declaring a variable outside the function makes it a Global Variable.


 Variable is accessed everywhere in the document.
Example : Simple Program on Global Variable

<html>
<head>
<script type = "text/javascript">
count = 5; //Global variable
var a = 4; //Global variable
function funccount() // Function Declaration
{
count+=5; // Local variable
a+=4;
document.write("<b>Inside function Global Count: </b>"+count+"<br>");
document.write("<b>Inside function Global A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<b>Outside function Global Count: </b>"+count+"<br>");
document.write("<b>Outside function Global A: </b>"+a+"<br>");
funccount();
</script>
</body>
</html>

Output:

Outside function Global Count: 5


Outside function Global A: 4
Inside function Global Count: 10
Inside function Global A: 8

2. Local Variable

 A variable declared within a function is called as Local Variable.


 It can be accessed only within the function.
Example : Simple Program on Local Variable

<html>
<head>
<script type="text/javascript">
function funccount(a) // Function with Argument
{
var count=5; // Local variable
count+=2;
document.write("<b>Inside Count: </b>"+count+"<br>");
a+=3;
document.write("<b>Inside A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var a=3, count = 0;
funccount(a);
document.write("<b>Outside Count: </b>"+count+"<br>");
document.write("<b>Outside A: </b> "+a+"<br>");
</script>
</body>
</html>

Output:

Inside Count: 7
Inside A: 6
Outside Count: 0
Outside A: 3
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";

Let's see the simple example of creating string literal.

1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>

Output:

This is string literal


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.

Let's see the example of creating string in JavaScript by new keyword.

1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>

Output:

hello javascript string

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 combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching
a character from the last position.

search() It searches a specified regular expression in a given string and returns its
position if a match occurs.

match() It searches a specified regular expression in a given string and returns that
regular expression if a match occurs.

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

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.

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.

1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>

Output:

2) JavaScript String concat(str) Method

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

1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>

Output:

javascript concat example


3) JavaScript String indexOf(str) Method

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

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>

Output:

11

4) JavaScript String lastIndexOf(str) Method

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

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>

Output:

16

5) JavaScript String toLowerCase() Method

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

1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method

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

1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method

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

1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>

Output:

cde
8) JavaScript String trim() Method

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

1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>

Output:

javascript trim
9) JavaScript String split() Method
1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </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:

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

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


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

~ 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

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

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. }
Flowchart of JavaScript If statement

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


1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>

Output of the above example


value of a is greater than 10

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. }
Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </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.

1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }

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

1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10. document.write("a is equal to 20");
11. }
12. else{
13. document.write("a is not equal to 10, 15 or 20");
14. }
15. </script>

Output of the above example


a is equal to 20

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.

1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. break;
8. ......
9.
10. default:
11. code to be executed if above values are not matched;
12. }
Let’s see the simple example of switch statement in javascript.

1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
9. result="B Grade";
10. break;
11. case 'C':
12. result="C Grade";
13. break;
14. default:
15. result="No Grade";
16. }
17. document.write(result);
18. </script>

Output of the above example


B Grade

1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result+=" A Grade";
7. case 'B':
8. result+=" B Grade";
9. case 'C':
10. result+=" C Grade";
11. default:
12. result+=" No Grade";
13. }
14. document.write(result);
15. </script>

Output of the above example


undefined B Grade C Grade No Grade

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.

1. for (initialization; condition; increment)


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

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

1. <script>
2. for (i=1; i<=5; i++)
3. {
4. document.write(i + "<br/>")
5. }
6. </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.

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

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

1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </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.

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

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

1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>

Output:

21
22
23
24
25

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.

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


2. //code to be executed
3. }

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.

1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>

JavaScript Function Arguments

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

1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>

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.

1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>

Output of the above example


hello javatpoint! How r u?

JavaScript Function Object

In JavaScript, the purpose of Function constructor is to create a new Function object. It


executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax

1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

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.

JavaScript Function Object Examples

Example 1

Let's see an example to display the sum of given numbers.

1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>

Output:

7
Example 2

Let's see an example to display the power of provided value.

1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Output:

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

tan() It returns the tangent of the given number.

tanh() It returns the hyperbolic tangent of the given number.

trunc() It returns an integer part of the given

Math.sqrt(n)

The JavaScript math.sqrt(n) method returns the square root of the given number.
1. Square Root of 17 is: <span id="p1"></span>
2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>

Output:

Square Root of 17 is: 4.123105625617661

Math.random()

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

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


2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>

Output:

Random Number is: 0.9304656527774167

Math.pow(m,n)

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

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


2. <script>
3. document.getElementById('p3').innerHTML=Math.pow(3,4);
4. </script>

Output:

3 to the power of 4 is: 81

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.

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


2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);
4. </script>

Output:

Floor of 4.6 is: 4

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.

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


2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>

Output:

Ceil of 4.6 is: 5

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.

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


2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>
Output:

Round of 4.3 is: 4


Round of 4.7 is: 5

Math.abs(n)

The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc.

1. Absolute value of -4 is: <span id="p8"></span>


2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>

Output:

Absolute value of -4 is: 4

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:

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

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

Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </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:

1. var arrayname=new Array();

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

Let's see the example of creating array directly.

1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </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.

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>

Output

Jai
Vijay
Smith

JavaScript Array Methods

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

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided
function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively


till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided
function conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies
the specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of
the first match.

isArray() It tests if the passed value ia an array.


join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of
the last match.

map() It calls the specified function for every array element and returns the new
array

of() It creates a new array from a variable number of arguments, holding any type
of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and reduces
initial) the array to a single value.

reduceRight() It executes a provided function for each value from right to left and reduces
the array to a single value.

some() It determines if any element of the array passes the test of the implemented
function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.
sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without affecting
the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the array.

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)

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}

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

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

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </scrip>
Output of the above example
102 Shyam Kumar 40000

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.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Output of the above example
101 Ravi 50000
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.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>

Output of the above example


103 Vimal Jaiswal 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.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 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.

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.

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

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

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.

getUTCDate() It returns the integer value between 1 and 31 that represents the day for the
specified date on the basis of universal time.

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

getUTCFullYears() It returns the integer value that represents the year on the basis of universal
time.

getUTCHours() It returns the integer value between 0 and 23 that represents the hours on the
basis of universal time.

getUTCMinutes() It returns the integer value between 0 and 59 that represents the minutes on
the basis of universal time.

getUTCMonth() It returns the integer value between 0 and 11 that represents the month on the
basis of universal time.

getUTCSeconds() It returns the integer value between 0 and 60 that represents the seconds on
the basis of universal time.

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

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

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

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

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

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

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

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

setUTCDate() It sets the day value for the specified date on the basis of universal time.

setUTCDay() It sets the particular day of the week on the basis of universal time.
setUTCFullYears() It sets the year value for the specified date on the basis of universal time.

setUTCHours() It sets the hour value for the specified date on the basis of universal time.

setUTCMilliseconds() It sets the millisecond value for the specified date on the basis of universal
time.

setUTCMinutes() It sets the minute value for the specified date on the basis of universal time.

setUTCMonth() It sets the month value for the specified date on the basis of universal time.

setUTCSeconds() It sets the second value for the specified date on the basis of universal time.

toDateString() It returns the date portion of a Date object.

toISOString() It returns the date in the form ISO format string.

toJSON() It returns a string representing the Date object. It also serializes the Date
object during JSON serialization.

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

toTimeString() It returns the time portion of a Date object.

toUTCString() It converts the specified date in the form of string using UTC time zone.

valueOf() It returns the primitive value of a Date object.


JavaScript Date Example

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

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


2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>

Output:

Current Date and Time: Mon Jun 05 2023 21:36:43 GMT+0530 (India Standard Time)

Let's see another code to print date/month/year.

1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>

Output:

Date is: 5/6/2023

JavaScript Current Time Example

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

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


2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>

Output:

Current Time: 21:36:43

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.

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


2. <script>
3. window.onload=function(){getTime();}
4. function getTime(){
5. var today=new Date();
6. var h=today.getHours();
7. var m=today.getMinutes();
8. var s=today.getSeconds();
9. // add a zero in front of numbers<10
10. m=checkTime(m);
11. s=checkTime(s);
12. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
13. setTimeout(function(){getTime()},1000);
14. }
15. //setInterval("getTime()",1000);//another way
16. function checkTime(i){
17. if (i<10){
18. i="0" + i;
19. }
20. return i;
21. }
22. </script>

Output:

Current Time:

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:

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

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.

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:
1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
try…catch example
1. <html>
2. <head> Exception Handling</br></head>
3. <body>
4. <script>
5. try{
6. var a= ["34","32","5","31","24","44","67"]; //a is an array
7. document.write(a); // displays elements of a
8. document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be i
nvoked
9. }catch(e){
10. alert("There is error which shows "+e.message); //Handling error
11. }
12. </script>
13. </body>
14. </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:
1. throw exception;
try…catch…throw syntax
1. try{
2. throw exception; // user can define their own exception
3. }
4. catch(error){
5. expression; } // code for handling exception.

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

throw example with try…catch


1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try {
6. throw new Error('This is the throw keyword'); //user-defined throw statement.
7. }
8. catch (e) {
9. document.write(e.message); // This will generate an error message
10. }
11. </script>
12. </body>
13. </html>
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:
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
8. expression; } //Executable code
try…catch…finally example
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try{
6. var a=2;
7. if(a==2)
8. document.write("ok");
9. }
10. catch(Error){
11. document.write("Error found"+e.message);
12. }
13. finally{
14. document.write("Value of a is 2 ");
15. }
16. </script>
17. </body>
18. </html>
{
DHTML with JavaScript - Data validation, opening a new window, messages and
confirmations, the status bar, different frames, rollover buttons, moving images
}

STUDY FROM XEROX OR CLASS NOTES

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy