Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Javascript Notes

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

Javascript Notes

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

JavaScript

Easy4us A Computer Language Institute


Prabhat Kumar (Katras)

Introduction
JavaScript is used to create client-side dynamic pages. JavaScript is an
object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The
JavaScript Translator (embedded in the browser) is responsible for translating
the JavaScript code for the web browser.
What is JavaScript?
JavaScript (js) is a light-weight object-oriented programming
language which is used by several websites for scripting the Web Pages. 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 Web Pages in the
Netscape Navigator browser. Since then, it has been adopted by all other
graphical web browsers. With JavaScript, users can build modern web
applications to interact directly without reloading the page every time. The
traditional website uses js to provide several forms of interactivity and
simplicity.
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.

Page 1
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

History of JavaScript: -
In 1993, Mosaic, the first popular web browser, came into existence.
In the year 1994, Netscape was founded by Marc Andreessen. He realized
that the web needed to become more dynamic. Thus, a 'glue language' was
believed to be provided to HTML to make web designing easy for designers
and part-time programmers. Consequently, in 1995, the company recruited
Brendan Eich intending to implement and embed Scheme programming
language to the browser. But, before Brendan could start, the company
merged with Sun Microsystems for adding Java into its Navigator so that it
could compete with Microsoft over the web technologies and platforms.
Now, two languages were there: Java and the scripting language. Further,
Netscape decided to give a similar name to the scripting language as Java's. It
led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first
code of Javascript named 'Mocha'. Later, the marketing team replaced the
name with 'LiveScript'. But, due to trademark reasons and certain other
reasons, in December 1995, the language was finally renamed to 'JavaScript'.
From then, JavaScript came into existence.
Application of JavaScript:-
JavaScript is used to create interactive websites. It is mainly used for:
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
 Displaying clocks etc.

JavaScript Example:-
<script>
document.write("Hello JavaScript by JavaScript");
</script>

External JavaScript file:-


We can create external JavaScript file and embed it in many html page. It
provides code reusability because single JavaScript file can be used in
several html pages. An external JavaScript file must be saved by .js
Page 2
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

extension. It is recommended to embed all JavaScript files into a single file. It


increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Easy4us in an alert
dialog box.
message.js
function msg(){
alert("Hello Easy4us ");
}

Let's include the JavaScript file into html page. It calls


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

Advantages of External JavaScript:-


There will be following benefits if a user creates an external javascript:
1. It helps in the reusability of code in more than one HTML file.
2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which
further reduces the page loading time.
4. It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location
of the js file.
Disadvantages of External JavaScript:-
Page 3
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

There are the following disadvantages of external files:-


1. The stealer may download the coder's code using the URL of the js file.
2. If two js files are dependent on one another, then a failure in one file
may affect the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js
code.
4. A tiny to a large change in the js code may cause unexpected results in
all its dependent files.
5. We need to check each file that depends on the commonly created
external javascript file.
6. If it is a few lines of code, then better to implement the internal
javascript code.
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.
Advantages of JavaScript comments
There are mainly two advantages of JavaScript comments.
1. To make code easy to understand: - It can be used to elaborate the
code so that end user can easily understand the code.
2. To avoid the unnecessary code: - It can also be used to avoid the code
being executed. Sometimes, we add the code to perform some action.
But after sometime, there may be need to disable the code. In such
case, it is better to use comments.
Types of JavaScript Comments: -
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment:-

Page 4
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

It is represented by double forward slashes (//). It can be used


before and after the statement.
Example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
Example of single-line comment i.e. added after the statement.
1. <html>
2. <head>
3. <script>
4. var a=10;
5. var b=20;
6. var c=a+b;//It adds values of a and b variable
7. document.write(c);//prints sum of 10 and 20
8. </script>
</head>
<body>
</body>
</html>
JavaScript Multi line Comment: -
It can be used to add single as well as multi line comments. So,
it is more convenient.
It is represented by forward slash with asterisk then
asterisk with forward slash.
For example:
/* your code here */
It can be used before, after and middle of the statement.
1. <html>
2. <head>
3. <script>
4. /* It is multi line comment.
5. It will not be displayed */
6. document.write("example of javascript multiline comment");
7. </script>
8. </head>
Page 5
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

9. <body>
</body>
</html>

JavaScript Variable
A JavaScript variable is simply a name of storage location. There are
two types of variables in JavaScript: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
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="Prabhat";
Incorrect JavaScript variables
1. var 123=30;
2. var *aa=320;

Example of JavaScript variable


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

JavaScript local variable: -


A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only. For example:
<html>
<head>
<script>

Page 6
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

function abc(){
var x=10;//local variable
}
</script>
</head>
<body>
</body>
</html>
Or,
<html>
<head>
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
</head>
<body>
</body>
</html>
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:
<html>
<head>
<script>
var data=200;//global variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

Page 7
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

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="Prabhat";//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. “Prabhat”
Number represents numeric values e.g. 100
Boolean represents Boolean value either true or false
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

Page 8
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

RegExp represents regular expression

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


Page 9
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

Page 10
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

Page 11
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.
if (expression){
//content to be evaluated
}
The simple example of if statement in javascript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

Page 12
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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
}
Example of if-else statement in JavaScript to find out the even or odd
number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript If...else if statement: -
It evaluates the content only if expression is true from several
expressions. The signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
The simple example of if else if statement in javascript.
<script>

Page 13
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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>

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.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);

Page 14
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</script>
The behavior of switch statement in JavaScript.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
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
}
Example of for loop in javascript.
<script>
for (i=1; i<=5; i++)

Page 15
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

{
document.write(i + "<br/>")
}
</script>
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.
while (condition)
{
//code to be executed
}
Example of while loop in javascript.
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

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);
Example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

Page 16
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Function Example: -
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"/>
JavaScript Function Arguments: -
We can call function by passing arguments. Let’s see the example of
function that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}

Page 17
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value: -
We can call function that returns a value and use it in our program.
Example of function that returns value.
<script>
function getInfo(){
return "hello Easy4us! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
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
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.

Page 18
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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
Example to display the sum of given numbers.
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>
Example 2
Let's see an example to display the power of provided value.
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
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:
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:1,name:"Shyam Kumar",salary:40000}

