Javascript Notes
Javascript Notes
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>
Let's create an external JavaScript file that prints Hello Easy4us in an alert
dialog box.
message.js
function msg(){
alert("Hello Easy4us ");
}
Page 4
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;
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>
Page 8
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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
/ Division 20/10 = 2
Page 10
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
= Assign 10+10 = 20
(?:) Conditional Operator returns value based on the condition. It is like if-else.
Page 11
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
statement.
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)
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>
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.
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.
Page 19
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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
5 Object.entries() This method returns an array with arrays of the key, value
pairs.
Page 21
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
12 Object.is() This method determines whether two values are the same
value.
18 Object.seal() This method prevents new properties from being added and
marks all existing properties as non-configurable.
Page 22
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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)
Page 23
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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.
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.
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.
Page 25
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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.
slice() It returns a new array containing the copy of the part of the given 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>
charCodeAt() It provides the Unicode value of a character present at the specified index.
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.
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.
toLocaleLowe It converts the given string into lowercase letter on the basis of host’s current
rCase() locale.
toLocaleUpper It converts the given string into uppercase letter on the basis of host’s current
Case() locale.
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.
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>
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.
toJSON() It returns a string representing the Date object. It also serializes the
Date object during JSON serialization.
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)
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
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.
floor() It returns largest integer value, lower than or equal to 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)
Page 38
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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.
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)
Constructor Returns the reference of Boolean function that created Boolean object.
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
confirm() Displays the confirm dialog box containing message with ok and cancel button.
setTimeout() performs action after specified time like calling function, evaluating expressions
etc.
Page 41
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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
Page 43
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Page 44
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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
Page 46
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Page 47
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
writeln("string") Writes the given string on the doucment with newline character
at the end.
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.
</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)
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: -
Page 53
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Page 54
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Page 55
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
</form>
Page 56
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Output:
Enter Name:
Page 57
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Enter Password:
register
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
Page 63
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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
Page 65
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Note - If we didn't specify any constructor method, JavaScript use default constructor 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)
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)
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");
}
}
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.
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.
Page 83
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Page 84
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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.
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;
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);
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:-
Page 90
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
</head>
<body>
</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)
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)
}
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
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
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
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
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>
Page 98
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
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>
Page 104
JavaScript
Easy4us A Computer Language Institute
Prabhat Kumar (Katras)
Page 105