Page 19
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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


</script>
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.
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>
3) By using an Object constructor
Here, we 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,"Prabhat Modi",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Output of the above example: -
103 Prabhat Modi 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;

Page 20
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Rahul Modi",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
JavaScript Object Methods
The various methods of Object are as follows:
S. Methods Description
No

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.

Page 21
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

7 Object.getOwnProperty This method returns a property descriptor for the specified


Descriptor() property of the specified object.

8 Object.getOwnProperty This method returns all own property descriptors of a given


Descriptors() object.

9 Object.getOwnProperty This method returns an array of all properties (enumerable


Names() or not) found.

10 Object.getOwnPropertyS This method returns an array of all own symbol key


ymbols() 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.preventExtension This method is used to prevent any extensions of an object.


s()

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.

Page 22
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

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).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Prabhat","Rahul","Kumar sanu"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
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] = "Prabhat";
emp[1] = "Kumar Sanu";
emp[2] = "Jyoti";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Page 23
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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","Viru","Sonu");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
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.

Page 24
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.

Page 25
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

reverse() It reverses the elements of given array.

reduce(function It executes a provided function for each value from left to right and reduces the
,initial) 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 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: -

Page 26
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

The string literal is created using double quotes. The syntax of creating
string using string literal is given below:
var stringname="string value";
Example of creating string literal.
<script>
var str="This is string literal";
document.write(str);
</script>
2) By string object (using new keyword): -
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Let's see the example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

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.

Page 27
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.

toLocaleLowe It converts the given string into lowercase letter on the basis of host’s current
rCase() locale.

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

toLocaleUpper It converts the given string into uppercase letter on the basis of host’s current
Case() 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.
<script>
var str="javascript";
document.write(str.charAt(2));

Page 28
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</script>
2) JavaScript String concat (str) Method
The JavaScript String concat (str) method concatenates or joins two
strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
3) JavaScript String indexOf (str) Method
The JavaScript String indexOf (str) method returns the index position
of the given string.
<script>
var s1="javascript from Easy4us indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
4) JavaScript String lastIndexOf (str) Method
The JavaScript String lastIndexOf (str) method returns the last index
position of the given string.
<script>
var s1="javascript from Easy4us indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
5) JavaScript String toLowerCase () Method
The JavaScript String toLowerCase () method returns the given string
in lowercase letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
6) JavaScript String toUpperCase () Method
The JavaScript String toUpperCase () method returns the given string
in uppercase letters.
Page 29
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
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.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
8) JavaScript String trim () Method
The JavaScript String trim () method removes leading and trailing
whitespaces from the string.
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
9) JavaScript String split () Method
<script>
var str="This is Easy4us website";
document.write (str.split (" ")); //splits the given string.
</script>

JavaScript Date Object: -


The JavaScript date object can be used to get year, month and day.
We can display a timer on the webpage by the help of JavaScript date object.
We can use different Date constructors to create date object. It provides
methods to get and set day, month, year, hour, minute and seconds.

Constructor: -
We can use 4 variant of Date constructor to create date object.
1. Date()
Page 30
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.

Page 31
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.

Page 32
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.

Page 33
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
Let's see another code to print date/month/year.
1. <script>
var date=new Date();
2. var day=date.getDate();
3. var month=date.getMonth()+1;
4. var year=date.getFullYear();
5. document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>

JavaScript Current Time Example


Let's see the simple example to print current time of system.
Current Time: <span id="txt"></span>
1. <script>
2. var today=new Date();
3. var h=today.getHours();
4. var m=today.getMinutes();
5. var s=today.getSeconds();
6. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
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.
Current Time: <span id="txt"></span>
<script>
window.onload=function(){getTime();}
function getTime(){
Page 34
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

var today=new Date();


var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
}
//setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
}
return i;
}
</script>

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.

Page 35
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

Math.sqrt (n): -

Page 36
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

The JavaScript math.sqrt (n) method returns the square root of the
given number.
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
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>

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);
</script>
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.
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
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.
Ceil of 4.6 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>
Math.round (n)

Page 37
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.
Round of 4.3 is: <span id="p6"></span><br>
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
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.
Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>

JavaScript Number Object: -


The JavaScript number object enables you to represent a numeric
value. It may be integer or floating-point. JavaScript number object follows
IEEE standard to represent the floating-point numbers.
By the help of Number () constructor, you can create number object in
JavaScript. For example:
1. var n=new Number(value);
If value can't be converted to number, it returns NaN (Not a Number) that can
be checked by isNaN () method.
You can direct assign a number to a variable also. For example:
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object

JavaScript Number Constants: -


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

Page 38
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

MIN_VALUE Returns the largest minimum value.

MAX_VALUE Returns the largest maximum value.

POSITIVE_INFINITY Returns positive infinity, overflow value.

NEGATIVE_INFINITY Returns negative infinity, overflow value.

NaN Represents "Not a Number" value.

JavaScript Number Methods: -


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

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

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

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

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

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

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

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

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

JavaScript Boolean: -
JavaScript Boolean is an object that represents value in two
states: true or false.
We can create the JavaScript Boolean object by Boolean () constructor
as given below.
Boolean b=new Boolean(value);

Page 39
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

The default value of JavaScript Boolean object is false.


JavaScript Boolean Example: -
1. <script>
2. document.write(10<20);//true
3. document.write(10<5);//false
</script>
JavaScript Boolean Properties
Property Description

Constructor Returns the reference of Boolean function that created Boolean object.

prototype Enables us to add properties and methods in Boolean prototype.

JavaScript Boolean Methods


Method Description

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

toString() Converts Boolean into String.

valueOf() Converts other type into Boolean.

Browser Object Model


The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions
of window by specifying window or directly. For example:
window.alert("hello Easy4us");
is same as:
1. alert("hello Easy4us");
We can use a lot of properties (other objects) defined underneath the window
object like document, history, screen, navigator, location, innerHeight,
innerWidth,………..

Page 40
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Window Object: -
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
The window object represents a window in browser. An object of
window is created automatically by the browser.
Window is the object of browser, it is not the object of javascript.
The javascript objects are string, array, date etc.
Methods of window object: -
The important methods of window object are as follows: -
Method Description

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

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

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

open() Opens the new window.

close() Closes the current window.

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

Example of alert () in javascript: -


It displays alert dialog box. It has message and ok button.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>

Page 41
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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


Example of confirm () in javascript: -
It displays the confirm dialog box. It has message with ok and
cancel buttons.
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
Example of prompt() in javascript: -
It displays prompt dialog box for input. It has message and
textfield.
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" value="click" onclick="msg()"/>
Example of open() in javascript: -
It displays the content in a new window.
<script type="text/javascript">
function msg(){
open("http://www.Easy4us.com");
}
</script>
<input type="button" value="Easy4us" onclick="msg()"/>
Example of setTimeout() in javascript: -
It performs its task after the given milliseconds.
<script type="text/javascript">

Page 42
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

function msg(){
setTimeout(
function(){
alert("Welcome to Easy4us after 2 seconds")
},2000);

}
</script>
<input type="button" value="click" onclick="msg()"/>
JavaScript History Object: -
1.
History Object
2.
Properties of History Object
3.
Methods of History Object
4.
Example of History Object
The JavaScript history object represents an array of URLs visited by
the user. By using this object, you can load previous, forward or any
particular page.
The history object is the window property, so it can be accessed by:
window.history
Or,
History
Property of JavaScript history object:
There are only 1 property of history object.
No. Property Description

1 length Returns the length of the history URLs.

Methods of JavaScript history object: -


There are only 3 methods of history object.
No. Method Description

1 forward() Loads the next page.

2 back() Loads the previous page.

Page 43
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

3 go() Loads the given page number.

Example of history object: -


Let’s see the different usage of history object.
history.back();//for previous page
history.forward();//for next page
history.go(2);//for next 2nd page
history.go(-2);//for previous 2nd page

JavaScript Navigator Object


1. Navigator Object
2. Properties of Navigator Object
3. Methods of Navigator Object
4. Example of Navigator Object
The JavaScript navigator object is used for browser detection. It can
be used to get browser information such as appName, appCodeName,
userAgent etc.
The navigator object is the window property, so it can be accessed by:
window.navigator
Or,
navigator
Property of JavaScript navigator object: -
There are many properties of navigator object that returns information of the
browser.
N Property Description
o
.

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false

Page 44
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

5 userAgent returns the user agent

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

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

8 plugins Returns the plugins. It is supported in Netscape and Firefox only.

9 systemLanguage Returns the system language. It is supported in IE only.

10 mimeTypes[] Returns the array of mime type. It is supported in Netscape and


Firefox only.

11 platform Returns the platform e.g. Win32.

12 online Returns true if browser is online otherwise false.

Methods of JavaScript navigator object


The methods of navigator object are given below.
No. Method Description

1 javaEnabled() Checks if java is enabled.

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

Example of navigator object


Let’s see the different usage of history object.
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>
Output:-

Page 45
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true

JavaScript Screen Object: -


1. Screen Object
2. Properties of Screen Object
3. Methods of Screen Object
4. Example of Screen Object
The JavaScript screen object holds information of browser screen. It can be
used to display screen width, height, colorDepth, pixelDepth etc.
The navigator object is the window property, so it can be accessed by:
window.screen
Or,
1. screen
Property of JavaScript Screen Object: -
There are many properties of screen object that returns information of the
browser.
No. Property Description

1 Width returns the width of the screen

2 Height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth Returns the pixel depth.

Page 46
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Example of JavaScript Screen Object: -


Let’s see the different usage of screen object.
1. <script>
2. document.writeln("<br/>screen.width: "+screen.width);
3. document.writeln("<br/>screen.height: "+screen.height);
4. document.writeln("<br/>screen.availWidth: "+screen.availWidth);
5. document.writeln("<br/>screen.availHeight: "+screen.availHeight);
6. document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
7. document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>
Output:-
screen.width: 1366
screen.height: 768
screen.availWidth: 1366
screen.availHeight: 728
screen.colorDepth: 24
screen.pixelDepth: 24
Document Object Model: -
1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object
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
Is same as
Document
Properties of document object
Let's see the properties of document object that can be accessed and
modified by the document object.

Page 47
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Methods of document object: -


We can access and change the contents of document by its methods.
The important methods of document object are as follows:
Method Description

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

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

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

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

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

Page 48
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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, which 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>
Javascript - document.getElementsByName ()
method: -
1. getElementsByName() method
2. Example of getElementsByName()
The document.getElementsByName () method returns all the element of
specified name.
The syntax of the getElementsByName () method is given below:
document.getElementsByName("name")
Here, name is required.
Example of document.getElementsByName () method
In this example, we going to count total number of genders. Here,
we are using getElementsByName () method to get all the genders.

Page 49
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Javascript - document.getElementsByTagName ()
method:
1. getElementsByTagName() method
2. Example of getElementsByTagName()
The document.getElementsByTagName () method returns all the element
of specified tag name.
The syntax of the getElementsByTagName () method is given below:
document.getElementsByTagName("name")
Here, name is required.
Example of document.getElementsByTagName () method
In this example, we going to count total number of paragraphs used in the
document. To do this, we have called the document.getElementsByTagName ("p")
method that returns the total paragraphs.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName() met
hod.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>

Page 50
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Another example of document.getElementsByTagName ()


method: -
In this example, we going to count total number of h2 and h3 tags
used in the document.
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>

Javascript – innerHTML: -
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the
html document.
It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
Example of innerHTML property
In this example, we are going to create the html form when user clicks on the
button.
In this example, we are dynamically writing the html form inside the
div name having the id mylocation. We are identifing this position by calling
the document.getElementById () method.
<html>

Page 51
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<head>
<title>DOM innerHTML Property</title>
</head>
<body style="text-align: center">
<h1 style="color:green">
Easy4us
</h1>
<h2>
DOM innerHTML Property
</h2>
<p id="p">Easy4us</p>
<button onclick="Easy4us()">Click me!</button>
<script>
function Easy4us() {
document.getElementById("p").innerHTML =
"A computer Language Institue.";
}
</script>
</body>
</html>
Example using innerHTML
<html>
<head>
</head>
<body>
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Prabhat';
}
</script>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
</body>
</html>
Output: - when we click change text button output will be changed

Page 52
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as
writing the validation message, password strength etc.
Javascript innerText Example: -
In this example, we are going to display the password strength when
releases the key after press.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
Output: -

JavaScript Form Validation


1. JavaScript form validation
2. Example of JavaScript validation
3. JavaScript email validation

Page 53
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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>
<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>
If we both field is Empty: -

Page 54
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Error will be displayed: -

If we insert only name field: -

Error will be display: -

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){
return 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">

Page 55
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</form>

When password is not matched: -

JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are
using isNaN() function.
<script>
function validate(){
var num=document.myform.num.value;
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 validation with image

Page 56
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Let’s see an interactive JavaScript form validation example that


displays correct and incorrect image if input is correct or incorrect.
<script>
function validate(){
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;
if(name.length<1){
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}else{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6){
document.getElementById("passwordloc").innerHTML= " <img src='unchecked.gif'/> P
assword must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}
return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>

Output:

Enter Name:

Page 57
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Enter Password:

register

JavaScript email validation: -


We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
o Email id must contain the @ and. character
o There must be at least one character before and after the @.
o There must be at least two characters after. (dot).
Let's see the simple example to validate the email field.
<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>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>

JavaScript Classes: -
In JavaScript, classes are the special type of functions. We can
define the class just like function declarations and function expressions.
The JavaScript class contains various class members within a body
including methods or constructor. The class is executed in strict mode. So,
the code containing the silent error or mistake throws an error.
The class syntax contains two components:
o Class declarations

Page 58
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

o Class expressions
Class Declarations: -
A class can be defined by using a class declaration. A class
keyword is used to declare a class with any particular name. According to
JavaScript naming conventions, the name of the class always starts with an
uppercase letter.
Class Declarations Example: -
Let's see a simple example of declaring the class.
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(this.id+" "+this.name+"<br>")
}
}
//passing object to a variable
var e1=new Employee(101,"Martin Roy");
var e2=new Employee(102,"Duke William");
e1.detail(); //calling method
e2.detail();
</script>
Output:
101 Martin Roy
102 Duke William
Class Declarations Example: Hoisting: -
Unlike function declaration, the class declaration is not a part of
JavaScript hoisting. So, it is required to declare the class before invoking it.
Let's see an example.
Page 59
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<script>
//Here, we are invoking the class before declaring it.
var e1=new Employee(101,"Martin Roy");
var e2=new Employee(102,"Duke William");
e1.detail(); //calling method
e2.detail();
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
detail()
{
document.writeln(this.id+" "+this.name+"<br>")
}
}
</script>
Class Declarations Example: Re-declaring Class: -
A class can be declared once only. If we try to declare class
more than one time, it throws an error.
Let's see an example.
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
detail()
{
document.writeln(this.id+" "+this.name+"<br>")

Page 60
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

}
}
//passing object to a variable
var e1=new Employee(101,"Martin Roy");
var e2=new Employee(102,"Duke William");
e1.detail(); //calling method
e2.detail();
//Re-declaring class
class Employee
{
}
</script>
Class expressions
Another way to define a class is by using a class expression.
Here, it is not mandatory to assign the name of the class. So, the class
expression can be named or unnamed. The class expression allows us to fetch
the class name. However, this will not be possible with class declaration.
Unnamed Class Expression: -
The class can be expressed without assigning any name to it.
Let's see an example.
<script>
var emp = class {
constructor(id, name) {
this.id = id;
this.name = name;
}
};
document.writeln(emp.name);
</script>
Output:
emp
Class Expression Example: Re-declaring Class: -
Unlike class declaration, the class expression allows us to re-
declare the same class. So, if we try to declare the class more than one time, it
throws an error.
<script>
//Declaring class
Page 61
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

var emp=class
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(this.id+" "+this.name+"<br>")
}
}
//passing object to a variable
var e1=new emp(101,"Martin Roy");
var e2=new emp(102,"Duke William");
e1.detail(); //calling method
e2.detail();

//Re-declaring class
var emp=class
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
detail()
{
document.writeln(this.id+" "+this.name+"<br>")
}
}
//passing object to a variable
var e1=new emp(103,"James Bella");
var e2=new emp(104,"Nick Johnson");
e1.detail(); //calling method

Page 62
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

e2.detail();
</script>
Output:
101 Martin Roy
102 Duke William
103 James Bella
104 Nick Johnson
Named Class Expression Example: -
We can express the class with the particular name. Here, the
scope of the class name is up to the class body. The class is retrieved using
class.name property.
<script>
var emp = class Employee {
constructor(id, name) {
this.id = id;
this.name = name;
}
};
document.writeln(emp.name);
/*document.writeln(Employee.name);
Error occurs on console:
"ReferenceError: Employee is not defined
*/
</script>
Output:
Employee

JavaScript Prototype Object: -


JavaScript is a prototype-based language that facilitates the
objects to acquire properties and features from one another. Here, each object
contains a prototype object.
In JavaScript, whenever a function is created
the prototype property is added to that function automatically. This property
is a prototype object that holds a constructor property.
Syntax:
1. ClassName.prototype.methodName
What is the requirement of a prototype object?

Page 63
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Whenever an object is created in JavaScript, its corresponding


functions are loaded into memory. So, a new copy of the function is created
on each object creation.
In a prototype-based approach, all the objects share the
same function. This ignores the requirement of creating a new copy of
function for each object. Thus, the functions are loaded once into the
memory.
Prototype Chaining: -
In JavaScript, each object contains a prototype object that
acquires properties and methods from it. Again an object's prototype object
may contain a prototype object that also acquires properties and methods, and
so on. It can be seen as prototype chaining.
JavaScript Prototype Object Example 1: -
Let's see an example to add a new method to the constructor function.
<script>
function Employee(firstName,lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
Employee.prototype.fullName=function()
{
return this.firstName+" "+this.lastName;
}
var employee1=new Employee("Martin","Roy");
var employee2=new Employee("Duke", "William");
document.writeln(employee1.fullName()+"<br>");
document.writeln(employee2.fullName());
</script>
Output:
Martin Roy
Duke William
Example 2
Let's see an example to add a new property to the constructor function.
<script>
function Employee(firstName,lastName)

Page 64
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

{
this.firstName=firstName;
this.lastName=lastName;
}
Employee.prototype.company="Easy4us"
var employee1=new Employee("Martin","Roy");
var employee2=new Employee("Duke", "William");
document.writeln(employee1.firstName+" "+employee1.lastName+" "+employee1.company
+"<br>");
document.writeln(employee2.firstName+" "+employee2.lastName+" "+employee2.company
);
</script>
Output:
Martin Roy Easy4us
Duke William Easy4us

JavaScript Constructor Method


A JavaScript constructor method is a special type of method which is used to
initialize and create an object. It is called when memory is allocated for an
object.
Points to remember: -
o The constructor keyword is used to declare a constructor method.
o The class can contain one constructor method only.
o JavaScript allows us to use parent class constructor through super keyword.
Constructor Method Example: -
Let's see a simple example of a constructor method.
1. <script>
2. class Employee {
3. constructor() {
4. this.id=101;
5. this.name = "Martin Roy";
6. }
7. }
8. var emp = new Employee();
9. document.writeln(emp.id+" "+emp.name);
</script>
Output:
101 Martin Roy

Page 65
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Constructor Method Example: super keyword: -


The super keyword is used to call the parent class constructor.
Let's see an example.
<script>
class CompanyName
{
constructor()
{
this.company="Easy4us";
}
}
class Employee extends CompanyName {
constructor(id,name) {
super();
this.id=id;
this.name=name;
}
}
var emp = new Employee(1,"John");
document.writeln(emp.id+" "+emp.name+" "+emp.company);
</script>
Output: John Easy4us

Note - If we didn't specify any constructor method, JavaScript use default constructor method.

JavaScript Static Method: -


The JavaScript provides Static methods that belong to the class
instead of an instance of that class. So, an instance is not required to call the
Static method. These methods are called directly on the class itself.
Points to remember: -
o The Static keyword is used to declare a Static method.
o The Static method can be of any name.
o A class can contain more than one Static method.

Page 66
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

o If we declare more than one Static method with a similar name, the
JavaScript always invokes the last one.
o The Static method can be used to create utility functions.
o We can use this keyword to call a Static method within another Static
method.
o We cannot use this keyword directly to call a Static method within the
non-Static method. In such case, we can call the Static method either
using the class name or as the property of the constructor.
JavaScript Static Method Example 1: -
Let's see a simple example of a Static method.
1. <script>
2. class Test
3. {
4. Static display()
5. {
6. return "Static method is invoked"
7. }
8. }
9. document.writeln(Test.display());
</script>
Output:
Static method is invoked
Example 2: -
Let’s see an example to invoke more than one Static method.
<script>
class Test
{
Static display1()
{
return "Static method is invoked"
}
Static display2()
{
return "Static method is invoked again"
}
}
document.writeln(Test.display1()+"<br>");

Page 67
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

document.writeln(Test.display2());
</script>
Output:
Static method is invoked
Static method is invoked again
Example 3: -
Let's see an example to invoke more than one Static method with
similar names.
<script>
class Test
{
Static display()
{
return "Static method is invoked"
}
Static display()
{
return "Static method is invoked again"
}
}
document.writeln(Test.display());
</script>
Output:
Static method is invoked again
Example 4: -
Let's see an example to invoke a Static method within the constructor.
<script>
class Test {
constructor() {
document.writeln(Test.display()+"<br>");
document.writeln(this.constructor.display());
}

Static display() {
return "Static method is invoked"
}
}
var t=new Test();

Page 68
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</script>
Output:
Static method is invoked
Static method is invoked
Example 5: -
Let's see an example to invoke a Static method within the non-
Static method.
<script>
class Test {
Static display() {
return "Static method is invoked"
}

show() {
document.writeln(Test.display()+"<br>");
}
}
var t=new Test();
t.show();
</script>
Output:
Static method is invoked
JavaScript Encapsulation: -
JavaScript Encapsulation is a process of binding the data (i.e.
variables) with a functions acting on that data. This allows us to control the
data and validate it. To achieve an encapsulation in JavaScript: -
o Use var keyword to make data members private.
o Use setter methods to set the data and getter methods to get that data.
The encapsulation allows us to handle an object using the following
properties:
Read/Write - Here, we use setter methods to write the data and getter
methods read that data.
Read Only - In this case, we use getter methods only.
Write Only - In this case, we use setter methods only.

Page 69
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

JavaScript Encapsulation Example: -


Let us look at a simple example of encapsulation that contains
two data members with its setter and getter methods.
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
{
this.name=name;
}

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

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

Page 70
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

JavaScript Encapsulation Example: Validate: -


In this example, we validate the marks of the student.
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
{
this.name=name;
}
getMarks()
{
return this.marks;
}
setMarks(marks)
{
if(marks<0||marks>100)
{
alert("Invalid Marks");
}
else
{
this.marks=marks;
}
}
}
var stud=new Student();
stud.setName("John");
stud.setMarks(110);//alert() invokes
document.writeln(stud.getName()+" "+stud.getMarks());

Page 71
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</script>
Output:
John undefined
JavaScript Encapsulation Example: Prototype-based approach
Here, we perform prototype-based encapsulation.
<script>
function Student(name,marks)
{
var s_name=name;
var s_marks=marks;
Object.defineProperty(this,"name",{
get:function()
{
return s_name;
},
set:function(s_name)
{
this.s_name=s_name;
}
});
Object.defineProperty(this,"marks",{
get:function()
{
return s_marks;
},
set:function(s_marks)
{
this.s_marks=s_marks;
}
});
}
var stud=new Student("John",80);
document.writeln(stud.name+" "+stud.marks);
</script>
Output: John 80

Page 72
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

JavaScript Inheritance
The JavaScript inheritance is a mechanism that allows us to
create new classes on the basis of already existing classes. It provides
flexibility to the child class to reuse the methods and variables of a parent
class.
The JavaScript extends keyword is used to create a child class on the
basis of a parent class. It facilitates child class to acquire all the properties
and behavior of its parent class.
Points to remember
o It maintains an IS-A relationship.
o The extends keyword is used in class expressions or class declarations.
o Using extends keyword, we can acquire all the properties and behavior
of the inbuilt object as well as custom classes.
o We can also use a prototype-based approach to achieve inheritance.
JavaScript extends Example: inbuilt object
In this example, we extends Date object to display today's date.
1. <script>
2. class Moment extends Date {
3. constructor() {
4. super();
5. }}
6. var m=new Moment();
7. document.writeln("Current date:")
8. document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear());
</script>
Output:
Current date: 31-8-2018
Let's see one more example to display the year value from the given
date.
<script>
class Moment extends Date {
constructor(year) {
super(year);
}}
var m=new Moment("August 15, 1947 20:22:10");
document.writeln("Year value:")

Page 73
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

document.writeln(m.getFullYear());
</script>
Output:
Year value: 1947
JavaScript extends Example: Custom class: -
In this example, we declare sub-class that extends the properties of its
parent class.
<script>
class Bike
{
constructor()
{
this.company="Honda";
}
}
class Vehicle extends Bike {
constructor(name,price) {
super();
this.name=name;
this.price=price;
}
}
var v = new Vehicle("Shine","70000");
document.writeln(v.company+" "+v.name+" "+v.price);
</script>
Output: Honda Shine 70000
JavaScript extends Example: a Prototype-based approach: -
Here, we perform prototype-based inheritance. In this approach, there
is no need to use class and extends keywords.
<script>
//Constructor function
function Bike(company)
{
this.company=company;
}

Bike.prototype.getCompany=function()
{

Page 74
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

return this.company;
}
//Another constructor function
function Vehicle(name,price) {
this.name=name;
this.price=price;
}
var bike = new Bike("Honda");
Vehicle.prototype=bike; //Now Bike treats as a parent of Vehicle.
var vehicle=new Vehicle("Shine",70000);
document.writeln(vehicle.getCompany()+" "+vehicle.name+" "+vehicle.price);
</script>
Output: Honda Shine 70000
JavaScript Polymorphism: -
The polymorphism is a core concept of an object-oriented
paradigm that provides a way to perform a single action in different forms. It
provides an ability to call the same method on different JavaScript objects.
As JavaScript is not a type-safe language, we can pass any type of data
members with the methods.
JavaScript Polymorphism Example 1: -
Let's see an example where a child class object invokes the parent
class method.
<script>
class A
{
display()
{
document.writeln("A is invoked");
}
}
class B extends A
{
}
var b=new B();
b.display();
</script>
Output: A is invoked

Page 75
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Example 2: -
Let's see an example where a child and parent class contains the same
method. Here, the object of child class invokes both classes method.
<script>
class A
{
display()
{
document.writeln("A is invoked<br>");
}
}
class B extends A
{
display()
{
document.writeln("B is invoked");
}
}

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


a.forEach(function(msg)
{
msg.display();
});
</script>
Output:
A is invoked
B is invoked
Example 3: -
Let's see the same example with prototype-based approach.
<script>
function A()
{
}
A.prototype.display=function()
{
return "A is invoked";
}

Page 76
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

function B()
{
}
B.prototype=Object.create(A.prototype);
var a=[new A(), new B()]
a.forEach(function(msg)
{
document.writeln(msg.display()+"<br>");
});
<script>
Output:
A is invoked
B is invoked
JavaScript Abstraction: -
An abstraction is a way of hiding the implementation details and
showing only the functionality to the users. In other words, it ignores the
irrelevant details and shows only the required one.
Points to remember: -
o We cannot create an instance of Abstract Class.
o It reduces the duplication of code.
JavaScript Abstraction Example: -
Example 1: -
Let's check whether we can create an instance of Abstract class or not.
<script>
//Creating a constructor function
function Vehicle()
{
this.vehicleName= vehicleName;
throw new Error("You cannot create an instance of Abstract class");

}
Vehicle.prototype.display=function()
{
return this.vehicleName;
}
var vehicle=new Vehicle();
</script>
Page 77
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Example 2: -
Let's see an example to achieve abstraction.
<script>
//Creating a constructor function
function Vehicle()
{
this.vehicleName="vehicleName";
throw new Error("You cannot create an instance of Abstract Class");
}
Vehicle.prototype.display=function()
{
return "Vehicle is: "+this.vehicleName;
}
//Creating a constructor function
function Bike(vehicleName)
{
this.vehicleName=vehicleName;
}
//Creating object without using the function constructor
Bike.prototype=Object.create(Vehicle.prototype);
var bike=new Bike("Honda");
document.writeln(bike.display());
</script>
Output: Vehicle is: Honda
Example 3: -
In this example, we use instanceof operator to test whether the object
refers to the corresponding class.
<script>
//Creating a constructor function
function Vehicle()
{
this.vehicleName=vehicleName;
throw new Error("You cannot create an instance of Abstract class");
}
//Creating a constructor function
function Bike(vehicleName)
{
this.vehicleName=vehicleName;
Page 78
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

}
Bike.prototype=Object.create(Vehicle.prototype);
var bike=new Bike("Honda");
document.writeln(bike instanceof Vehicle);
document.writeln(bike instanceof Bike);
</script>
Output: true true

JavaScript Cookies: -
A cookie is an amount of information that persists between
a server-side and a client-side. A web browser stores this information at the
time of browsing.
A cookie contains the information as a string generally in the form of
a name-value pair separated by semi-colons. It maintains the state of a user
and remembers the user's information among all the web pages.
How Cookies Works?
o When a user sends a request to the server, then each of that request is
treated as a new request sent by the different user.
o So, to recognize the old user, we need to add the cookie with the
response from the server.
o browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is
added with that request automatically. Due to the cookie, the server
recognizes the users.

How to create a Cookie in JavaScript?


In JavaScript, we can create, read, update and delete a cookie by
using document.cookie property.
The following syntax is used to create a cookie:

Page 79
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

document.cookie="name=value";
JavaScript Cookie Example
Example 1
Let's see an example to set and get a cookie.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

Example 2
Here, we display the cookie's name-value pair separately.
<!DOCTYPE html>
<html>
<head>
</head>

Page 80
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>

</body>
</html>

Example 3: -
In this example, we provide choices of color and pass the
selected color value to the cookie. Now, cookie stores the last choice of a
user in a browser. So, on reloading the web page, the user's last choice will
be shown on the screen.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="color" onchange="display()">
<option value="Select Color">Select Color</option>
<option value="yellow">Yellow</option>

Page 81
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<option value="green">Green</option>
<option value="red">Red</option>
</select>
<script type="text/javascript">
function display()
{
var value = document.getElementById("color").value;
if (value != "Select Color")
{
document.bgColor = value;
document.cookie = "color=" + value;
}
}
window.onload = function ()
{
if (document.cookie.length != 0)
{
var array = document.cookie.split("=");
document.getElementById("color").value = array[1];
document.bgColor = array[1];
}
}
</script>
</body>
</html>

Cookie Attributes
JavaScript provides some optional attributes that enhance the functionality of cookies. Here,
is the list of some attributes with their description.

Attributes Description

expires It maintains the state of a cookie up to the specified date and time.

max-age It maintains the state of a cookie up to the specified time. Here, time is given in second

Page 82
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Path It expands the scope of the cookie to all the pages of a website.

domain It is used to specify the domain for which the cookie is valid.

Cookie expires attribute


The cookie expires attribute provides one of the ways to create a
persistent cookie. Here, a date and time are declared that represents the active
period of a cookie. Once the declared time is passed, a cookie is deleted
automatically.
Let's see an example of cookie expires attribute.
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin;expires=Sun, 20 Aug 2030 12:00:00 UTC";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

Page 83
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Cookie max-age attribute: -


The cookie max-age attribute provides another way to create a
persistent cookie. Here, time is declared in seconds. A cookie is valid up to
the declared time only.
Let's see an example of cookie max-age attribute.
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) + ";"
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Cookie path attribute: -
If a cookie is created for a webpage, by default, it is valid only
for the current directory and sub-directory. JavaScript provides a path
attribute to expand the scope of cookie up to all the pages of a website.
Cookie path attribute Example: -

Page 84
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

In this example, we use path attribute to enhance the visibility of


cookies up to all the pages. Here, you all just need to do is to maintain the
above directory structure and put the below program in all three web pages.
Now, the cookie is valid for each web page.
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) + ";path=/;"
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Cookie domain attribute: -
A JavaScript domain attribute specifies the domain for which the
cookie is valid. Let's suppose if we provide any domain name to the attribute
such like:
domain=easy4us.com
Here, the cookie is valid for the given domain and all its sub-domains.
However, if we provide any sub-domain to the attribute such like:

Page 85
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

omain=training.easy4us.com
Here, the cookie is valid only for the given sub-domain. So, it's a better
approach to provide domain name instead of sub-domain.
Cookie with multiple Name-Value pairs: -
In JavaScript, a cookie can contain only a single name-value pair.
However, to store more than one name-value pair, we can use the following
approach: -
o Serialize the custom object in a JSON string, parse it and then store in a
cookie.
o For each name-value pair, use a separate cookie.

Examples to Store Name-Value pair in a Cookie: -


Example 1: -
Let's see an example to check whether a cookie contains more
than one name-value pair.
<html>
<head>
</head>
<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
//Declaring 3 key-value pairs
var info="Name="+ document.getElementById("name").value+";Email="+document.ge
tElementById("email").value+";Course="+document.getElementById("course").value;
//Providing all 3 key-value pairs to a single cookie
document.cookie=info;
}

function getCookie()
{
if(document.cookie.length!=0)

Page 86
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

{
//Invoking key-value pair stored in a cookie
alert(document.cookie);
}
else
{
alert("Cookie not available")
}
}
</script>
</body>
</html>
However, if you click, Get Cookie without filling the form, the below dialog
box appears.
Example 2
Let's see an example to store different name-value pairs in a
cookie using JSON.
<html>
<head>
</head>
<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">

<script>
function setCookie()
{
var obj = {};//Creating custom object
obj.name = document.getElementById("name").value;
obj.email = document.getElementById("email").value;
obj.course = document.getElementById("course").value;

//Converting JavaScript object to JSON string


var jsonString = JSON.stringify(obj);

Page 87
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

document.cookie = jsonString;
}
function getCookie()
{
if( document.cookie.length!=0)
{
//Parsing JSON string to JSON object
var obj = JSON.parse(document.cookie);

alert("Name="+obj.name+" "+"Email="+obj.email+" "+"Course="+obj.course);


}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Here, we can see that all the stored name-value pairs are displayed.
Example 3: -
Let's see an example to store each name-value pair in a different cookie.
<html>
<head>
</head>
<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie = "name=" + document.getElementById("name").value;
document.cookie = "email=" + document.getElementById("email").value;
document.cookie = "course=" + document.getElementById("course").value;
}

Page 88
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

function getCookie()
{
if (document.cookie.length != 0)
{
alert("Name="+document.getElementById("name").value+" Email="+document.getElementByI
d("email").value+" Course="+document.getElementById("course").value);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Output:-

On clicking Get Cookie button, the below dialog box appears.

Deleting a Cookie in JavaScript: -


In the previous section, we learned the different ways to set and update
a cookie in JavaScript. Apart from that, JavaScript also allows us to delete a
cookie. Here, we see all the possible ways to delete a cookie.
Different ways to delete a Cookie
These are the following ways to delete a cookie:
Page 89
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

o A cookie can be deleted by using expire attribute.


o A cookie can also be deleted by using max-age attribute.
o We can delete a cookie explicitly, by using a web browser.
Examples to delete a Cookie
Example 1: -
In this example, we use expire attribute to delete a cookie by providing
expiry date (i.e. any past date) to it.
<html>
<head>
</head>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="name=Martin Roy; expires=Sun, 20 Aug 2000 12:00:00 UTC";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not avaliable");
}
}
</script>
</body>
</html>
Example 2: -
In this example, we use max-age attribute to delete a cookie by
providing zero or negative number (that represents seconds) to it.
<html>
<head>

Page 90
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</head>
<body>

<input type="button" value="Set Cookie" onclick="setCookie()">


<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="name=Martin Roy;max-age=0";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not avaliable");
}
}

</script>
</body>

</html>
Example 3: -
Let's see an example to set, get and delete multiple cookies.
<html>
<head>
</head>
<body>
<input type="button" value="Set Cookie1" onclick="setCookie1()">
<input type="button" value="Get Cookie1" onclick="getCookie1()">
<input type="button" value="Delete Cookie1" onclick="deleteCookie1()">
<br>
<input type="button" value="Set Cookie2" onclick="setCookie2()">
<input type="button" value="Get Cookie2" onclick="getCookie2()">

Page 91
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<input type="button" value="Delete Cookie2" onclick="deleteCookie2()">


<br>
<input type="button" value="Display all cookies" onclick="displayCookie()">
<script>
function setCookie1()
{
document.cookie="name=Martin Roy";
cookie1= document.cookie;
}
function setCookie2()
{
document.cookie="name=Duke William";
cookie2= document.cookie;
}
function getCookie1()
{
if(cookie1.length!=0)
{
alert(cookie1);
}
else
{
alert("Cookie not available");
}
}
function getCookie2()
{
if(cookie2.length!=0)
{
alert(cookie2);
}
else
{
alert("Cookie not available");
}
}
function deleteCookie1()
{

Page 92
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

document.cookie=cookie1+";max-age=0";
cookie1=document.cookie;
alert("Cookie1 is deleted");
}
function deleteCookie2()
{
document.cookie=cookie2+";max-age=0";
cookie2=document.cookie;
alert("Cookie2 is deleted");
}
function displayCookie()
{
if(cookie1!=0&&cookie2!=0)
{
alert(cookie1+" "+cookie2);
}
else if(cookie1!=0)
{
alert(cookie1);
}
else if(cookie2!=0)
{
alert(cookie2);
}
else{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Example 4: -
Let's see an example to delete a cookie explicitly.
<html>
<head>
</head>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">

Page 93
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<input type="button" value="Get Cookie" onclick="getCookie()">


<script>
function setCookie()
{
document.cookie="name=Martin Roy";

}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not avaliable");
}
}
</script>
</body>
</html>
After clicking Set Cookie once, whenever we click Get Cookie, the
cookies key and value is displayed on the screen.
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 Handler Description

Page 94
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Performed

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 Performed Event Handler Description

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

Form events: -
Event Performed Event Handler Description

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

Page 95
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

Let's discuss some examples over events and their handlers.


Click Event: -
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("This is Easy4us");
}
</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 Easy4us");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

Page 96
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Focus Event: -
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>
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>

Page 97
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

</html>

Exception Handling in JavaScript: -


An exception signifies the presence of an abnormal
condition which requires special operable techniques. In programming terms,
an exception is the anomalous code that breaks the normal flow of the code.
Such exceptions require specialized programming constructs for its
execution.
What is Exception Handling: -
In programming, exception handling is a process or method used
for handling the abnormal statements in the code and executing them. It also
enables to handle the flow control of the code/program. For handling the
code, various handlers are used that process the exception and execute the
code.
For example, the Division of a non-zero value with zero will
result into infinity always, and it is an exception. Thus, with the help of
exception handling, it can be executed and handled.
In exception handling:
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.

Page 98
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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.
These exception handling statements are discussed in the next section.
JavaScript try…catch: -
A try…catch is a commonly used statement in various
programming languages. Basically, it is used to handle the error-prone part of

Page 99
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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

Page 100
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

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: -
1. try{
2. throw exception; // user can define their own exception
3. }
4. 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.

Page 101
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Syntax: -
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
expression; } //Executable code
try…catch…finally example: -
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>
Therefore, we can also use try/catch/throw/finally keyword together for
handling complex code.
JavaScript this keyword: -
The this keyword is a reference variable that refers to the current
object. Here, we will learn about this keyword with help of different
examples.
JavaScript this Keyword Example: -
Let's see a simple example of this keyword.

Page 102
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

<html>
<head>
<script>
var address=
{
company:"Easy4us",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
}
};
var fetch=address.fullAddress();
document.writeln(fetch);
</script>
</head>
<body>
</body>
</html>

Output:
Easy4us Noida UP
The following ways can be used to know which object is referred by this
keyword.
Global Context
In global context, variables are declared outside the function. Here, this
keyword refers to the window object.
<html>
<head>
<script>
var website="Easy4us";
function web()
{
document.write(this.website);
}

Page 103
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

web();
</script>
</head>
<body>
</body>
</html>

The call() and apply() method


The call() and apply() method allows us to write a method that
can be used on different objects.
<html>
<head>
<script>
var emp_address = {
fullAddress: function() {
return this.company + " " + this.city+" "+this.state;
}
}
var address = {
company:"Easy4us",
city:"Noida",
state:"UP",
}
document.writeln(emp_address.fullAddress.call(address));
document.writeln(emp_address.fullAddress.apply(address));
</script>
</head>
<body>
</body>
</html>
The bind() Method
The bind() method was introduced in ECMAScript 5. It creates a
new function whose this keyword refers to the provided value, with a given
sequence of arguments.

Page 104
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)

Note: - EMCAScript is a Standard for scripting languages such as


JavaScript. Jscript, etc. It is a trademark scripting languages specification.
JavaScript is a language based on ECMAScript. JavaScript is considered as
one of the most popular implementations of ECMAScript.
<html>
<head>
<script>
var lang="Java";
function lang_name(call)
{
call();
};
var obj={
lang:"JavaScript",
language:function()
{
document.writeln(this.lang+ " is a popular programming language.");
}
};
lang_name(obj.language);
lang_name(obj.language.bind(obj));
</script>
1. </head>
2. <body>
3. </body>
4. </html>

Page 105

You might also like