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

JavaScript Merged Merged

The document provides an overview of JavaScript, its functionalities, and how to implement it within HTML pages. It covers topics such as JavaScript's role in adding interactivity, its syntax, variable scope, and destructuring for easier data access. Additionally, it explains the use of operators, comments, and the importance of case sensitivity in JavaScript programming.

Uploaded by

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

JavaScript Merged Merged

The document provides an overview of JavaScript, its functionalities, and how to implement it within HTML pages. It covers topics such as JavaScript's role in adding interactivity, its syntax, variable scope, and destructuring for easier data access. Additionally, it explains the use of operators, comments, and the importance of case sensitivity in JavaScript programming.

Uploaded by

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

http://www.vidyanidhi.

com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC
of CDAC
9769201036
ketkiacharya.net@gm
ail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


What is JavaScript?
•JavaScript was designed to add interactivity to HTML
pages
•JavaScript is a scripting language
•A scripting language is a lightweight programming
language
•A JavaScript consists of lines of executable computer code
•A JavaScript is usually embedded directly into HTML
pages
•JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
•Everyone can use JavaScript without purchasing a license

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


What can a JavaScript Do?
JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a scripting
language with a very simple syntax! Almost anyone can put small
"snippets" of code into their HTML pages

JavaScript can put dynamic text into an HTML page - A JavaScript


statement like this: document.write("<h1>" + name + "</h1>") can
write a variable text into an HTML page

JavaScript can react to events - A JavaScript can be set to execute when


something happens, like when a page has finished loading or when a user
clicks on an HTML element

JavaScript can read and write HTML elements - A JavaScript can


read and change the content of an HTML element

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• JavaScript can be used to validate data - A JavaScript can be
used to validate form data before it is submitted to a server. This
saves the server from extra processing

• JavaScript can be used to detect the visitor's browser - A


JavaScript can be used to detect the visitor's browser, and -
depending on the browser - load another page specifically
designed for that browser

• JavaScript can be used to create cookies - A JavaScript can be


used to store and retrieve information on the visitor's computer

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


How to Put a JavaScript Into an HTML Page

<html> <body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
The code above will produce this output on an HTML page:

Hello World!
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page
loads into the browser. This is not always what we want.
Sometimes we want to execute a script when a page loads, other
times when a user triggers an event.
Scripts in the head section: Scripts to be executed when they
are called, or when an event is triggered, go in the head section.
When you place a script in the head section, you will ensure that
the script is loaded before anyone uses it.

<html> <head>
<script type="text/javascript"> ...
. </script>
</head>USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Scripts in the body section: Scripts to be executed when
the page loads go in the body section. When you place a script in
the body section it generates the content of the page.

<html>
<head>
</head>
<body>
<script type="text/javascript">
.... </script>
</body>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Scripts in both the body and the head
section: You can place an unlimited number of
scripts in your document, so you can have
scripts in both the body and the head section.

<html>
<head>
<script type="text/javascript"> .... </script>
</head>
<body>
<script type="text/javascript"> .... </script>
</body>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Using an External JavaScript
Sometimes you might want to run the same JavaScript on several pages, without
having to write the same script on every page.
To simplify this, you can write a JavaScript in an external file. Save the external
JavaScript file with a .js file extension.
Note: The external script cannot contain the <script> tag!
To use the external script, point to the .js file in the "src" attribute of the <script>
tag:

<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>

Note: Remember to place the script exactly where you normally would
write the script! USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Lifetime of Variables
When you declare a variable within a function, the variable can only
be accessed within that function. When you exit the function, the
variable is destroyed. These variables are called local variables. You
can have local variables with the same name in different functions,
because each is recognized only by the function in which it is
declared.

If you declare a variable outside a function, all the functions on your


page can access it. The lifetime of these variables starts when they are
declared, and ends when the page is closed.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2.5
% Modulus 5%2 1
(division 10%8 2
remainder) 10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Assignment Operators

Is The Same
Operator Example
As
= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks x=5
for both value and y="5"
type) x==y returns true
x===y returns false

!= is not equal 5!=8 returns true


> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or 5>=8 returns false
equal to
<= is less than or equal 5<=8 returns true
to

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Variables
A variable is a "container" for information you want to store. A variable's
value can change during the script. You can refer to a variable by name to
see its value or to change its value.

Rules for variable names:


•Variable names are case sensitive
•They must begin with a letter or the underscore character

IMPORTANT! JavaScript is case-sensitive! A variable named


strname is not the same as a variable named STRNAME!

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be
used, for example, a radix of 16 (hexadecimal) indicates that the
number in the string should be parsed from a hexadecimal number to a
decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
•If the string begins with "0x", the radix is 16 (hexadecimal)
•If the string begins with "0", the radix is 8 (octal). This feature is
deprecated
•If the string begins with any other value, the radix is 10 (decimal)

Syntax
parseInt(string, radix)
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Parameter Description
string Required. The string to be parsed
radix Optional. A number (from 2 to 36) that
represents the numeral system to be
used

Tips and Notes


Only the first number in the string is returned!
Note:
Note: Leading and trailing spaces are allowed.
Note: If the first character cannot be converted to a
number, parseInt() returns NaN.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


JavaScript is Case Sensitive
A function named "myfunction" is not the same as "myFunction" and a variable named
"myVar" is not the same as "myvar".
JavaScript is case sensitive - therefore watch your capitalization
closely when you create or call variables, objects and functions.

White Space
JavaScript ignores extra spaces. You can add white
space to your script to make it more readable. The
following lines are equivalent:

name="Hege" name = "Hege"

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Break up a Code Line
You can break up a code line within
a text string with a backslash
The example below will be displayed properly:

document.write("Hello \
World!")

However, you cannot break


up a code line like this:

document.write \ ("Hello
World!")

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


//this is a comment
document.write("Hello World!")

/* This is a comment block. It contains several lines


*/ document.write("Hello World!")

or by using /* and */ (this creates a multi-line


comment block):

/* This is a comment block. It contains


several lines */ document.write("Hello
World!")
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
JavaScript is an Object Oriented Programming
(OOP) language.

An OOP language allows you to define your own objects and


make your own variable types.

Properties

Properties are the values associated with an object.

<script type="text/javascript">
var txt="Hello World!“
document.write(txt.length)
</script>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Methods

Methods are the actions that can be


performed on objects.
<script type="text/javascript">

var str="Hello world!“

document.write(“upper”+str.toUpperCase())

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• he ECMAScript Edition 4 standard will be the
first update to be released in over four years.
• JavaScript 2.0 conforms to Edition 4 of the
ECMAScript standard, and the difference
between the two is extremely minor.
• The specification for JavaScript 2.0 can be
found on the following site:
http://www.ecmascript.org/

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Programming the Web
DHTML

• The DHTML Document Object Model (DOM)

window

event navigator history document location screen frames

all location children forms selection body links

text radio button textarea select


password checkbox submit
option
file reset

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Destructuring for Easier Data Access
Object and array literals are two of the most frequently used notations in JavaScript, and thanks to the popular JSON data
format, they’ve become a particularly important part of the language. It’s quite common to define objects and arrays, and then
systematically pull out relevant pieces of information from those structures. ECMAScript 6 simplifies this task by adding
destructuring, which is the process of breaking a data structure down into smaller parts. This chapter shows you how to
harness destructuring for both objects and arrays.
Why is Destructuring Useful?
In ECMAScript 5 and earlier, the need to fetch information from objects and arrays could lead to a lot of code that looks
the same, just to get certain data into local variables. For example:
int a=5, b=7
let options = { repeat: true, save: false };
// extract data from the object

let repeat = options.repeat,

save = options.save;
This code extracts the values of repeat and save from the options object and stores that data in local variables with the same names. While
this code looks simple, imagine if you had a large number of variables to assign; you would have to assign them all one by one. And if there
was a nested data structure to traverse to find the information instead, you might have to dig through the entire structure just to find one
piece of data.

That’s why ECMAScript 6 adds destructuring for both objects and arrays. When you break a data structure into smaller parts, getting the
information you need out of it becomes much easier. Many languages implement destructuring with a minimal amount of syntax to make the
process simpler to use. The ECMAScript 6 implementation actually makes use of syntax you’re already familiar with: the syntax for object and
array literals. USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Object Destructuring
Object destructuring syntax uses an object literal on the left side of an assignment operation. For example:
let node = { type: "Identifier", name: "foo"
}; Don’t Forget the Initializer
When using destructuring to declare variables using
let { type, name } = node; var, let, or const, you must supply an initializer (the
console.log(type); value after the equals sign). The following lines of
code will all throw syntax errors due to a missing
// "Identifier" console.log(name); initializer:

// "foo" // syntax error!


var { type, name };

// syntax error!
node type: "Identifier", name: "foo" let { type, name };

// syntax error!
const { type, name };
let { type, name } = node; While const always requires an initializer, even when
using nondestructured variables, var and let only
require initializers when using destructuring.
Identifier foo
type name
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Destructuring Assignment
The object destructuring examples so far have used variable declarations. However, it’s also possible to
use destructuring in assignments. For instance, you may decide to change the values of variables after
they are defined, as follows:
In this example, type and name are initialized with values
let node = { when declared, and
type: "Identifier",
name: "foo" then two variables with the same names are initialized with
}, different values.
type = "Literal",
name = 5; The next line uses destructuring assignment to change those
values by reading from the node object.
// assign different values using destructuring
({ type, name } = node); Note that you must put parentheses around a destructuring
assignment statement. That’s because an opening curly brace
console.log(type); // "Identifier" is expected to a be a block statement, and a block statement
console.log(name); // "foo" cannot appear on the left side of an assignment. The
parentheses signal that the next curly brace is not a block
statement and should be interpreted as an expression,
allowing the assignment to complete.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


A destructuring assignment expression evaluates to the right side of the expression (after the =). That means you
can use a destructuring assignment expression anywhere a value is expected. For instance, passing a value to a
function:
type:
"Identifier",
name: "foo" The outputInfo() function is called with a destructuring
let node = { assignment expression. The expression evaluates to node
type: "Identifier", because that is the value of the right side of the
name: "foo" expression. The assignment to type and name both
}, behave as normal and node is passed into outputInfo().
type = "Literal", node value
name = 5;
Note:
function outputInfo(value) { An error is thrown when the right side of the
console.log(value === node); destructuring assignment expression (the expression after
} =) evaluates to null or undefined. This happens because
any attempt to read a property of null or undefined
outputInfo({ type, name } = node); // true results in a runtime error.

console.log(type); // "Identifier" type


console.log(name); // "foo" “Literal”

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Default Values

When you use a destructuring assignment statement, if you specify a local variable with a property name that doesn’t
exist on the object, then that local variable is assigned a value of undefined. For example:
let node = {
type: "Identifier", You can optionally define a default value to use when a
name: "foo" specified property doesn’t exist. To do so, insert an equals sign
}; (=) after the property name and specify the default value, like
this:
let { type, name, value } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // undefined let { type, name, value = true } = node;
This code defines an additional local variable called
value and attempts to assign it a value. However, there console.log(type); // "Identifier"
is no corresponding value property on the node object, console.log(name); // "foo"
so the variable is assigned the value of undefined as console.log(value); // true
expected.
In this example, the variable value is given true as a default value. The default value
is only used if the property is missing on node or has a value of undefined. Since
there is no node.value property, the variable value uses the default value. This
works similarly to the default parameter values for functions,
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Assigning to Different Local Variable Names
Up to this point, each example de structuring assignment has used the object property name as the local variable name; for
example, the value of node.type was stored in a type variable. That works well when you want to use the same name, but what
if you don’t? ECMAScript 6 has an extended syntax that allows you to assign to a local variable with a different name, and that
syntax looks like the object literal non shorthand property initializer syntax. Here’s an example:
let node = {
type: "Identifier",
name: "foo"
};

let { type: localType, name: localName } = node type: "Identifier", name: "foo"
;

console.log(localType); // "Identifier"
console.log(localName);
console.log(type); //err

This code uses destructuring assignment to declare the localType and localName variables, which contain the values from
the node.type and node.name properties, respectively. The syntax type: localType says to read the property named type
and store its value in the localType variable. This syntax is effectively the opposite of traditional object literal syntax, where
the name is on the left of the colon and the value is on the right. In this case, the name is on the right of the colon and the
location of the value to read is on the left.
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
You can add default values when using a different variable name, as well. The equals sign and
default value are still placed after the local variable name. For example:

let node = {
type: "Identifier“
};

let { type: localType, name: localName = "bar" } = node;

console.log(localType); // "Identifier"
console.log(localName); // "bar"

Here, the localName variable has a default value of "bar". The variable is assigned its default value because there’s no
node.name property.

So far, you’ve seen how to deal with destructuring of an object whose properties are primitive values. Object destructuring
can also be used to retrieve values in nested object structures.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Nested Object Destructuring
By using a syntax similar to object literals, you can navigate into a nested object structure to retrieve just the
information you want. Here’s an example:
let node1 = {
type: "Identifier", The destructuring pattern in this example uses curly braces to indicate that the pattern
name: "foo" should descend into the property named loc on node and look for the start property.
};
Remember from the last section that whenever there’s a colon in a destructuring
let node = { pattern, it means the identifier before the colon is giving a location to inspect, and the
type: "Identifier",
name: "foo", right side assigns a value. When there’s a curly brace after the colon, that indicates that
loc: { the destination is nested another level into the object.
start: {
line: 1,
column: 1 You can go one step further and use a different name for the local
}, variable as well: let node = {
end: { type: "Identifier",
line: 1, name: "foo",
In this version of the
column: 4 loc: { code, node.loc.start
}
} line: 1,
start: { line: 1, is stored in a new
}; column:1 column: 1 local variable called
},
let { loc: { start }} = node; end: { line: 1, localStart.
column: 4 Destructuring
console.log(start.line); // 1 }
console.log(start.column); start patterns can be
}
};
nested to an arbitrary
// extract node.loc.start level of depth, with
let { loc: { start:{line} } } = node; let { loc: { start: localStart }} = node; all capabilities
console.log(line) console.log(localStart.line); // 1 available at each
1 console.log(localStart.column); // 1
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
level.
Array Destructuring
Array destructuring syntax is very similar to object destructuring; it just uses array literal syntax instead of object
literal syntax. The destructuring operates on positions within an array, rather than the named properties that are
available in objects. For example:
You can also omit items in the destructuring pattern and only
let colors = [ "red", "green", "blue" ]; provide variable names for the items you’re interested in. If, for
example, you just want the third value of an array, you don’t
let [ firstColor, secondColor ] = colors; need to supply variable names for the first and second items.
Here’s how that works:
console.log(firstColor); // "red"
console.log(secondColor); // "green" let colors = [ "red", "green", "blue" ];

let [ , , thirdColor ] = colors;


Here, array destructuring pulls out the values "red" and
"green" from the colors array and stores them in the console.log(thirdColor); // "blue"
firstColor and secondColor variables. Those values are
chosen because of their position in the array; the actual
This code uses a destructuring assignment to retrieve the third
variable names could be anything. Any items not
item in colors. The commas preceding thirdColor in the pattern
explicitly mentioned in the destructuring pattern are
are placeholders for the array items that come before it. By using
ignored. Keep in mind that the array itself isn’t changed
this approach, you can easily pick out values from any number of
in any way.
slots in the middle of an array without needing to provide
variable names for them.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Destructuring Assignment
You can use array destructuring in the context of an assignment, but unlike object destructuring, there
is no need to wrap the expression in parentheses. For example:

let colors = [ "red", "green", "blue" ],


firstColor = "black",
secondColor = "purple";

[ firstColor, secondColor ] = colors;

console.log(firstColor); // "red"
console.log(secondColor);

The destructured assignment in this code works in a similar manner to the last array destructuring example. The only
difference is that firstColor and secondColor have already been defined. Most of the time, that’s probably all you’ll
need to know about array destructuring assignment, but there’s a little bit more to it that you will probably find
useful.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Swap Two Number

Array destructuring assignment has a very unique use case that makes it easier to swap the
values of two variables. Value swapping is a common operation in sorting algorithms, and the
ECMAScript 5 way of swapping variables involves a third, temporary variable, as in this
example: The intermediate variable tmp is necessary in order to swap the
values of a and b. Using array destructuring assignment,
let a = 1,
however, there’s no need for that extra variable. Here’s how
b = 2,
you can swap variables in ECMAScript 6:
tmp;
// Swapping variables in ECMAScript 5
tmp = a; // Swapping variables in ECMAScript 6
a = b; let a = 1,
b = tmp; b = 2;

console.log(a); // 2 [ a, b ] = [ b, a ];
console.log(b); // 1
console.log(a); // 2
console.log(b); // 1

The array destructuring assignment in this example looks like a mirror image. The left side of the assignment (before the
equals sign) is a destructuring pattern just like those in the other array destructuring examples. The right side is an array
literal that is temporarily created for the swap. The destructuring happens on the temporary array, which has the values of
b and a copied into its first and second positions. The effect is that the variables have swapped values.
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Default Values
Array destructuring assignment allows you to specify a default value for any position in the array, too. The default
value is used when the property at the given position either doesn’t exist or has the value undefined. For example

let colors = [ "red" ];

let [ firstColor, secondColor = "green" ] = colors;

console.log(firstColor); // "red"
console.log(secondColor); // "green"

In this code, the colors array has only one item, so there is
nothing for secondColor to match. Since there is a default value,
secondColor is set to "green" instead of undefined

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Nested Destructuring

You can destructure nested arrays in a manner similar to destructuring nested objects. By inserting another array
pattern into the overall pattern, the destructuring will descend into a nested array, like this:

let colors = [ "red", [ "green", "lightgreen" ], "blue" ];

// later

let [ firstColor, [ secondColor ] ] = colors;

console.log(firstColor); // "red"
console.log(secondColor); // "green"

Here, the secondColor variable refers to the "green" value inside the colors array. That item is contained within a second
array, so the extra square brackets around secondColor in the destructuring pattern are necessary. As with objects, you
can nest arrays arbitrarily deep.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Rest Items

rest parameters for functions, and array destructuring has a similar concept called rest items. Rest items use the ... syntax to
assign the remaining items in an array to a particular variable. Here’s an example:

restColors
let colors = [ "red", "green", "blue" ];
0 1
let [ firstColor, ...restColors ] = colors;

console.log(firstColor); // "red" green blue


console.log(restColors.length); // 2
console.log(restColors[0]); // "green"
console.log(restColors[1]); // "blue"

The first item in colors is assigned to firstColor, and the rest are assigned into a new restColors array. The restColors
array, therefore, has two items: "green" and "blue". Rest items are useful for extracting certain items from an array
and keeping the rest available, but there’s another helpful use.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


clone

A glaring omission from JavaScript arrays is the ability to easily create a clone. In ECMAScript 5, developers frequently used
the concat() method as an easy way to clone an array. For example:

// cloning an array in ECMAScript 5 // cloning an array in ECMAScript 6


var colors = [ "red", "green", "blue" ]; let colors = [ "red", "green", "blue" ];
var clonedColors = colors.concat(); let [ ...clonedColors ] = colors;

console.log(clonedColors); console.log(clonedColors);
//"[red,green,blue]" //"[red,green,blue]"

In this example, rest items are used to copy values from


the colors array into the clonedColors array. While it’s a
While the concat() method is intended to concatenate two matter of perception as to whether this technique makes
arrays together, calling it without an argument returns a clone the developer’s intent clearer than using the concat()
of the array. In ECMAScript 6, you can use rest items to achieve method, this is a useful ability to be aware of.
the same thing through syntax intended to function that way. It
works like this:
Note:Rest items must be the last entry in the destructured array
and cannot be followed by a comma. Including a comma after
rest items is a syntax error.
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
concat

A glaring omission from JavaScript arrays is the ability to easily create a clone. In ECMAScript 5, developers frequently used
the concat() method as an easy way to clone an array. For example:

// cloning an array in ECMAScript 5


var colors = [ "red", "green", "blue" ];
var colors2 = [ “white", “pink", "black" ];
var clonedColors = colors.concat(colors2 );

console.log(clonedColors);
//"[red,green,blue, white, pink, black]"

While the concat() method is intended to concatenate two arrays together, calling it without an argument returns a clone
of the array. In ECMAScript 6, you can use rest items to achieve the same thing through syntax intended to function that
way. It works like this:

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Default value of unassigned variable
var a; document.write(a+"<br/>");
document.write(a+"<br/>"); If you print
let b; undeclare and uninitialized variable you will
get error
document.write(b+"<br/>");
const x=2; ReferenceError: a is not defined <anonymous>
document.write(x+"<br/>"); file:///D:/jspractice/a.html:4

If you declare variable but forget to initialised it will print


undefined But undeclared but intilised variable will not give any error
Ie. a=5;
In Js there no compulsion to declare variable. document.write(a+"<br/>");
Due to which if programmer type wrong variable
name then JS consider it as another variable.
Eg, Observe neither var nor let keyword used.
Fname=“VITA”

And some ware you intend to use Fname but by


mistake you wrote Fnme then it will not give error
but Fnme will be consider as new variable .
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
‘use strict’
For better and safe programming always use ‘use strict’ which indicate you are
running script in a strict mode.
'use strict'
a=5;
document.write(a+"<br/>");

This code will give error.


ReferenceError: assignment to undeclared variable a

You must declare variable with var, let or const key word

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<!DOCTYPE html>
<html lang="us-eng">

Order of execution is top to bottom. <head><title>my 1st example</title>


Any javascrpt code has to be within <meta content="text/html; charset=UTF-8" http-equiv="content-type">
<script></script> tag. Html does not <style>
understand script. .cl{color:red;}
</style>
In browser there is javas script engine
which will compile your code and generate <script>

native code. document.write("hello in head");


</script>
In browser you can disable Java script. </head>
Window <body>
<h1> head----main page</h1>
<script>
document
document.write("<b class= 'cl'>main section</b>");
Document document.write("<hr/>");
console.log(document);
console.log(window);
</script>
<p> again in html part</p> <p>Unicode Transformation Format </p>
window </body> </html>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Java Script is OOP language
<script>
document.write("hello in head");
console.log(document);
console.log(window);
</script>
• In the above example document is reference to Object Document[function
Document]
• Write is a method in Document class.
document is member of Window class.
Try above example and observe console which will display all method and
property associate with class Document

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
var a=5; Typeof operator revel datatype of any variable.
document.write(typeof(a));
Eg.
var aa=5.5;
var a=5;
document.write(typeof(aa)); a is number

var b="hello";
document.write(typeof(b));
var c='h';
var aa=5.5 // is a number
document.write(typeof(c));
var b=“hello” //is a string
var p=true; var c=‘d’ //string
Var p=true; //boolean
document.write(typeof(p));
var y; Any calculation between undefine and data will result into not a number. NaN
document.write(y);
+ operator is overloaded in string class
var x=2;
document.write(y+2);
var str="hi"
document.write(x+2);//4
document.write(str+2);//hi2
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
+ operator is overloaded
<script>
var a;
var b;
a=5;
b=9;
document.write(a+b); //14
document.write( a+b+" ans ");//14 ans
document.write("<br/>ans="+a+b);//ans=59
//if 1st is string and then + then “+” as concatenation operator

document.write("<br/>ans="+(a+b));//ans=14
In the above line () has higher presidence so it will print
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Beware of Automatic Type Conversions
Beware that numbers can accidentally be converted to strings or NaN (Not a Number).
JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:
Example
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number

When doing mathematical operations, JavaScript can convert numbers to strings:


Example
var x = 5 + 7; // x.valueOf() is 12, typeof x is a number
var x = 5 + "7"; // x.valueOf() is 57, typeof x is a string
var x = "5" + 7; // x.valueOf() is 57, typeof x is a string
var x = 5 - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number
var x = "5" - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - “y"; // x.valueOf() is NaN, typeof x is a number
var x = “5” *” 7”; // x.valueOf() is 35, typeof x is a number
Var p=“3”
d.w(p.valueOf())
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
for(var i=1;i<=3;i++)
Let var difference document.write(i);
document.write(i);//4
for(let i=1;i<=3;i++)
document.write(i); Scope of var is hoisted
document.write(i);//err Ie. Declaration is read above for loopp

Scope of let I within block var i;


for(i=1;i<=3;i++)
document.write(i);
document.write(i);//4

Scope of var is hoisted


Ie. Declaration is read above for
loop

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Constant declarations
Variables declared using const are considered to be Constants are also block-level declarations, similar to let.
constants, so the value cannot be changed once set. That means constants are destroyed once execution flows
For this reason, every const variable must be out of the block in which they were declared and
initialized. For example: declarations are not hoisted to the top of the block. For
example:
if (condition) {
// Valid constant const MAX_ITEMS = 5;
// more code
const MAX_ITEMS = 30;
}
// MAX_ITEMS isn't accessible here
// Syntax error: missing initialization
In this code, the constant MAX_ITEMS is declared within
const NAME; and if statement.
Once the statement finishes executing, MAX_ITEMS is
destroyed and is not accessible outside of that block.
// Syntax error: Declaration and initialization in
different line
const NAME;
NAME=“VITA”;

USM’s Shriram Mantri Vidyanidhi Info Tech Academy



const in objects and arrays
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable
identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its
properties) can be altered
const MY_OBJECT = {'key': 'value’};

// Attempting to overwrite the object throws an error // Uncaught TypeError: Assignment to


constant variable.

MY_OBJECT = {'OTHER_KEY': 'value’};

// However, object keys are not protected, // so the following statement is executed without
problem
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable // The same
applies to arrays

const MY_ARRAY = []; // It's possible to push items into the array

MY_ARRAY.push('A'); // ["A"]

// However, assigning a new array to the variable throws an error // Uncaught TypeError:
Assignment to constant variable.

MY_ARRAY = ['B'];
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Object

const MY_OBJECT = {'key': 'value’};

MY_OBJECT
Key=value
otherValue
Name=“vita”

MY_OBJECT.Key = 'otherValue';

MY_OBJECT.Name = ‘vita';

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


const MY_OBJECT = {'key': 'value’};

const arr=[1,2,3]; MY_OBJECT = {'OTHER_KEY': 'value’};


arr.push(5);
// Attempting to overwrite the object throws an
for (const iter of arr) error // Uncaught TypeError: Assignment to constant
variable
console.log(iter)

iter
1 2 3 5 'key': 'value
MY_OBJECT

// Use Object.freeze(MY_OBJECT) to make


object immutable // The same applies to
arrays
MY_OBJECT.key = 'otherValue'; 'Otherkey': 'value

'key’: ‘Othervalue’
MY_OBJECT

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Also similar to let, an error is thrown whenever a const declaration is made with an identifier for an already-defined variable in the same scope. It doesn’t
matter if that variable was declared using var (for global or function scope) or let (for block scope). For example:
‘use strict’
var message = "Hello!";
let age = 25;

// Each of these would cause an error given the previous declarations


const message = "Goodbye!";
const age = 30;

• Uncaught SyntaxError: redeclaration of let age


• Uncaught SyntaxError: redeclaration of var message

• Let is preferred over var


• Because var a=55;
• var a=99
• //no error but
• Let a=99;
• Let a=55;
• //you will get error Uncaught SyntaxError: redeclaration of let a

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


External js <html>
Create ex1.js <head>
<title>VITA</title>
function call() <script src="js/ex1.js">
{ </script>
</head>
document.write("hello welcome to <body>
javascript"); <script>
} call();
</script>
</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Function
Since javascript is dynamically typed programming language function can return any type of data and it need not mention the type.
<script>
"use strict";
function go()
{ Function definition
document.write("hello");
} function go()

go(); //function call {

var r=go(); undefined document.write("hello");

console.log(r);//Undefine }
document.write(typeof(go)); //function

document.write("<hr/>");

document.write(go); //function defination

</script>
In the above example observe no datatype before function. In the above example r will get value “Undefined” . By default function will return
undefined.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Passing parameter to function
<script> Observe we do not have to write any
"use strict"; type before a, b in function definition.
a b p
function call(a,b)
5 7 35
{ var p; function call(a,b){ }
p=a*b
a b p Every function has it’s own copy of
return p;
variable.
} 3 3 9
var x , y; We know function makes code reusable.
x=5; x y r
y=7; 5 7 35
var r=call(x,y);
document.write(r);
9
document.write(call(3,3));
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Passing insufficient parameter to function
<script> In javascript if you pass only one
"use strict"; parameter in function call and have two
a b p parameter in definition. It is not an
function call(a,b) error.
5 undefined NaN
{ var p;
p=a*b function call(a,b)
a b p { }
return p;
} 3 3 9
var r=call(x);
var x , y;
x=5; x y r Observe we do not have to write any
type before a, b in function definition.
y=7; 5 7 NaN
var r=call(x);
document.write(r); function call(a,b){ }
9
document.write(call(3,3)); Every function has it’s own copy of
</script> variable.
We know function makes code reusable.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Passing insufficient parameter to function and checking undefined

<script> a In javascript if you pass only one


"use strict"; parameter in function call and have two
function call(a,b) 5 b p parameter in definition. It is not an
{ var p; error.
undefined 5
if(a!=undefined&&b!=undefined)
p=a*b function call(a,b)
else if(a!=undefined) a b p { }
p=a;
3 3 9
return p; var r=call(x);
}
var x , y; x y r We can avoid NaN by checking undefine
x=5; before calculation.
y=7; 5 7 5
var r=call(x);
document.write(r);
document.write(call(3,3)); 9
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
Logically setting default value
"use strict";
What is false in java script
function call(a,b) 0
{ var p; undefined
b=b || 3;
p=a*b
return p;
}
var x , y;
x=5;
y=7;
var r=call(x);
document.write(r);
document.write(call(3,3));
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Default argument

<script> a In javascript if you pass only one


"use strict"; parameter in function call and have two
5 b p parameter in definition. It is not an
function call(a,b=1) error. You can set default value for
1 5
{ var p; second parameter.
p=a*b If user pass second parameter then
a b p default value will be overridden.
return p;
} 3 13 9
function call(a,b)
var x , y; { }
x=5; x y r var r=call(x);
y=7; 5 7 5
var r=call(x); We can avoid NaN by checking undefine
document.write(r); before calculation.
9
document.write(call(3,3)); Default parameter has to be last.
</script> If you set default parameter in between
you will get error

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
"use strict";
Variable length of argument
function findMax() {
Arguments
var i, max = arguments[0];
arguments
for (i = 1; i < arguments.length; i++) {
if (arguments[i] > max) { 0 1 2 3 4 5
max = arguments[i];
1 123 500 115 44 88
}
console.log(arguments); Callee:
console.log(typeof arguments)//Object
} Symbole:
return max;
}
var x = findMax(1, 123, 500, 115, 44, 88);
document.write(x);</script>

• arguments object contains all arguments passed to the function;


• the arguments object is not a real array
• methods like sort, map, forEach or pop can not be applied on it directly;
• the arguments object has additional functionality specific to itself (like the
callee property).
• You can call findMax() function with different number of parameter
• Call findMax(2,9)
• Call findMax(9,8,2)

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Rest parameter function multiply( ...myarg) { }
<script>
"use strict";
In above line myarg is rest parameter observe 3 dots
myarg
function multiply(...myarg) {
console.log(myarg) //
2 3
console.log(typeof myarg)// object
console.log(myarg.constructor)// object
let sum=0;
for(let i=0;i<myarg.length;i++)
sum=sum+myarg[i];
return sum;
}
var arr = multiply( 2, 3); 2 3
document.write(arr);
arr = multiply( 2, 3,5,6,7); arr

</script>
5

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Rest parameter Uncaught SyntaxError: Rest parameter must be last
formal parameter
<script>
You will get above error if your rest parameter is not
"use strict";
last parameter
function multiply(m, ...myarg) { m
function multiply( ...myarg, m) { }
console.log(myarg) //2.3
1 0 1 In above line rest parameter is in the beginning
console.log(typeof myarg)// object
let sum=0; 2 3
for(let i=0;i<myarg.length;i++)
ar
sum=sum+myarg[i];
r
return sum;
5
}
var arr = multiply( 1, 2, 3);
document.write(arr);
</script>
1 2 3

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Difference between rest parameters and the arguments object

• There are three main differences between rest parameters and the
arguments object:

• rest parameters are only the ones that haven't been given a separate
name, while the arguments object contains all arguments passed to
the function;
• the arguments object is not a real array, while rest parameters are
Array instances, meaning methods like sort, map, forEach or pop can
be applied on it directly;
• the arguments object has additional functionality specific to itself
(like the callee property).

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


spread
Closely related to rest parameters is the spread operator. While rest parameters allow you to specify that
multiple independent arguments should be combined into an array, the spread operator allows you to specify an
array that should be split and have its items passed in as separate arguments to a function

<script> x y z
"use strict";
0 1 2
function myFunction(x, y, z)

{ return x+y+z;

} args

var args = [0, 1, 2];


0 1 2
0 1 2
var r=myFunction(...args);

console.log(r);

</script>

• Any argument in the argument list can use spread syntax and it can be used multiple times.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Spread parameter can be written any where in function call.

v w y
x
<script>
-1 0 1 2
"use strict";

function myFunction(v, w, x, y, z) { }

var args = [0, 1];

myFunction(-1, ...args, 2) -1 0 1 2

<script> args

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


“use strict” is good practice else see the problem
external memory block
<script>
//observe you have not used use strict X a=5
var x; //global variable Undefined
function call() c 9
{
a=5; //global variable 7
var c=7; //local variable
document.write("welcome");
alert("hi");
x=9;
}
//document.write(a); //uninitialized variable as function call is not done yet
call();
document.write(a); //5 as it is define after function call
//document.write("with var"+c); //out of scope
document.write(x);
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Anonymous function • In Java Script you can assign function definition to a
variable.
<script> • go is a variable which is pointing to anonymous
var go= function () function.
• Try document.write(go) it will print function definition
{ return "This is a String";
}
• How to call anonymous function?
var testStr = go(); // testStr contians "This is a string" Ans: Just put parenthesis “()” after variable pointing to
document.write(testStr); function eg. go();

var testCopy =go; // testCopy is a pointer to the function() • Can we assign function pointer variable to another
variable?
var testing = testCopy(); // testing contains "This is a string"
Ans: yes in our example we have assign go to variable
document.write(testing);
testCopy. Observe var testCopy =go; in this line no
</script> testStr
parenthesis “()” after go
function () This is a String
go
{ return
"This is a testing
String";
testCopy } This is a String

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Can we pass name of function in function call
<script>
function(a) • Recollect we have done function pointer concept in C and
let s=function(a){ s
return a*a { .Net
return a*a • s, c, go , w are pointer to function.
}
} • go(c) this line is calling function go
• Observe parameter passed in go it is “c” which is pointing to
let c=function(a) {
function definition. When you pass data in function call, this
return a*a*a function(a) data get copied in to “w”. Here after function call “c” and“w”
} c { both are pointing to same function definition.
• Here function go says my job is to call function , whichever
var go=function(w,d) return a*a*a name you pass I will call that function.
{ } • Just think instead of “c” can we pass function definition in
alert(w(d)); function call?
} function(w,d) Ans: Yes. But this will reduce flexibility.
go
{
go(c,2) w
return w(d);
}

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Can we pass function definition in function call: callback
<script> • Recollect we have done function pointer concept in C and
.Net
var go=function(w) • Just think can we pass function definition in function call?
Ans: Yes.
{
Observe in our example parameter passed in function call is
alert(w(5)); function definition. So here “w” is now pointing to anonymous
function(a)
} function.
{ This concept is also known as function call back.

go(function(a) { return a*a*a


return a*a*a }

}
go function(w)
) {
w
Alert( w(5));
}

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Check : what will be the output

<script>
function mydata(param1, param2, callback) {
alert('Started learning at.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}

mydata('vita', 'DAC', function() { alert('Finished learning DAC');});

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Self Invoking function
<script>
In this example as soon as page get loaded this function get
(function() executed.

{ alert( "This is a String");} () )

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Lets compare code for better understanding
<script> <script>
var r=(function(a){ var go=function(a){ function(a)
return a*a;} (5) ) return a*a; {
return a*a;
document.write(r); } }
</script> document.write(go);
//print function definition (5)
var r=go(5); //calling function
</script>
So here in this example if you print go with out parenthesis
“()”it will print function definition
So self invoking function is nothing but anonymous function
without handle, and parenthesis “()” after it is just a function
call

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Why to learn self invoking function
(function( window, undefined ) {

})(window)
If you open Jquey.js file you can see such code
In jQuery library they have used these concept.

There are some situation where you want to initialize the data as soon as
application start in such scenario you can use self invoking function

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Self Invoking function
<script> In this example as soon as page get loaded this function get
executed.
var r=(function(a) Here we have passed value 5 in self invoking function.
return a*a;} (5) ) This Anonymous function will return 5*5= 25 which get
captured in variable r.
document.write(r);
Here “r” is handle to hold return value of self invoking
</script> function.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Arrow function
Anonymous function Arrow function
var reflect = function(value) { var reflect1 = value => value;
return value; }; document.write(reflect1(67));
document.write(reflect(22));

var sum = function(num1, num2) { var sum1 = (num1, num2) => num1 + num2;
return num1 + num2; document.write(sum1(5,7));
};
document.write(sum(5,5));

var getName = function() { var getName = () => "TSYS";


return "TSYS"; console.log(getName());
};
console.log(getName());

var getTempItem = function(id) { var getTempItem = id => ({ id:id, name: "Temp" })


return { let obj=getTempItem(5)
id: id, document.write(obj.id)
name: "Temp" Id=5
}; Name=“temp”
obj
};
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
var reflect1 = value => value;
document.write(reflect1(67)); Let cube=n=>n*n*n;
let r= n=> n%2==0 Let ans=cube(2);
let result=r(4);
If(result==true)
console.log(“Number is even”);
-------------------------------------------- var sumfunction = (...arg) => { let sum=0;
let r= n=>{
if(n%2==0) for(let i=0;i<arg.length;i++)
return true; sum=sum+arg[i];
else return sum;
return false; } };
}
Let result=sumfunction(5,6,3,2,1);
console.log(result)

let result= (n)=>{


let f=1;
for(let i=2;i<=n;i++) Let cube=n=>d.w(n*n*n);
f=f*i; cube(2);
return f;

}
Let ans=result(5) USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Arrow function used in array-sort function
values=[6,2,4,5,1,9]; //[111,2,1,22]
var result = values.sort(function(a, b) {
return a - b;
});
document.write(result);
var result1 = values.sort((a, b) => a - b);

document.write(result1); values=[6,2,4,5,1,9];
document.write(values.sort();)

Internally using quick sort

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


map
The map() method creates a new array populated with the results of calling a provided function on
every element in the calling array.

const array1 = [1, 4, 9, 16];

// pass a function to map


const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
Object
Function can also represent as class
//userdefine object
function person(nm,mks) inheritance
{ ob person
alert(this) Name=mona
this.name=nm Marks=80
this.marks=mks
} In java script function it self is class and it act as constructor
var ob=new person("mona",80);// control will go to function also.
document.write(ob); //object Object ob=new person("mona",80);//from this line ---control will go to function
document.write(ob.constructor); //function Person definition and it will initialized the instance member--- name and marks.

document.write("<hr/>") alert(this) //this refer to current object here it will object Object
document.write(ob.name+" "+ob["name"]) • Do I have to use this to initialise instance member ???
document.write("<hr/>") Yes in our example when we use this.name we says that name is
for(let pp in ob) instance variable with reference to class(function) person.
document.write(pp+" "+ob[pp]); • Can I write only name ? No if you want to represent as
instance member this is must.
document.write(ob instanceof person);//true
document.write(ob instanceof Object);//true
Object
Shallow Copy cpy
//userdefine object
function person(nm,mks)
{ inheritance
person
alert(this)
ob
this.name=nm Name=mona Geeta
this.marks=mks Marks=80
}
var ob=new person("mona",80);// control will go to function
document.write(ob); //object Object In java script function it self is class and it act as constructor
document.write(ob.constructor); //function Person also.
document.write("<hr/>") ob=new person("mona",80);//from this line ---control will go to function
Var cpy=ob; definition and it will initialized the instance member--- name and marks.
document.write(ob.name+" "+ob["name"])
alert(this) //this refer to current object here it will object Object
document.write(cpy.name+" "+cpy["name"])
• Do I have to use this to initialise instance member ???
cpy.name=“geeta”
Yes in our example when we use this.name we says that name is
document.write("<hr/>")
instance variable with reference to class(function) person.
for(let pp in ob)
document.write(pp+" "+ob[pp]);
• Can I write only name ? No if you want to represent as
document.write(ob instanceof person);//true
instance member this is must.
document.write(ob instanceof Object);//true
• document.write(ob); //object Object
• Recollect we have studied in .Net that when you print object internally it is calling ToString() method.
• But person class(function) do not have ToString() method?
• Yes. Recollect if method is not found in class(function) then control will go to parent class and here Object is a
parent class so Object class ToString method get called.
• So it is printing object Object here 1st object is data type and second Object is name of class(function)
• document.write(ob.constructor); //function Person
• Here constructor is a key word. We are checking it is calling which constructor?
• It will print full person function definition
• document.write(ob.name+" "+ob["name"])
• By default all member of class(function) are public. So it will allow you to access name instance member out side the
class(function)
• In JS you can also use instance member as index value ie ob["name"] observe name is written in “ ” it is representing
value at this key.
• for(pp in ob)
document.write(pp+" "+ob[pp]);
• in JS you can iterate over the instance member using for in
• This loop will fetch instance member from ob[reference] and store it in variable pp
• So it will print name mona
marks 80
• document.write(ob instanceof person); document.write(ob instanceof Object);
• Above both line will print true [it is same as instanceof key word in java]
• Ob is instance if person class[function]
Can we call directly person(“mona”,80) without new key word?
Yes. That is the biggest problem in JS.
When you call without new key word it will call it with reference to window object. And name and marks will be set as instance member in
window class
//userdefine object
function person(nm,mks)
{
alert(this)//it will display Window[native code]
this.name=nm
this.marks=mks
}
person(“mona”,80);
document.write(window.name);
console.log(window);
“use strict”
Re run this code by adding following line
//userdefine object
“use strict”
function person(nm,mks)
When you add this line in that case
{
alert(this)// undefined
alert(this)//it will display undefined
Here “this” will be undefined and it will not add instance member to
this.name=nm
window class. In fact It will give error and will not allow you to call
this.marks=mks
directly person(“mona”,80) without new key word
}
person(“mona”,80);
document.write(window.name);
console.log(window);
Literal object
<script> Object
var obj={name:"raj“,”2division”:”A” } //this is literal object obj
obj.marks=80 //adding instance member name=raj
alert(obj); // object Object [“2division”]=A
document.write(obj.constructor); //function Object marks=80
document.write(obj.name + “ “ + obj[“2division”]);
</script>

• In literal object we use colon : to assign value to instance member. var obj={"name":"raj“ }
• We can directly add instance member to the class like this obj.marks=80
• which constructor will it call?
It is instance of Object class so it will call constructor of Object class (function)

alert(obj); // object Object


As we know when you print object it will Call ToString() method.
If instance member variable name is not as per rule of variable then enclosed it in “” and you can use it with following syntax
obj[“2division”]);
new Object()
<script> Object
var obj=new Object(); obj
Name=vita
obj.name="vita"; marks=90
obj.marks=90;
document.write(obj); //object Object
document.write(obj.constructor); //function Object
</script>
You can create object using new Object() also.
the differences: constructor object and literal object

 The constructor object has its properties and methods defined with the
keyword 'this' in front of it, whereas the literal version does not.

 In the constructor object the properties/methods have their 'values'


defined after an equal sign '=' whereas in the literal version, they are
defined after a colon ':'.

 The constructor function can have (optional) semi-colons ';' at the


end of each property/method declaration whereas in the literal version
if you have more than one property or method, they MUST be separated with
a comma ',', and they CANNOT have semi-colons after them, otherwise JavaScript will return an
error.

 You can create multiple object for constructor object

 You create only one object in literal object. Just for display and temporary use.
<script>
How to add method to literal object
obj={ In this example fullname is instance
fname: "Raj", method.
lname:"Mathur", obj add is a literal object.
fname=raj
age : 25, toString method is used to display detail
lname=Mathur
add: { d:"juhu"}, of object
fullname: function()
age=25
{ d=juhu
add
return this.fname+ " "+this.lname;
}, fullname toString:function()
return….
toString:function() toString {return this.fullname() +" "+this.age+"
{ return this.fullname() +" "+this.age+" "+ this.add.d; } "+ this.add.d; }
return…. The above code we have use toString()
}
method which will retun state of an
var f=obj.fullname();
object. Ie fullname age and address.
document.write(f);
document.write(obj);
You have to call instance function
document.write(obj.toString());
fullname using this dot only.
</script>
How to add method to constructor
person.prototype
object
“use strict" Object function(){
function person(nm,ag)
{ toString
inheritance
this.name=nm; walk
this.age=ag;
this.speak=function(){ obj1 name=raj
return " hello "+this.name age=80 function(){
} speak
alert(this.constructor)
return…
} x
person.prototype.walk=function(){ name=mona
return this.name+" can walk "; age=90
}
speak
person.prototype.toString= function(){
return this.name+ " "+this.age Every object has it’s own copy of variable. See the diagram
} Obj1 has its own member name , age , speak
var obj1=new person("raj",80); X has its own member name, age, speak
var x=new person("mona",90); When you add method using prototype it will not create a copy for every
document.write(obj1);//raj 80 object. You have to use function name dot prototype
document.write(obj1.speak());//hello raj Prototype is a keyword.
document.write(x);
document.writeln(x.speak()); person.prototype.toString= function(){
document.write(x.walk()); return this.name+ " "+this.age }
</script>
Difference: add method as instance member and add method through prototype
function person(nm,ag)
• Instance method is slow in performance as it will allocate
{ var x=“blue”;
memory for every object this.name=nm;
this.age=ag;
• Prototype method is provide better performance as it will this.speak=function(){
stored in separate memory block (virtual table) and every return " hello "+this.name+” ”+x

object will have same copy of function }


alert(this.constructor)
}
• Instance method can make use of private variable eg if you
person.prototype.walk=function(){
have declare var x in function person Instance method can have return this.name+" can walk ";
access to this variable }
person.prototype.toString= function(){
• Prototype method can not access variable declared in function return this.name+ " "+this.age

with var key word as scope of var will be within the function }
Call and apply
• With the call() method, you can write a method that can be used on different objects.
In a function definition, this refers to the "owner" of the function.
var objperson = { In the example above, this is the objperson object that "owns" the fullName
firstName:"John", function.
lastName: "Doe", In other words, this.firstName means the firstName property of this object.
fullName: function () {
return this.firstName + " " + this.lastName; var objperson = {
} fullName: function() {
} return this.firstName + " " + this.lastName;
objperson.fullName(); // Will return "John Doe" }
} objperson fullName Function
this(objperson1)
var objperson1 = {
The call() method is a predefined JavaScript method.
firstName:"John",
lastName: "Doe"
It can be used to invoke (call) a method with an owner
}
object as an argument (parameter). objperson1 Jone Mary
var objperson2 = {
firstName:"Mary", Doe Doe
With call(), an object can use a method belonging to objperson2
lastName: "Doe"
another object.
}
objperson.fullName.call(objperson1); // Will return "John Doe“
objperson.fullName.call(objperson2); // Will return "Mary
Doe"
Object
Window

function Function(){}
Person(){}
The call() Method with Arguments
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
console.log(person. fullName.call(person1, " Mumbai ", " india "))
The apply() is same as call bit this method takes arguments as an array.

var person = {
fullName: function(city, country) {
alert(this)
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
console.log(person. fullName.apply(person1,["Mumbai", "india"]))

In JavaScript strict mode, if the first argument of the apply() method is not an object, it becomes the owner (object) of the invoked function. In "non-strict"
mode, it becomes the global object.
TRY: no===‘’use strict” console.log(person. fullName.apply(this,[“Mumbai”,”india”])) here this will become window object
Inheritance older syntax has changed to extend
var obj1=new person("raj",80);
<script> console.log(obj1);
"use strict" document.write(obj1);
function person(nm,ag) var x=new person("mona",90);
{ console.log(x);
if(this instanceof person) document.write(x);
{
this.name=nm; //child class
this.age=ag; function child() Person
this.speak=function(){return "hello"} {
display
alert(this.constructor)
return this; } toString
} child.prototype=Object.create(person.prototype);
else
throw new TypeError("Check this is not a function"
);
} child
person.prototype.display=function(){ return "paren c
t classmethod data"; }
person.prototype.toString=function(){
return this.name+ " "+this.age
}
var c=new child(); //child got access to parent method
console.log(c.display());
document.write(c);
document.write(c.display());
</script>
Call has become super in new syntax
function child(nm,ag)
<script> {
"use strict"
function person(nm,ag) person.call(this,nm,ag);
{
if(this instanceof person) this.speak=function(){return " uh...ooooa uh ..oooa";};
{ this.name=nm;
this.age=ag;
alert(this.constructor)
return this; }
}
child.prototype=Object.create(person.prototype); //extends
else
child.prototype.walk=function(){ return " child can crawl "}
throw new TypeError("Check this is not a function");
var c=new child("rohan",60); //child got access to parent method
} console.log(c.display()); person Display
person.prototype.display=function(){ return " parent class
method data "; }
person.prototype.walk=function(){ return " Person can walk
console.log(c); toString
"}
person.prototype.toString=function()
document.write(c); walk
{return this.name+" "+this.age+" "+ this.walk()} document.write(c.display());
document.write(c.walk()); child
var obj1=new person("raj",80);
console.log(obj1); </script> name:Rohan
console.log(obj1.display());
document.write(obj1);
<pre> age=60
var x=new person("mona",90); <h3> we can use
c walk
console.log(x);
document.write(x); person.call(this,nm,ag);
ie. parent class name.call()
1st parameter refere to current object(1st parameter has to be of type
object
and rest value to initialised
)
</h3> </pre>
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Why closures
• Global variables can be made local (private) with closures.
counter <script>

<script> function add() {


let counter = 0; 0 1 2 3 let counter = 0;

function add() { counter += 1;


counter += 1; return counter;
return counter; }
}
document.write(add());
document.write(add()); document.write(add());
document.write(add()); document.write(add());
document.write(add()); </script>
</script>

In this example counter is local variable but


In this example counter is global now it will return 1 1 1 as counter get
variable so it may get modified initialised to 0 for each function call
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Nested function JavaScript supports nested functions. Nested functions
have access to the scope "above" them.

<script>
In this example, the inner function plus() has access to
function add() {
the counter variable in the parent function:
var counter = 0;
function plus()
{ This could have solved the counter dilemma, if we could
counter += 1; reach the plus() function from the outside.
}
plus(); We also need to find a way to execute counter = 0 only
return counter; <script> once.
}
Let Plus=function() {
document.write(add()); We need a closure.pus=
var counter = 0;
document.write(add());
</script> return function ()
{
return counter += 1;
}
}()
document.write(plus());
document.write(plus());
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


closures var add = (function () {
var counter = 0;
<!DOCTYPE html>
return function () {return counter += 1;
}
<html>
})();
<body>
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>//3 return function () {return counter += 1;}
<p id="demo">0</p>
<script>
var add = (function () { //2 add= function () {return counter += 1;} As soon as page gets loaded it will invoke
var counter = 0; above code[self invoking function and
return function () {return counter += 1;} counter will be initialized to 0. self
})(); //1 invoking function get called only one time
so it will initialised counter to 0 only
function myFunction(){//4
one time and add is now pointing to
document.getElementById("demo").innerHTML = add();//5 anonymous function returning counter
}
</script></body>
</html>
function myFunction(){
document.getElementById("demo").innerHTML = add();
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


New Window()
New Document()

document getElementById()

New ParagraphElement ()

innerHTML

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


ES6 introduce Class keyword Object
<script>
'use strict'
class Account
This.name=raj geeta
{
obj1 This.balance=20000
constructor(name,amt)
{
this.name=name; This.name=mona
this.balance=amt; obj2 This.balance=50000
alert(typeof this.constructor)
}
document.write(obj1); //object Object
}
Internally calling toString() method.
var obj1=new Account("raj",20000);
But Account class does not have this method
console.log(obj1);
So it will go to parent class and call parent’s toString()
document.write(obj1 instanceof Account);//true
method.
document.write(obj1 instanceof Object);//true
alert(typeof this.constructor)
obj1.name="geeta";
Above line says it is function So…
console.log(obj1);
Can I call Account() directly ?
document.write(obj1); //object Object
No you will get error
var obj2=new Account("Mona",50000);
document.write(obj2.name);
console.log(new Object());

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


When you use class key word
• Class methods are non-enumerable. A class definition sets enumerable flag to
false for all methods in the "prototype".
• That’s good, because if we use for..in over an object, we usually don’t want its
class methods.
• Classes always use strict. All code inside the class construct is automatically in
strict mode.
An important difference between function declarations and class declarations is that function declarations
are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise
code like the following will throw a ReferenceError:

const p = new Rectangle(); // ReferenceError


class Rectangle {}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
What is mean by enumerable
let person=function(nm,ag)
{ this.name=nm;
this.age=ag;
this.dojob=function() {
document.write("do-=== job hello<br/>");
}
}
let obj=new person("Raj",25);
obj.dojob()
document.write("<hr/>")
for(let prop in obj)
{ if(typeof obj[prop]==‘function’)
obj[prop]();
document.write(prop+" "+obj[prop]);
document.write("<hr/>")
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Class Expression <script>
person=function(){
<script>
Function person(){

this.sayhi= function (a){ this.sayhi= function (a){


alert(a) alert(a)
}; };
} }

• Just like functions, classes can be defined new person().sayhi("bye");


let obj=new person();
new person().sayhi("bye");
let obj=new person();
inside another expression, passed around, obj.sayhi("hello");
</script>
obj.sayhi("hello");
</script>
returned, assigned, etc.

obj sayhi
• Here’s an example of a class expression:
Alert()

let User = class {


new User().sayHi(); // works,
sayHi() { shows definition
alert("Hello"); new User()
}
}; sayHi()

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


We can even make classes dynamically “on-demand”, like this:
function makeClass(phrase) {
// declare a class and return it
return class
{ sayHi()
{ alert(phrase); };
};
}
// Create a new class
let User = makeClass("Hello"); class
{ sayHi()
new User().sayHi(); // Hello {
Let uobj=new User() alert(phrase); };
};
uobj.sayHi();

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
Add deposit and display method Object
'use strict' var obj1=new Account("raj",20000);
class Account console.log(obj1.display());
document.write(obj1.display());
{ deposit(amt){ }
constructor(name,amt) obj1.name="geeta"; Account
{ console.log(obj1.display()); display(){}
document.write(obj1.display());
this.name=name;
this.balance=amt; var obj2=new Account("Mona",50000);
console.log(obj2);
alert(typeof this.constructor) this.name=raj geeta
} console.log(new Object()); this.balance=20000
obj1
deposit(amt) document.write(new Object());
</script>
{ this.balance+=amt;
this.name=mona
} obj2 this.balance=50000
display()
{return this.name+ " " +this.balance}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Override to toString() method Object
<script>
'use strict' var obj1=new Account("raj",20000);
console.log(obj1); toString(){}
class Account
document.write(obj1);
{ console.log(obj1);
constructor(name,amt)
var obj2=new Account("Mona",50000); deposit(amt){ }
{
console.log(obj2);
this.name=name; </script>
this.balance=amt;
alert(typeof this.constructor) toString()
this.name=raj
} this.balance=20000
obj1
deposit(amt)
{ this.balance+=amt;
} this.name=mona
obj2 this.balance=50000
toString()
{return this.name+ " " +this.balance}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<script>
Getter setter method Object

'use strict'
class Account
{ var obj1=new Account("raj",20000);
constructor(name,amt) (1) console.log(obj1);
{ document.write(obj1);
this.Aname=name; (2) obj1.Aname="geeta"; //calling set
this.Abalance=amt; (4) console.log(obj1);
} document.write(obj1);
get Aname(){ return this._name; } document.write(obj1.Aname);
set Aname(value) { this._name=value; } (3) deposit(amt){ }
obj1.deposit(200);
get Abalance() { return this._balance; } </script> toString()
set Abalance(value) { this._balance=value; } (5) this._name=raj
this._balance=20000
obj1
deposit(amt)
{ get Aname(){
this.Abalance= this.Abalance +amt;
} set Aname(){

toString()
{ //calling get
return this.Aname+ " " +this.Abalance
}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Parent class Account
Inheritance Child
{ class Savingaccount extends Account Object
constructor(fname,lname,amt) {
{ this.firstname=fname; constructor(acctype,fname,lname,amt)
this.lastname=lname; { super(fname,lname,amt)
this.balance=amt; this.type=acctype; Account
}
}
deposit(amt){ }
set firstname(value) {this._fnm=value;} withdraw(amt)
get firstname(){ return this._fnm;} { const minbal=1000; toString()
if(amt>(this.balance-minbal))
get firstname(){
throw new TypeError("err");
set balance(value) {this._bal=value;}
this.balance-=amt; set firstname(){
get balance(){ return this._bal;}

}
set lastname(value) {this._lnm=value;} }
get lastname(){ return this._lnm;}
var obj=new Savingaccount ("sav","Raj","Mathur",2000) Savingaccount
deposit(amt) obj.deposit(2000); this._fnm=raj
{ this.balance+=amt; } document.write(obj); this.lnm-Mathur
obj.withdraw(3000); this_bal=2000 4000
document.write(obj); obj withdraw
toString() { return this.firstname+ " " + Type=sav
this.lastname+" "+this.balance}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Parent class Account
Inheritance Child
{ class Savingaccount extends Account Object
constructor(fname,lname,amt) {
{ this.firstname=fname; constructor(acctype,fname,lname,amt)
this.lastname=lname; { super(fname,lname,amt)
this.balance=amt; this.type=acctype; Account
}
}
Error("err"); deposit(amt){ }
set firstname(value) {this._fnm=value;} withdraw(amt)
get firstname(){ return this._fnm;} { const minbal=1000; toString()
if(amt>(this.balance-minbal))
new TypeError("err"); get firstname(){
throw new TypeError("err");
set balance(value) {this._bal=value;}
this.balance-=amt; set firstname(){
get balance(){ return this._bal;}

} e
set lastname(value) {this._lnm=value;} }
get lastname(){ return this._lnm;}
var obj=new Savingaccount ("sav","Raj","Mathur",2000) Savingaccount
deposit(amt) obj.deposit(2000); this._fnm=raj
{ this.balance+=amt; } document.write(obj); try{ this.lnm-Mathur
obj.withdraw(5000);} this_bal=2000 4000
catch(e){console.log(e.message)} obj withdraw
toString() { return this.firstname+ " " + Type=sav
document.write(obj);
this.lastname+" "+this.balance}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Parent
class Account
{
Abstract classChild
constructor(fname,lname,amt) class Savingaccount extends Account Object
{ {
alert(new.target) constructor(acctype,fname,lname,amt)
if (new.target === Account) { super(fname,lname,amt)
{ this.type=acctype; Account
throw new TypeError("Cannot construct Abstract
instances directly");
} }
deposit(amt){ }
this.firstname=fname; withdraw(amt)
this.lastname=lname; { const minbal=1000; toString()
this.balance=amt;
if(amt>(this.balance-minbal))
} get firstname(){
set firstname(value) {this._fnm=value;} throw new TypeError("err");
get firstname(){ return this._fnm;} this.balance-=amt; set firstname(){
set balance(value) {this._bal=value;}
} obj1
get balance(){ return this._bal;}
} this._fnm=raj
set lastname(value) {this._lnm=value;} this.lnm-Mathur
get lastname(){ return this._lnm;}
var Aobj=new Account (”Raj","Mathur",2000)
deposit(amt) //ERRRR this_bal=20000
{ this.balance+=amt; } Type=sav
toString() { return this.firstname+ " " + this.lastname+" var obj=new Savingaccount ("sav","Raj","Mathur",2000)
"+this.balance}
}
obj.deposit(2000); withdraw
document.write(obj);
obj.withdraw(3000);
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
class SavingAccount extends Account
{ constructor(name,amount)
{ super(name,amount);
} var ca1=new SavingAccount("Vidya",90000);
<script> console.log(ca1);
'use strict' withdrow(amt) ca1.deposit(8000);
class Account { const minbal=10000; document.write(ca1);
{ ca1.withdrow(70000);
static accid() var b=this.Abalance-amt document.write(ca1);
{ Account.dd=++Account.dd||1; if(b<minbal) document.write("<hr/>");
return Account.dd; {throw new Error("insufficiant balance");} for(var x in ca1)
} this.Abalance-=amt; document.write(ca1[x]);
constructor(name,amt) } </script>
{ alert(new.target)
if (new.target === Account) { }
throw new TypeError("Cannot construct Abstract instances Let obj=new Account(“raj”,20000);
directly"); var sa1=new SavingAccount("Raj",50000);
} console.log(sa1);
document.write(sa1);
this.Aname=name; var sa2=new SavingAccount("manali",90000);
this.Abalance=amt; console.log(sa2);
this._id= Account.accid(); document.write(sa2);
} sa2.Aname="vita";
get Aname(){ return this._name; } console.log(sa2.hasOwnProperty("Aname"));
set Aname(value) { this._name=value; } console.log(sa2.hasOwnProperty("_name"));
var oba=new Account("Geeta",5000);
get Abalance() { return this._balance; }
set Abalance(value) { this._balance=value; } class currentAccount extends Account
deposit(amt) {
{this.Abalance+=amt; constructor(name,amount)
} { super(name,amount);
get Aid(){return this._id;} }
toString() withdrow(amt)
{return this.Aname+ " " { this.Abalance-=amt;
+this.Abalance+"id="+ this.Aid} }

USM’s Shriram Mantri Vidyanidhi


} Info Tech Academy
'use strict'
documet.write("hello");
window.document.write("hellow")
Document
Window
window
document
write

alert open

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Calling member method
class MyMath
{
obj=new MyMath(3);
constructor(number) console.log(obj.sqr());
{ console.log(obj.cube())
this.no=number;
}
sqr()
{ let s=this.no*this.no; obj
no=3 sqr()
return s;
} cube()
cube()
{
let q= this.sqr()*this.no
return q;
}
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Static method External Memory
static add(a,b)
<script> static sqr(a)
'use strict'
class mymaths
{
static add(a,b)
{
return a+b;
}
static sqr(a)
{ return a*a; }
}
document.write(mymaths.add(3,5));
document.write(mymaths.sqr(3));
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


const module = {
x: 42, X=42
getX: function() { module getX this.x
return this.x;
} Window
};
const unboundGetX = module.getX; unboundGetX
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);


console.log(boundGetX());
// expected output: 42
console.log( module.getX.call(module))

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Vita{
Class DAC{

}
Vita.DAC
Import vita from ‘./vita’

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
‘use strict'
ES8 #--private variable Object
class Account
{ #name;
#balance; this.#name=raj
constructor(name,amt) this.#balance=20000
{
this.#name=name; obj1
this.#balance=amt; this.#name=mona
alert(typeof this.constructor) obj1 this.#balance=50000
}
toString()
{return `Name=${this.#name} document.write(obj1); // //geeta 20000
Bal=${this.#balance}` Internally calling toString() method.
} - Account class does have this method
} So it will call toString() method.
/*toString() alert(typeof this.constructor)
{return “Name=“+this.#name+ “Bal=“+this.#balance;}*/
Above line says it is function So…
var obj1=new Account("raj",20000);
Can I call Account() directly ?
console.log(obj1);
document.write(obj1 instanceof Account);//true
No you will get error
document.write(obj1 instanceof Object);//true Default value in private instance member?
//obj1.#name="geeta"; Undefined
console.log(obj1); Can I access #name out side class?
document.write(obj1); //geeta 20000 NO
var obj2=new Account("Mona",50000); Uncaught SyntaxError: Private field '#name' must be
console.log(new Object()); declared in an enclosing class
</script> USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<script> Object
‘ use strict'
class Account
ES8 _--protected variable
{ _name; obj1
this.name=raj geeta
this.balance=20000
_balance;
constructor(name,amt) this.name=mona
obj2
{ this._name=name; this.balance=50000

this._balance=amt; document.write(obj1); // //geeta 20000


alert(typeof this.constructor) Internally calling toString() method.
} - Account class does have this method
toString() So it will call toString() method.
{return `Name=${this._name} Bal=${this._balance}` } alert(typeof this.constructor)
Above line says it is function So…
} Can I call Account() directly ?
var obj1=new Account("raj",20000); No you will get error
console.log(obj1);
document.write(obj1 instanceof Account);//true Default value in private instance member?
document.write(obj1 instanceof Object);//true Undefined
obj1._name="geeta"; _name is available out side the class but need no use.
document.write(obj1); //object Object Use it only in child class
var obj2=new Account("Mona",50000); Is instance member required [above constructor] ?
</script> No
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Parent class Account Inheritance Child _protected
{ _firstname; class Savingaccount extends Account Object
_lastname; {type=acctype;
constructor(acctype,fname,lname,amt)
_balance; { super(fname,lname,amt)
constructor(fname,lname,amt) this.type=acctype; Account
{ this.firstname=fname;
this.lastname=lname;
this.balance=amt; }
deposit(amt){ }
} withdraw(amt)
{ const minbal=1000; toString()
set firstname(value) {this._firstname=value;}
if(amt>(this.balance-minbal)) get firstname(){
get firstname(){ return this._firstname;}
throw new TypeError("err");
set balance(value) {this._balance=value;} this.balance-=amt; set firstname(){
get balance(){ return this._balance;}
}
set lastname(value) {this._lastname=value;}
} Savingaccount
get lastname(){ return this._lastname;} var obj=new Savingaccount ("sav","Raj","Mathur",2000)
obj.deposit(2000);
withdraw
document.write(obj);
deposit(amt) this. ._firstname =raj
{ this. balance +=amt; } obj.withdraw(500);
document.write(obj); this. ._lastname -Mathur
toString() { return this.firstname+ " " + document.write(obj.balance); obj1
this.lastname+" "+this.balance} Obj.balance=50000; this. ._balance =20000
} this.Type=sav
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<script> ‘use strict’
Complete application class Savingaccount extends Account
class Account { { type;
#firstname; #lastname; constructor(acctype,fname,lname,amt)
#balance; #id;
{ super(fname,lname,amt)
static #aid=0;
constructor(fname,lname,amt)
this.type=acctype;
{ this.firstname=fname; }
this.lastname=lname;
this. _cbalance =amt; withdraw(amt)
this.#id=++Account.#aid; { const minbal=1000;
} if(amt>(this._cbalance-minbal))
throw new TypeError("err");
set firstname(value) {this.#firstname=value;} this._cbalance=this._cbalance-amt;
get firstname(){ return this.#firstname;}

}
set _cbalance(value) {this.#balance=value;}
get _cbalance(){ return this.#balance;}
}

set lastname(value) {this.#lastname=value;} var obj=new Savingaccount ("sav","Raj","Math


get lastname(){ return this.#lastname;} ur",2000)
get gid(){ return this.#id;} obj.deposit(2000);
deposit(amt) document.write(obj);
{ this. _cbalance +=amt; }
obj.withdraw(500);
toString() { return this.gid + " "+ this.firstname+ " " + this.lastn
document.write(obj);
ame+" "+this._cbalance} //obj.gid=101;
} USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Object

External memory
Static aid =0 1 2
Account Static coname=“vidyanidhi”
Static rateofint=0.08
Static payinterest( obj)
deposit(amt){ }
obj
toString()
get firstname(){

set firstname(){

Savingaccount

withdraw
this. .firstname =raj
obj this. .lastname -Mathur
this. ._balance =20000
This.#id=1
this.Type=sav

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


In the above example we have declare static variable to generate account id.
this.#id=++Account.aid;
In the above line we can access static variable with class name.
get gid(){ return this.#id;}
We have written only getter property as user can read Id but can not set it. Generally account number is given by bank.
We have declare instance member private in a class and achieve data hiding, encapsulation.
set _cbalance(value) {this.#balance=value;}
get _cbalance(){ return this.#balance;}

We purposely declared get set _cbalance so that programmer should not use this variable outside the
class. But only child class can access it.
In bank you can read balance but you can not set balance. So should I write getter only?? Think how you
will set value when user deposit money?
So you need getter and setter both. You just want to ensure that it should be available only to child
class. So we are using _balance so that it is reminder to programmer that this variable need not used
outside class.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Private method/private static variable
Private instance methods

Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields.
<script>
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world'
}

getPrivateMessage() {
return this.#privateMethod()
}
}

const instance = new ClassWithPrivateMethod()


console.log(instance.getPrivateMessage())
// expected output: "hello world"
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Private getters and setters are also possible:

class ClassWithPrivateAccessor {
#message

get #decoratedMessage() {
return `${this.#message}`
}
set #decoratedMessage(msg) {
this.#message = msg
}

constructor() {
this.#decoratedMessage = 'hello world'
console.log(this.#decoratedMessage)
}
}
let Obj=new ClassWithPrivateAccessor();

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


the limitation of static variables being called by only static methods still holds.

class ClassWithPrivateStaticField {
static #PRIVATE_STATIC_FIELD

static publicStaticMethod() {
ClassWithPrivateStaticField.#PRIVATE_STATIC_FI
ELD = 42
return ClassWithPrivateStaticField.#PRIVATE_ST
ATIC_FIELD
}
}

console.log(ClassWithPrivateStaticField.publicStaticMethod() ===
42)

Private static fields are added to the class constructor at class evaluation time.

There is a provenance restriction on private static fields. Only the class which defines the
private static field can access the field.

This can lead to unexpected behavior when using this.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Private static methods
Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only
accessible from inside the class declaration.
Private static methods may be generator, async, and async generator functions.

class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
return 42
}

static publicStaticMethod1() {
return ClassWithPrivateStaticMethod.#privateStaticMethod();
}

static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
console.log(ClassWithPrivateStaticMethod.publicStaticMethod1() === 42);
console.log(ClassWithPrivateStaticMethod.publicStaticMethod2() === 42);

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


This can lead to unexpected behavior when using this. In the following example
this refers to the Derived class (not the Base class) when we try to call
Derived.publicStaticMethod2(), and thus exhibits the same "provenance
restriction" as mentioned above:

class Base {
static #privateStaticMethod() {
return 42;
}
static publicStaticMethod1() {
return Base.#privateStaticMethod();
}
static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
class Derived extends Base {}
console.log(Derived.publicStaticMethod1()); // 42
console.log(Derived.publicStaticMethod2()); // TypeError

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


yield 0 1 2 3 4
sides 1 2 3 4 5
class Polygon {
constructor(...sides) {
this.sides = sides;
} pentagon
// Method *getSides()
*getSides() {
for(const side of this.sides){
yield side;
}
}
}

const pentagon = new Polygon(1,2,3,4,5);

console.log([...pentagon.getSides()]); // [1,2,3,4,5]

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
function* generateSequence() {
yield 1;
• The yield keyword pauses generator function yield 2;
execution and the value of the expression following yield 3;
the yield keyword is returned to the generator's }
caller. It can be thought of as a generator-based let sequence = [...generateSequence()];
version of the return keyword. ... A yield ,
alert(sequence); // 0, 1, 2, 3
which causes the generator to once again
pause and return the generator's new value. </script>

console.log(generateSequence())

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script>
generator
class MyClass {
Next()
*createIterator() { Return()
yield 1; Throw()
MyClass
yield 2;
yield 3; instance *createIterator()
}
}
let instance = new MyClass();
let iterator = instance.createIterator();
console.log(iterator);
let one=iterator.next(); Can I use loop= Yes
alert(JSON.stringify(one));
let two=iterator.next();
alert(JSON.stringify(two)); for(let x of iterator)
alert(x)
let three=iterator.next();
alert(JSON.stringify(three));
let four=iterator.next();
alert(JSON.stringify(four));
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
var cc=new Company();

var i= cc.crIterator();
class Company console.log(i)
{ constructor() for(let x of i)
{ this.x=new Array() document.write(x);
this.x[0]=new Employee("Raj",1);
this.x[1]=new Employee("Mona",2);
this.x[2]=new Employee("Geeta",3);
}
*crIterator() {
yield *this.x;
}
}
new Company();
cc
class Employee *crIterator() 0 1 2
{ constructor(nm,id) this.x
{this.name=nm;
this.id=id;
}
toString() Name=Mo
{return this.name+ " "+this.id; } Name=Raj Name=Geeta
na
} Id=1 Id=3
Id=2

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Can I write iterator manually
<script>
class MyIterator {
constructor() {
this.i=0;
this.step = new Array(1,2);
}
[Symbol.iterator]() {
return this;
}
next() {
if(this.i<this.step.length)
{
return this.step[this.i++];
}
return {done: true};
}
}
let iter = new MyIterator();
console.log(iter.next());
console.log(iter.next());
// output: {done: true}
console.log(iter.next());
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Optional chaining '?.' • The “non-existing property” problem
As an example, let’s say we have user objects that hold the information about our users.
Most of our users have addresses in user.address property, with the street user.address.street, but some did not provide
them.
In such case, when we attempt to get user.address.street, and the user happens to be without an address, we get an error:

let user = {}; // a user without "address" property address


street
alert(user.address.street); // Error!

That’s the expected result. JavaScript works like this. As user.address is undefined, an attempt to get user.address.street fails
with an error.

In many practical cases we’d prefer to get undefined instead of an error here (meaning “no street”).
…And another example. In the web development, we can get an object that corresponds to a web page element using a
special method call, such as document.querySelector('.elem'), and it returns null when there’s no such element.

// document.querySelector('.elem') is null if there's no element


let html = document.querySelector('.elem').innerHTML; // error if it's null

Once again, if the element doesn’t exist, we’ll get an error accessing .innerHTML of null. And in some cases, when the absence
of the element is normal, we’d like to avoid the error and just accept html = null as the result.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


How can we do this?
The obvious solution would be to check the value using if or the conditional operator ?, before accessing its property,
like this:

let user = {}; address street


user
alert(user.address ? user.address.street : undefined);

It works, there’s no error… But it’s quite in elegant. As you can see, the "user.address" appears twice in the code. For
more deeply nested properties, that becomes a problem as more repetitions are required.

E.g. let’s try getting user.address.street.name.

We need to check both user.address and user.address.street:


let user = {}; // user has no address
alert(user.address ?(user.address.street ? user.address.street.name : null ): null);

That’s just awful, one may even have problems understanding such code.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Optional chaining
The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.
Further in this article, for brevity, we’ll be saying that something “exists” if it’s not null and not undefined.
In other words, value?.prop: works as value.prop, if value exists,
otherwise (when value is undefined/null) it returns undefined.
Here’s the safe way to access user.address.street using ?.:
let user = {}; // user has no address
alert( user?.address?.street ); // undefined (no error)

The code is short and clean, there’s no duplication at all.


Reading the address with user?.address works even if user object doesn’t exist:

let user = null;


alert( user?.address ); // undefined
alert( user?.address.street ); // undefined

Please note: the ?. syntax makes optional the value before it, but not any further.
E.g. in user?.address.street.name the ?. allows user to safely be null/undefined (and returns undefined in that case), but that’s only for
user. Further properties are accessed in a regular way. If we want some of them to be optional, then we’ll need to replace more . with ?..

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• The variable before ?. must be declared
• If there’s no variable user at all, then user?.anything triggers an error:
• // ReferenceError: user is not defined
• user?.address;

• The variable must be declared (e.g. let/const/var user or as a function


parameter). The optional chaining works only for declared variables.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Short-circuiting
As it was said before, the ?. immediately stops (“short-circuits”) the evaluation if the left part doesn’t exist.
So, if there are any further function calls or side effects, they don’t occur.
For instance:
let user = null;

let x = 0;

user?.sayHi(x++); // no "sayHi", so the execution doesn't reach x++

alert(x); // 0, value not incremented

Other variants: ?.(), ?.[]


The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets.
For example, ?.() is used to call a function that may not exist.
In the code below, some of our users have admin method, and some don’t:
let userAdmin = {

admin() {

alert("I am admin");

};

let userGuest = {};

userAdmin.admin?.(); // I am admin

userGuest.admin?.(); // nothing (no such method)

Here, in both lines we first use the dot (user1.admin) to get admin property, because the user object must exist, so it’s safe read from it.
Then ?.() checks the left part: if the admin function exists, then it runs (that’s so for user1). Otherwise (for user2) the evaluation stops
without errors.
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
The ?.[] syntax also works, if we’d like to use brackets [] to access properties instead of dot .. Similar to
previous cases, it allows to safely read a property from an object that may not exist.
let key = "firstName";
let user1 = {
firstName: "John"
};
let user2 = null;
alert( user1?.[key] ); // John
alert( user2?.[key] ); // undefined

Also we can use ?. with delete:


delete user?.name; // delete user.name if user exists
We can use ?. for safe reading and deleting, but not writing
The optional chaining ?. has no use at the left side of an assignment.
For example:
let user = null;
user?.name = "John"; // Error, doesn't work
// because it evaluates to undefined = "John"

It’s just not that smart.


USM’s Shriram Mantri Vidyanidhi Info Tech Academy
The optional chaining ?. syntax has three forms:

obj?.prop – returns obj.prop if obj exists, otherwise undefined.


obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
obj.method?.() – calls obj.method() if obj.method exists, otherwise
returns undefined.

As we can see, all of them are straightforward and simple to use. The
?. checks the left part for null/undefined and allows the evaluation to
proceed if it’s not so.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The nullish coalescing operator is written as two question marks ??.

The result of a ?? b is:


if a is defined, then a,
if a isn’t defined, then b.
In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one.
The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the
two.
We can rewrite result = a ?? b using the operators that we already know, like this: function add(a,b)
{
b=b||1;
result = (a !== null && a !== undefined) ? a : b;
The common use case for ?? is to provide a default value for a potentially undefined variable. let r=a+b;
}
For example, here we show Anonymous if user isn’t defined:
let user; function add(a,b)
alert(user ?? "Anonymous"); // Anonymous {
b=b??1;
Of course, if user had any value except null/undefined, then we would see it instead:
let user = "John"; let r=a+b;
alert(user ?? "Anonymous"); // John }
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
The important difference between them is that:
Comparison with || || returns the first truthy value.
The OR || operator can be used in the same way ?? returns the first defined value.
For example, in the code above we could replace ?? with || and
still get the same result: In other words, || doesn’t distinguish between false, 0, an
let firstName = null;
empty string "" and null/undefined. They are all the same –
falsy values. If any of these is the first argument of ||, then we’ll
let lastName = null; get the second argument as the result.
let nickName = "Supercoder"; In practice though, we may want to u
// shows the first truthy value:
let height = 0;
alert(firstName || lastName || nickName || "Anonym
ous"); // Supercoder alert(height || 100); // 100
alert(height ?? 100); // 0

The height || 100 checks height for being a falsy value, and it
really is.
The OR || operator exists since the beginning of JavaScript, so so the result is the second argument, 100.
developers were using it for such purposes for a long time. The height ?? 100 checks height for being null/undefined,
and it’s not,
On the other hand, the nullish coalescing operator ?? was added to so the result is height “as is”, that is 0.
JavaScript only recently, and the reason for that was that people
weren’t quite happy with ||. If the zero height is a valid value, that shouldn’t be replaced
with the default, then ?? does just the right thing.
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Precedence
The precedence of the ?? operator is rather low: 5 in the MDN table. So ?? is evaluated before = and ?, but after most other
operations, such as +, *.

So if we’d like to choose a value with ?? in an expression with other operators, consider adding parentheses:
let height = null;
let width = null;

// important: use parentheses


let area = (height ?? 100) * (width ?? 50);
alert(area); // 5000

Otherwise, if we omit parentheses, then as * has the higher precedence than ??, it would execute first, leading to incorrect results.
// without parentheses
let area = height ?? 100 * width ?? 50;

// ...works the same as this (probably not what we want):


let area = height ?? (100 * width) ?? 50;

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Using ?? with && or ||

Due to safety reasons, JavaScript forbids using ?? together with && and || operators, unless the precedence is explicitly specified with
parentheses.

The code below triggers a syntax error:

• let x = 1 && 2 ?? 3; // Syntax error


The limitation is surely debatable, but it was added to the language specification with the purpose to avoid programming mistakes, when
people start to switch to ?? from ||.

Use explicit parentheses to work around it:

let x = (1 && 2) ?? 3; // Works

alert(x); // 2

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Summary??

• The nullish coalescing operator ?? provides a short way to choose the first
“defined” value from a list.

• It’s used to assign default values to variables:

• // set height=100, if height is null or undefined


• height = height ?? 10;

• The operator ?? has a very low precedence, only a bit higher than ? and =, so consider
adding parentheses when using it in an expression.

• It’s forbidden to use it with || or && without explicit parentheses.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Window class has many methods

Lets discuss some of it


Open, close, alert, prompt, confirm
isNaN, isFinite,eval
setInterval, clearInterval
setTimeOut, clearTimeOut
Location is getter/setter

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Open
function callme()
{

window.open('p.html')

function tool()
{

window.open('p.html','_blank','height=
200,width=200')
}
Open will open new file in current window by default.
If you add second parameter _blank then it will open file in a new tab

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Definition and Usage
The open() method is used to open a new browser window.
Syntax

window.open(URL,name,specs)

Parameter Description
URL Optional. Specifies the URL of the page to open. If no URL is specified, a new window with about:blank is opened
name Optional. Specifies the target attribute or the name of the window. The following values are supported:

 _blank - URL is loaded into a new window. This is default

 _self - URL replaces the current page

 name - The name of the window


specs Optional. A comma-separated list of items. The following values are supported:
fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode
height=pixels The height of the window. Min. value is 100
left=pixels The left position of the window
menubar=yes|no|1|0 Whether or not to display the menu bar. Default is yes
resizable=yes|no|1|0 Whether or not the window is resizable. Default is yes
scrollbars=yes|no|1|0 Whether or not to display scroll bars. Default is yes
status=yes|no|1|0 Whether or not to add a status bar. Default is yes
titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. Default is yes
toolbar=yes|no|1|0 Whether or not to display the browser toolbar. Default is yes
top=pixels The top position of the window
width=pixels The width of the window. Min. value is 100

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<html>
Prompt
<head><title>template</title>
<script>
var no1=window.prompt("enter number",5);
var b=parseInt(no1);
var no2=prompt();
document.write(no1+no2);//string +(concat)number
document.write("<br/>");
document.write(no1*no2);//no1.valueOf() get called
document.write("<br/>");
document.write(typeof(no1));//string
pno1=parseInt(no1);
pno2=parseInt(no2);
var ans=pno1+pno2;
document.write(ans);
document.write("<br/>");
document.write(no1*no2);
</script></head><body>
prompt("sometext","defaultvalue");
</body></html> USM’s Shriram Mantri Vidyanidhi Info Tech Academy
alert
<html> <html>
<head><title>template</title> <head><title>template</title>
<script> <script>
alert("hello <br/> world") alert=function(a)
alert("hello \n world") {
</script> document.write(a);
</head> }
<body> alert(“hello”)
</body> </script>
</html> </head>
<body>
</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<html>
Confirm
<head><title>template</title>
<script>
a=confirm("do you want to continue");
alert(a);
</script>
</head>
<body>
</body>
</html>

If user click on ok it will return true


If you click on cancel it will return false

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Location: To redirect user
<html>
<head>
<script type="text/javascript">
function newLocation()
{
window.location="p.html";
}
</script>
</head>
<body>
<input type="button" id="btn" value="Change URL">
<script>
document.getElementById("btn").addEventListener("click",newLocation,false);
</script>
</body>

</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


resizeBy-moveBy resizeTo-moveTo
<html> resizeTo-moveTo will work only one time as it is set to some value
<head>
<script type="text/javascript"> resizeBy-moveBy is relative to current value so it will keep
function resizeWindow() increasing by some value compare to previous value
{ window.resizeBy(50,50) }
Works only in IE
window.moveBy(50,50)
</script>
</head>
<body>
<input type="button" onclick="resizeWindow()"
value="Resize window">

</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


t= setInterval("alert('hi')",1000); //keep executeing
after 1000 millisecond
//clearInterval(t)

t=setTimeout("alert('hi')",6000); //execute one time


after 60000 millisecond
alert(t);
//clearTimeout(t);

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Eval=Evaluate expresstion 5+2-3*6/2
5+2-18/2
5+2-9
<html> //CSRF XSS 7-9
-2
<head><title>template</title>
<script>
a="5+2-3" <!doctypehtml>
<html><head><script>
document.write(a) var i;
document.write("<br>"+eval(a))//4 var no1=prompt("enter no1","5");
document.write("<br>"+eval("5+2-3*6/2")) var no2=prompt("enter no2","5");
var no3=prompt("enter no3","5");
document.write("<br>"+eval("55+6")) var no4=prompt("enter no4","5");
</script> var no5=prompt("enter no5","5");
for(i=1;i<=5;i++)
</head> {document.write("no"+i);
<body> document.write(eval("no"+i));
</body> //document.write("<hr/>");
document.write("</br>");
</html> }
</script>
</head>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy </html>
Scrolling a window

win.scrollBy(x,y)
• Scroll the window x pixels right and y down relative the current scroll.
Negative values are allowed.

win.scrollTo(x,y)
• Scroll the window to the given coordinates (x,y).

elem.scrollIntoView(top = true)
• Scroll the window to make elem show up at the top (the default) or at the
bottom for elem.scrollIntoView(false).

• There’s also window.onscroll event.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Scrolling: scrollTo, scrollBy, scrollIntoView
Important:
To scroll the page with JavaScript, its DOM must be fully built.
For instance, if we try to scroll the page with a script in <head>, it won’t work.
Regular elements can be scrolled by changing scrollTop/scrollLeft.
We can do the same for the page using
document.documentElement.scrollTop/scrollLeft (except Safari, where document.body.scrollTop/Left should be used instead
Alternatively, there’s a simpler, universal solution: special methods
window.scrollBy(x,y)
And
window.scrollTo(pageX,pageY).

•The method scrollBy(x,y) scrolls the page relative to its current position.
•For instance, scrollBy(0,10) scrolls the page 10px down.

<button onclick="window.scrollBy(0,10)">window.scrollBy(0,10)</button>

•The method scrollTo(pageX,pageY) scrolls the page to absolute coordinates,


<button onclick="window.scrollTo(0,0)">window.scrollTo(0,0)</button>

•so that the top-left corner of the visible part has coordinates (pageX, pageY) relative to the document’s top-left corner.
•It’s like setting scrollLeft/scrollTop.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


To scroll to the very beginning, we can use scrollTo(0,0).
These methods work for all browsers the same way.

scrollIntoView

For completeness, let’s cover one more method: elem.scrollIntoView(top).

The call to elem.scrollIntoView(top) scrolls the page to make elem visible. It has one argument:
•If top=true (that’s the default), then the page will be scrolled to make elem appear on the top of the window.

•The upper edge of the element will be aligned with the window top.

•If top=false, then the page scrolls to make elem appear at the bottom. The bottom edge of the element will be
aligned with the window bottom.

The button below scrolls the page to position itself at the window top:
<button onclick="this.scrollIntoView()">this.scrollIntoView()</button>

And this button scrolls the page to position itself at the bottom:
<button onclick="this.scrollIntoView(false)">this.scrollIntoView(false)</button>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Forbid the scrolling

Sometimes we need to make the document “unscrollable”. For instance, when we need to cover the page with a large message
requiring immediate attention, and we want the visitor to interact with that message, not with the document.

To make the document unscrollable, it’s enough to set

document.body.style.overflow = "hidden".
<button onclick="document.body.style.overflow = 'hidden'">document.body.style.overflow = ‘hidden’</button>

The page will “freeze” at its current scroll position.

document.body.style.overflow = “ ".
<button onclick="document.body.style.overflow = ''">document.body.style.overflow = ‘’</button>

The first button freezes the scroll, while the second one releases it.

We can use the same technique to freeze the scroll for other elements, not just for document.body.

The drawback of the method is that the scrollbar disappears. If it occupied some space, then that space is now free and the content
“jumps” to fill it.

That looks a bit odd, but can be worked around if we compare clientWidth before and after the freeze.

If it increased (the scrollbar disappeared), then add padding to document.body in place of the scrollbar to keep the content width the same.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
DOM

Document Object Model


DOM Nodes
• The DOM says:
• The entire document is a document node
• Every HTML element is an element node
• The text in the HTML elements are text nodes
• Every HTML attribute is an attribute node
• Comments are comment nodes
Show parent child relation ship
• <html> html
<head>
<title>DOM Tutorial</title>
</head> body
<body> head
<h1>DOM Lesson one</h1>
<p>Hello title h1 p
<span>world<span>!
</p> TextNode
</body> Hello span
</html>
Text is Always Stored in Text Nodes

• A common error in DOM processing is to expect an


element node to contain text.
• However, the text of an element node is stored in a
text node.
• In this example: <title>DOM Tutorial</title>, the
element node <title>, holds a text node with the value
"DOM Tutorial".
• "DOM Tutorial" is not the value of the <title> element!
• However, in the HTML DOM the value of the text node
can be accessed by the innerHTML property.
HTML DOM Properties

• Some DOM properties:


• x.innerHTML - the text value of x
• x.nodeName - the name of x
• x.nodeValue - the value of x
• x.parentNode - the parent node of x
• x.childNodes - the child nodes of x
• x.attributes - the attributes nodes of x
• Note: In the list above, x is a node object (HTML
element).
HTML DOM Methods

• Some DOM methods:


• x.getElementById(id) - get the element with a
specified id
• x.getElementsByTagName(name) - get all
elements with a specified tag name
• x.appendChild(node) - insert a child node to x
• x.removeChild(node) - remove a child node from
x
• Note: In the list above, x is a node object (HTML
element).
nodeName
• The nodeName property specifies the name of a
node.
• nodeName is read-only
• nodeName of an element node is the same as the
tag name
• nodeName of an attribute node is the attribute
name
• nodeName of a text node is always #text
• nodeName of the document node is always
#document
nodeType

Element type NodeType


Element 1
Attribute 2
Text 3
Comment 8
Document 9
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
DOM

Document Object Model


getElementById("pr") returns Object
<html><head><script type="text/javascript">
function callme()
{let s=document.getElementById("pr")
alert(s);//Object ParagraphElement
alert(s.nodeName) //name of node here is p tag
alert(s.childNodes[0].nodeValue) //1st child ka data
alert(s.childNodes[0].nodeName)//#text
alert(s.childNodes[0].nodeType)//3
alert(s.innerHTML); //entire data between tag P tag
</script></head><body>
<p onmouseOver="callme()" id="pr">Welcome<b> to world of</b> Dom</p>
</body>
</html> alert(s.childNodes[1]. childNodes[0].nodeValue)

p
#text nodeValue
0
[welcome]
1 <b>
nodeValue
#text[3]
[to world of]
2 #text nodeValue
[DOM]
<html><head></head>
<body>
<p id="cp">hello</p>
Create div tag and
<input type="button" value="copy" onclick="call()"/> type your name
<p id="pr"></p> On mouse over copy
your name in to h1
<script> tag
function call()
{
var x=document.getElementById("cp"); <p id=“pp”> hello<b>bye</b></p>
var y=document.getElementById("pr");
y.innerHTML=x.innerHTML
Using DOM and read “bye” value and
} display in div tag
</script>
</body>
</html>

x <p id="cp">hello</p>

y <p id="pr"> </p>


getElementsByTagName("p") returns array of Object p
<html><head><script type="text/javascript">
function callme()
{let s=document.getElementsByTagName("p"); //$(‘p’) Read 5 p tag and
let l=s.length; display in div tag
for(i=0;i<l;i++)
{alert(s[i].innerHTML)}

}
</script></head><body>
<input type="button" onclick="callme()" value="clickme"/>
<p>Welcome<b> to world of</b> Dom</p>
<p>2nd p</p>
<p>3rd p</p>
</body>
</html>

0 1 2

<p>Welcome<b> to world of</b> <p>2nd p</p> <p>3rd p</p>


Dom</p>

s
Be careful
<html><head></head><body>
<script type="text/javascript"> Order of execution is top to
let s=document.getElementsByTagName("p");
bottom
let l =(s.length);
for(i=0;i<l;i++)
{
document.write(s[i].innerHTML+"</br>")
}
</script>
<p>Welcome<b> to world of</b> Dom</p>
<p>2nd p</p>
<p>3rd p</p>

</body>
</html>
Read Value of TextBox
<html><head><script>
function readtext()
{
let a=document.getElementById("nm1")
let b=document.getElementById("nm2")
b.value=a.value
//alert(document.getElementById("pp").value);
//alert(document.getElementById("pp").childNodes[0].nodeValue);
}
</script></head><body>
<p id="pp">hello</p>
<form name="frm">
<input type="text" id="nm1"/>
<input type="button" value="read" onclick="readtext()">
<input type="text" id="nm2"/>
</form> Create 2 textarea and one checkbox
</body> Onclick of check box it should copy address
</html> from one text area to another
classList
0 1 2

.mystyle { .anotherClass .myClass {


width: 500px; { text-align: center;
height: 50px; background-color: bisque; font-size: 25px;
} } color: black;
margin-bottom: 10px;
}

x
var x = document.getElementById("myDIV").classList;

<div id="myDIV" class="mystyle anotherClass myClass">


I am a DIV element with multiple classes
</div>
<!DOCTYPE html>
<html><head><style>
.mystyle {
classList
width: 500px;
height: 50px;
}
You can dynamically read css
.anotherClass {
background-color: bisque;
class using classList property of
} a object[Tag]
.myClass {
text-align: center;
font-size: 25px;
color: black;
margin-bottom: 10px;
}
</style></head><body>

<p>Click the button to display the class names of the div element.</p>

<div id="myDIV" class="mystyle anotherClass myClass">


I am a DIV element with multiple classes
</div>

<button onclick="myFunction()">Try it</button>


<p><strong>Note:</strong> The classList property is not supported in Intern
et Explorer 9 and earlier versions.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myDIV").classList;
alert(x.length);
alert(x[0]) ;
document.getElementById("demo").innerHTML = x;
} </script>
getElementsByClassName("example");
<!DOCTYPE html>
<html><body>
<ul class="example"> 0 1
<li class="child">Coffee</li> Example Example
<li class="child">Tea</li> <ul class="example"> <ul class="example">
</ul>
<ul class="example"> 0 1 0 1
<li class="child">bun</li>
<li class="child">ice-cream</li> child Child Child Child
</ul> Coffee Tea bun ice-cream
<p>Click the button to change the text of
the first list item (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method
is not supported in Internet Explorer 8 and earlier versions
.</p>

<script>
function myFunction() {
var list = document.getElementsByClassName("example");
alert(list.length)
list[0].getElementsByClassName("child")[0].innerHTML = "Milk"
;
}
</script>

</body>
</html>
classList.add("anotherClass"): allow you to add css class
to a tag
<div id="myDIV" class="mystyle myClass">
I am a DIV element with multiple classes
</div>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
y=document.getElementById("myDIV").classList;
alert(y.length);
alert(y[0]) ;
document.getElementById("myDIV").classList.add("anotherClass");

document.getElementById("demo").innerHTML = y[2];
}
</script>
After function call it will add CSS class to div tag
div id="myDIV" class="mystyle myClass anotherClass"">
I am a DIV element with multiple classes
</div> 0 1 2

.mystyle { .myClass { .anotherClass {


width: 500px; text-align: center; background-color: bisque;
height: 50px; font-size: 25px; }
} color: black;
margin-bottom: 10px;
}
Better way of writing code
kidnap only one time
<script>
function myFunction() {
let divobj=document.getElementById("myDIV");
y= divobj.classList;
alert(y.length);
alert(y[0]) ;
divobj.classList.add("anotherClass");

document.getElementById("demo").innerHTML = y[2];
}
</script>
classList.remove("anotherClass") : Remove CSS class Dynamically

<div id="myDIV" class="mystyle anotherClass">


I am a DIV element with multiple classes
</div>

<script>
function myFunction() {

document.getElementById("myDIV").classList.remove("anotherClass");

}
</script>
0 1
.mystyle { .anotherClass
width: 500px; {
height: 50px; background-color: bisque;
} }
document.getElementById("myDIV").classList.replace("anotherClass","myClass");

Create 3 radio button with following value


1. Red
2. 2. green
3. 3. blue
4. On click of radio button change the text color of a paragraph
contains("anotherClass") : Return boolean
<div id="myDIV" class="mystyle anotherClass">
I am a DIV element with multiple classes
</div>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myDIV").classList.contains("anotherC
lass");

document.getElementById("demo").innerHTML = x;
}
</script>

If CSS class is there in a tag it will return true else false

• obj=document.getElementById("myDIV") it returns  Div object


• arr= obj. classList  array of css class
• b= arr.contains(‘’)true
toggle("anotherClass") return boolen
<div id="myDIV" class="mystyle anotherClass">
I am a DIV element with multiple classes
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV").classList.toggle("anotherClass");
document.getElementById("demo").innerHTML = x;
}
</script>
Toggle return Boolean if CSS class is there it will call remove method to remove
css class and if it return false it will call add method add css class.

Note internaly it is calling contains method.


function myFunctiontoggle() {
var x = document.getElementById("myDIV").classList.contains("anotherClass"
);
if(x==true)
{ document.getElementById("myDIV").classList.remove(“anotherClass”);
X=false;
return false;
}
else
document.getElementById("myDIV").classList.add(“anotherClass”)
X=true
return true
document.getElementById("demo").innerHTML = x;
querySelectorAll("p")/querySelector("p")

<!DOCTYPE html>
<html><head><style> function my() {
#myDIV {
border: 1px solid black;
var x = document.getElementByI
margin: 5px; d("myDIV").querySelector("p");
} x.style.color = "blue";
</style></head><body>
<div id="myDIV">
<p>This is a p element in div.</p>
}
<p>This is also a p element in div.</p>
</div>
<p>Click the button to add a background color querySelectorAll("p") : will select all p tag
to the first p element (index 0) in div.</p>

<button onclick="myFunction()">querySelectorA
ll</button> querySelector("p"): will select only 1st p
<script>
tag from the collection
function myFunction() {
var x = document.getElementById("myDIV").
querySelectorAll("p");
x[0].style.backgroundColor = "red";
x[1].style.backgroundColor = "red";
}

</script>
</body>
Note: The querySelector() method only returns the first element that matches the
</html> specified selectors. To return all the matches, use the querySelectorAll() method
instead.
document.querySelector('#foobar');

var el = document.querySelector(".myclass");

var el = document.querySelector("div.user-panel.main input[name='login']");

H1 span [Space]
> Direct child

+
~

*
[ ] attribute
!
$
=
Getter setter for Attribute
<p align="center" id="pp"> hello</p>
<input type="button" onclick="go()"/>
<div id="dd"></div>
<script>
function go()
{
document.getElementById("pp").setAttribute("align","left");

document.getElementById("dd").innerHTML=document.getElementById("pp").getAttribute("align");
}
</script>

setAttribute("align","left"); ===Set value for attribute align

getAttribute("align") ===get-Read value for attribute align


setTimeout() simply delay the job
<html><head><script type="text/javascript">
var c=0; var t;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);

}
function stopCount()
{
clearTimeout(t);
}
</script></head><body>
<form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>
setTimeout batter way
var a=1;var t;
function sayHi()
function st()
{ alert('Hello'); }
{document.write(“Hello st”);

setTimeout(sayHi, 1000); }
document.write(“non blocking programing”);
function call()
document.write(“bye”); {document.write(“Hello call”);

}
function tp()
{document.write(“Hello tp”);

st();
setTimeout(() => alert('Hello'),
call();
1000);
tp();
document.write(“bye”);
setInterval() will call itself so becarefull
<!DOCTYPE html><head><script> TRY THIS!!!!!!!!!!!!!!
var a;var t;
<!DOCTYPE html><head><script>
function st()
var a=1;var t;
{
a=1;
function call()
t=setInterval("call()",1000);
{
} document.getElementById(“nm”).value=a++;
t=setInterval("call()",1000);
function call()
{
document.getElementById(“nm”).value=a++;
}
function tp()
}
{
function tp()
{ alert("hi");
alert("hi");
clearInterval(t)
clearInterval(t)
}
} </script></head><body>
</script></head><body> <input type="textbox" name="nm" value="hi" />
<input type="textbox" id="nm" value="hi" /> <input type="button" value="start" onclick=“call()"/>
<input type="button" value="start" onclick="st()"/>
<input type="button" onclick="tp()" value="stop">
<input type="button" onclick="tp()" value="stop">
</body>
</body>
</html>
</html>

setInterval("call()",1000); it will increase number faster


call() Call()
setInterval()

call()
setInterval()
Changing Style dynamically
<html><head><script>
function callme()
{document.getElementById("pr").style.color="red";
document.getElementById("pr").style.background="yellow";
}

function change()
{document.getElementById("pr").style.color="black";
document.getElementById("pr").style.background="pink";
}
</script></head><body>
<p onmouseover="callme()" id="pr" onmouseout="change()">
welcome to world of style and dom</p>
</body>
</html>
Setting class: clasName

<html><head><style>
.cl{background-color:yellow;font-size:250;color:red;}
.cc{color:blue;}
</style><script>
function callme()
{
ob=document.getElementById("pr")
ob.className="cl";
}
</script></head>
<body>
<p onmouseOver="callme()" id="pr" class="cc"> welcome to world o
f style and dom</p>
</body>

</html>
All images are stored as Array
Images
<html><head><script>
function callme()
0 1 2
{alert(document.images.length)
document.mg.src="b.bmp"; a.bmp p.bmp X.bmp
//document.images[0].src="b.bmp";
document.getElementById("im").src="b.bmp";
}
function backimg()
{document.mg.src="a.bmp";
}
</script></head><body>
<img src="a.bmp" name="mg" id="im“
onmouseover= "callme()“
onmouseout="backimg()">
<img src="p.bmp" />
<img src="x.bmp" />
</body></html>
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
<html>
Array collection of any type of data
<head><title>template</title>
<script> Better way to declare array is []
let arr=new Array() //do not use this way
//it represent object
arr[0]=1; let a =[1,”ket”, ‘g’,20.5 ];
arr[1]="ket";
arr[2]='g';
arr[3]=20.5;
alert(arr.length); It stays on stack
for(let i=0;i<arr.length;i++) 1 ket g 20.5
document.write("<br>"+arr[i])

document.write("<hr/>");

//toString method overriden


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

document.write("<hr/>");

for(let list of arr)// introduce in new version Heap


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

for(let x in arr)//do not use Key 0 1 2 3


document.write(arr[x]);
</script></head><body>
value 1 Ket g 20.5
</body> arr
</html>
Be Careful
<script>
za=new Array(3,8,9,2)
document.write(za); za

for(x of za) 0 1 2 3
document.write(x)
document.write("<p>") 3 8 9 2

//here 2 is size of array


var aa=new Array(2)
7 3
document.write(aa.length);
aa[0]=7;
aa[1]=3; Object
document.write(aa);//7,3
document.write("<hr/>");
function Array() { [native code] }
</script>

document.write(za.constructor);
Better way to declare array
var arr=[1,2,"hi","by"]
<script>
let arr=[];
document.write(arr) arr[0]=5;
arr[4]=4;
document.write(arr)

document.write("<hr/>");

for(let e in arr)
document.write(arr[e])

document.write("<hr/>");

for(let e of arr)
5 undefined undefined undefined 4 document.write(e)
//remove undefined
As we discuss internally it is stored as
for(let e of arr)
key value so for index 1,2,3 it is saying
if(e)
undefined ie. There is no such key
document.write(e)
</script>
<html> 2D Array
<head><script>
var a=new Array();

a[0]=new Array();
a[1]=new Array();
Raj 50 A
a 0
a[0][0]="raj";
a[0][1]=50; 1
Mona 80 B
a[0][2]="A"

a[1][0]="mona";
a[1][1]=80;
a[1][2]="B"
document.write(a[0][1]+"seee");
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
document.write(" "+a[i][j])
document.write("<hr/>");
}
</script></head><body>
</body></html>
Concat: join two array and return new array
<script> nar
10 20 30
let nar=[10,20,30] ar
5 6 7
let ar=[5,6,7]
let result=ar.concat(nar)
document.write(result.constructor)
document.write(result)
document.write("<br/>"+ar);

document.write("<br/>"+nar);
</script>
result
5 6 7 10 20 30
slice(begin,end)
begin : Zero-based index at which to begin extraction.
end : (Optional) Zero-based index at which to end extraction:

slice extracts up to but not including end


<script> cut
var cut=[100,200,300,400] 100 200 300 400
var c=cut.slice(1);
document.write("</br>"+c);
<script> 200 300 400
O/P: 200 300 400 c

<script>
var cut=[100,200,300,400]
document.write("<br>slice(1,3)="+cut.slice(1,3)) 200 300
document.write("</br>"+cut);
</script>
cut
100 200 300 400
Join : convert array to string
<script>
var ar=new Array(5,3,2) 5 3 2

ans=ar.join("-");
document.write(ans);
document.write(typeof(ans)); 5-3-2
ans
</script>
<script>
var ar=new Array(5,3,2) string
ans=ar.join();
document.write(ans); //5,3,2
document.write(typeof(ans));
</script>
POP
var arr = new Array(3);
arr[0] = "D";
arr[1] = "A"; POP
arr[2] = "C";
document.write(arr + "<br />");
document.write(arr.pop() + "<br />"); 2 C
document.write(arr); 1 A C

0 D

1 A
0 D
Push
<script type="text/javascript">

var arr = new Array(3);


arr[0] = "vita";
arr[1] = "dac";
arr[2] = "acts";
3 2020
document.write(arr + "<br />");
document.write(arr.push(“2020") + 2 acts
"<br />"); //4 1 dac
document.write(arr);
0 vita
</script>

The push() method adds one or more elements to the end of an array
and returns the new length.
Shift remove s 1st element from array
<script>

var nar=[100,200,300]
document.write("after shift"+nar.shift())
document.write("</br>"+nar.length)
document.write("</br>"+nar)
</script>
2 300
1 200
100
0 100
Unshift add element in the beginning of array
<script type="text/javascript"> 3
var arr = new Array(); 2 acts
arr[0] = "vita"; 1 dac
arr[1] = "dac"; 0 vita
arr[2] = "acts";
document.write(arr + "<br />");
document.write(arr.unshift("2020")+"<br />");
document.write(arr);
3 acts
</script>
2 dac
in IE it will not show new length
1 vita
0

2020
Reverse: Reverse the array
<script>
var srt=new Array("anita","zeena","beena")
document.write("<br/>"+srt.reverse())
var scpy= srt.reverse();
document.write("<br/>affecting original arr "+srt)
</script>

srt
0 1 2

scpy
anita zeena beena
beena zeena anita

let ob={name:”raj”, age:25} ob 5


Name=raj
let ob2=ob Age=25 a=5 b
Shellow copy ob2 b=a; 5
Splice to add and remove
array.splice(index, howmany, item1, ....., itemX)
Parameter Description

index Required. An integer that specifies at what position to add/remove items, Use negative values to specify the
position from the end of the array

howmany Optional. The number of items to be removed. If set to 0, no items will be removed

item1, ..., itemX Optional. The new item(s) to be added to the array

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1, 2);
document.write("</br>"+fruits );
0 1 2 3
</script> Banana Orange Apple Mango
in the above code it will remove 2 element from index 1 so O/P:

var fr = ["Banana", "Orange", "Apple", "Mango"];


fr.splice(2, 0, "Lemon", "Kiwi");
document.write("</br>"+fr );
In the above code it will insert two data at index 2

0 1 2 3 4 5
Banana Orange Lemon kiwi Apple Mango
Sort
<script>
var srt=new Array("anita","Zeena","beena") API………
document.write("<br/>"+srt.sort()) function Array()
var srtno=[100,350,1,2] {
document.write("<br/>"+srtno.sort()) sort=function( sortnumber)
document.write("<p>after sort function</p>") {
a=Sortnumber( a,b);
function sortnumber(a,b)
{
If(a>0)
return a-b {
} swap…….
}
document.write("<br/>"+srtno.sort(sortnumber))
document.write("<br/>"+srtno.sort((a,b)=>a-b))
}

}
</script> a-b==-1 97-98
a-a=0 97-97
b-a=1 98-97
If the sortnumber is not given then the elements are converted to strings and then sorted alphabetically.

•V8: Quicksort or Insertion Sort (for smaller arrays)


•Firefox: Merge sort
•Safari: Quicksort, Merge Sort, or Selection Sort (depending on the type of
array)
Sorting Array of Objects
Using a comparator function like this makes it Note: It's important to keep in mind that this
extremely easy to sort custom objects in method sorts in-place, which means that the
JavaScript original array is actually sorted and no copy is
let users = [
made. So, while the .sort() method does return
{name: 'Scotty', age: '18'},
the sorted array, you don't actually need to
{name: 'Tommy', age: '21'},
{name: 'Sally', age: '71'}, assign it to anything since the array that it is
{name: 'Billy', age: '18'}, called on is sorted.
{name: 'Timmy', age: '21'}
];

If you want to reverse the order of the sorting, just switch


users.sort((a, b) => { around the comparison of a and b. So if we want the
let keyA = a.age + a.name; numbers to be in descending order, you'd do the
let keyB = b.age + b.name; following:
if (keyA < keyB) return -1;
if (keyA > keyB) return 1; let keyA = a.age + a.name; “18Scotty”
return 0; let keyB = b.age + b.name; “21Tommy”
});

• This will result in the following sorted array: let nums = [3, 2, 6, 50, 10];
[ { name: 'Billy', age: '18' }, nums.sort((a, b) => b - a);
{ name: 'Scotty', age: '18' },
{ name: 'Timmy', age: '21' },
{ name: 'Tommy', age: '21' }, O/P
{ name: 'Sally', age: '71' } ] [ 50, 10, 6, 3, 2 ]

for(const obj of users)


document.write(`name=${obj.name} age=${obj.age}`);
Find
<script>
The find() method returns the const array1 = [5, 12, 8, 130, 44];
value of the first element in the
provided array that satisfies the const found = array1.find(element => element > 10);
provided testing function. If no
values satisfy the testing function,console.log(found);
undefined is returned. // expected output: 12
</script>

<script>
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];

function isCherries(fruit) {
return fruit.name === 'cherries';
}

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
</script>
Filter
The filter() method creates a <script>
const words = ['spray', 'limit', 'elite', 'exuber
new array with all elements
ant', 'destruction', 'present'];
that pass the test
implemented by the provided const result = words.filter(word => word.length >
function. 6);

console.log(result);
// expected output: Array ["exuberant", "destruct
ion", "present"]
</script>

function isBigEnough(value) {
return value >= 10
}

let filtered = [12, 5, 8, 130, 44].filter(isBigEnough)


// filtered is [12, 130, 44]
at
The at() method takes an integer
const array1 = [5, 12, 8, 130, 44];
value and returns the item at that
index, allowing for positive and
let index = 2;
negative integers. Negative integers
count back from the last item in the
console.log(`Using an index of ${index}
array.
the item returned is ${array1.at(index
)}`);
// expected output: "Using an index of
2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index}


item returned is ${array1.at(index)}`)
;
// expected output: "Using an index of
-2 item returned is 130"

console.log(“Using an index of”+index+ ”the item returned


is ”+array1.at(index));
at() <script>
const array1 = [5,12,8,130,44];
fill()
const found = array1.includes(8);
filter()
console.log(found);
find() // expected output: True
</script>
includes()

If matching element found then


return true else false
array.fill(value, start, end)
Parameters

Parame Description
ter
value Required.
The value to fill in.
start Optional.
The start index (position).
Default is 0.
end Optional.
The stop index (position).
Default is array length.

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.fill("Kiwi", 2, 4);

Banana,Orange,Kiwi,Kiwi
<script>
const array1= [1,4,9,16];

// pass a function to map


const map1=array1.map(x=>x*2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

</script>
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
<script>
var a="VIDYANIDHI"
String is immutable Do not use
document.write(a);
new String()
document.write("<hr/>") a VIDYANIDHI new Number()
new Boolean()
document.write(typeof(a));
new Array
document.write("<hr/>")

m VIDYANIDHIraj
document.write(a.length);
document.write("<hr/>")
m=a+"raj";
document.write(m);
document.write("<hr/>");
str Hello
document.write(a);
document.write("<hr/>");

document.write(a.length);
document.write("<hr/>");

var str=new String("hello");

document.write(typeof(str)); //object
document.write("<hr/>");
document.write(str);
</script>
<script type="text/javascript"> Concat()
var str1="Hello ";
var str2="world!";
var str3=str1.concat(str2); str1 Hello
document.write(" </br> "+st
r3);
document.write("<hr/>");
document.write("</br>"+str1+ " <
/br>"+str2);
document.write("<hr/>"); str2
world
var a="vita"
document.write(a.concat("CDAC")) str3
document.write("<hr/>");
document.write(a)
</script> Hello world
a=“vita”
vita a=a+”CDAC”
a
a vita

vitaCDAC vitaCDAC
<script>
var a=new String("abc");
String equality
var b=new String("abc"); a abc
document.write(a==b);//false == check reference (Arrow )which is
not same

var c=b;
document.write(c==b);
b abc
document.write(a===b);//false
document.write(a.equals(b);//true deprecated do not use

document.write("<hr/>");
document.write(a.valueOf()==b.valueOf());//true
c
var x="abc";
var y="abc";
x y
document.write("<hr/>");

document.write(x==y);//true
document.write(x===y);//true
abc == abc
document.write("<hr/>");
document.write(x.valueOf()==y.valueOf());//true

document.write(a===x);//false
document.write(a==x);//true

<script>
0
str document.write("be alert !!!!!!!!!!!!!!!!!!!!!!");
01 str="";
for(i=0;i<1000000;i++)
012 { str=str+i; }
document.write(str);
0123
charAt()
The charAt() method returns the character at the specified index in a string.
The index of the first character is 0, the second character is 1, and so on.
Str.charAt(0) ==@ error
Str.charAt(str.length-1) ==@ error

<script>
var a="VIDYANIDHI"
document.write(a.charAt(1))
0 1 2 3 4 5 6 7 8 9
v I D Y A N I D H I
</script>

var str = “VIDYANIDHI";


var res = str.charAt(str.length-1);
substring
• The substring() method extracts the characters from a string, between two specified indices,
and returns the new sub string.
• This method extracts the characters in a string between "start" and "end", not including "end"
itself. If end omitted, it extracts the rest of the string
• If "start" is greater than "end", this method will swap the two arguments, meaning
str.substring(1, 4) == str.substring(4, 1).
• If either "start" or "end" is less than 0, it is treated as if it were 0.
• Note: The substring() method does not change the original string.

<script type="text/javascript">

var str="Hello world";


document.write(str.substring(3,7)); //lo w
document.write("<hr/>");
document.write(str.substring(2));// llo world
</script>
Substr(start,length)
• The substr() method extracts parts of a string, beginning at the character at the specified position, and
returns the specified number of characters.
• Note: The substr() method does not change the original string.

<script>
var str = "Hello world!";
var res = str.substr(6);
document.write(res);
</script>
O/p=world!

<script>
var str = "Hello world!";
var res = str.substr(1,3);
document.write(res);
</script>
O/p=ell
indexOf(“data”,startindex)
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.

It is used to check @ for email(if -1 error)


If str.length-1==index (error)
If str[0]==index (error)
<script type="text/javascript">
var txt=“PGDAC CDAC"
document.write(txt.indexOf(“D")) //2
document.write(txt.indexOf(“C“,5)) //6

document.write("<br/>")

var a=txt.indexOf(“D")
document.write(txt.indexOf(“D”,a+1))//7
document.write(txt.indexOf("X"))
document.write(txt.indexOf(“d")) //-1

</script>
0 1 2 3 4 5 6 7 8 9
P G D A C C D A C
lastIndexOf(data,end index)
The lastIndexOf() method returns the position of the last occurrence of a
specified value in a string.
Note: The string is searched from the end to the beginning, but returns
the index starting at the beginning, at position 0.
This method returns -1 if the value to search for never occurs.
Note: The lastIndexOf() method is case sensitive!
0 1 2 3 4 5 6
<script type="text/javascript"> P G D A C C
var txt=“PGDAC CDAC"
document.write(txt.lastIndexOf(“D")) //7
document.write("<br/>")

var a=txt. lastIndexOf(“D")


document.write(txt. lastIndexOf(“D”,a-1))//2
document.write(txt. lastIndexOf("X"))
document.write(txt. lastIndexOf(“d")) //-1

0 1 2 3 4 5 6 7 8 8
P G D A C C D A C
</script>
split() String to Array
The split() method is used to split a string into an array of substrings, and returns the new
array.
Tip: If an empty string ("") is used as the separator, the string is split between each
character.
Note: The split() method does not change the original string.

0 1
<script type="text/javascript"> wel come
var str="wel-come"
var s=str.split("-") <script type="text/javascript">
document.write("<br>"+s);
document.write("<BR/>") var str="wel-come"
for(i=0;i<s.length;i=i+1) var s=str.split("")
{ document.write("<br>"+s);
document.write(s[i]) </script>
}

</script> 0 1 2 3 4 5 6 7
w e l - c o m e

Match()
The match() method searches a string for a match against a regular expression, and returns the matches,
as an Array object.
• Note: If the regular expression does not include the g modifier (to perform a global search), the match()
method will return only the first match in the string. i modifier to ignore case
• This method returns null if no match is found.
• If str.match(“@”) null error If str.match(“.”) == null error
• r= str.match(/@/) if r.length>1 error r= str.match(/\./) if r.length>3 error

<script type="text/javascript">
var str="Center Vita Center" 0
document.write(str.match("Center")+"<br/>") Center
<script/>
<script type="text/javascript">
var str="Center Vita center“
let robj= /center/ //typeof(robj)object 0 1
console.log(robj.constructor);//ƒ RegExp() { Center center
[native code] }
lets s= str.match(/center/ig)
for(i=0;i<s.length;i++)
{ document.write(s[i]) <script type="text/javascript">
} var str="Center Vita Center"
<script/> document.write(str.match("dac")+"<br/>")
<script/>
O/p Null
Replace
The replace() method searches a string for a specified value, or a regular expression, and
returns a new string where the specified values are replaced.
Note: If you are replacing a value (and not a regular expression), only the first instance of
the value will be replaced. To replace all occurrences of a specified value, use the global
(g) modifier

// this is called pattern internally Object


i=ignore case
g=global occurance
<script type="text/javascript">
var str="Visit CDAC cdac is good center!";
document.write("</br>"+str);
document.write("<hr/>");
document.write(str.replace(/cdac/ig, "VITA"));
<script/>
O/P: Visit CDAC cdac is good center!
New string:
Visit VITA VITA is good center!
charCodeAt()/ fromCharCode()
• The charCodeAt() method returns the Unicode of the character at the specified index in a
string.
• The index of the first character is 0, the second character 1, and so on.
• The fromCharCode() method converts Unicode values into characters.
• Note: This is a static method of the String object, and the syntax is always
String.fromCharCode().

var str = "HELLO WORLD";


var n = str.charCodeAt(0)// 72
document.write(n)
var res = String.fromCharCode(n);//H
document.write(res)

String functions
The toUpperCase() method converts a string to uppercase letters.
• Note: The toUpperCase() method does not change the original string.
• Tip: Use the toLowerCase() method to convert a string to lowercase letters.
• The trim() method removes whitespace from both sides of a string.
• Note: The trim() method does not change the original string.
• The repeat() method returns a new string with a specified number of copies of the string it was called
on.(ES-6)
The endsWith() method determines whether a string ends with the characters of a specified string.
This method returns true if the string ends with the characters, and false if not.
Note: The endsWith() method is case sensitive.(ES- 6)

The startsWith() method determines whether a string begins with the characters of a specified string.
This method returns true if the string begins with the characters, and false if not.
Note: The startsWith() method is case sensitive. .(ES-6)

The includes() method determines whether a string contains the characters of a specified string.
This method returns true if the string contains the characters, and false if not.
Note: The includes() method is case sensitive. .(ES-6) string.includes(searchvalue, start)
Optional. Default 0. At which
position to start the search
Start
var str = “Hello World! ";
var res = str.toLowerCase();
var result = str.toUpperCase();
alert(str.trim());
document.write(str.repeat(2));
var n = str.startsWith("Hello");//true
var en = str.endsWith("rld! ");
var rr = str.includes("world!", 5);
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy




An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
Event
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• Often, when events happen, you may want to do something.
• JavaScript lets you execute code when events are detected.
• HTML allows event handler attributes, with JavaScript code, to be added to
HTML elements.
<!DOCTYPE html>
<!DOCTYPE html>
<html><head><script>
<html><head>
function go()
<script>
{ alert("click event");
function go()
}
{alert("you click button");
</script></head><body>
}
<form>
</script>
<input type="button" id="btn"/>
</head><body>
</form>
<form>
<script>
<input type="button“
document.getElementById("btn").onclick=
onclick="go()"/>
go;
<input type="button“
</script>
onclick="alert('button == clicked')"/>
</body>
</form>
</html>
</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


addEventListener(event,function)

Definition and Usage


The addEventListener() method attaches an event handler to the specified element.
Tip: Use the removeEventListener() method to remove an event handler that has been
attached with the addEventListener() method.
Tip: Use the document.addEventListener() method to attach an event handler to the
document.

<!DOCTYPE html><html><head>
<script>
function go()
{alert("click event");}
</script></head><body>
<form>
<input type="button" id="btn"/>
<p id="pp"> i am p tag</p>
</form>
</body>
<script>
document.getElementById("btn").addEventListener("click",go);
document.getElementById("pp").addEventListener("mouseover",
function rise(){alert("go rise")}
</script>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<!DOCTYPE html>
<html><head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
}
</style></head>

<div id="myDIV">This div element has an onmousemove event handler that displ
ays a random number every time you move your mouse inside this orange field.
<p>Click the button to remove the DIV's event handler.</p>

<button onclick="removeHandler()" id="myBtn">Try it</button>


</div>

<p><strong>Note:</strong> The addEventListener() and removeEventListener() m


ethods are not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<div id="myDIV">This div element has an onmousemove event handler that displays a random
number every time you move your mouse inside this orange field.
<p>Click the button to remove the DIV's event handler.</p>

<button onclick="removeHandler()" id="myBtn">Try it</button>


</div>

<p><strong>Note:</strong> The addEventListener() and removeEventListener() methods are no


t supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}

function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
document.getElementById("myDIV").addEventListener("mouseover", function(){alert("hi")})
document.getElementById("myDIV").addEventListener("mouseout", ()=>alert(“mouse out”))
</script>
</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Date:function
• By default, JavaScript will use the browser's time zone and display a date as a full text string:
• Mon Nov 30 2020 13:03:21 GMT+0530 (India Standard Time)
– There are 4 ways to create a new date object:

• new Date()//creates a new date object with the current date and time:
• new Date(year, month, day, hours, minutes, seconds, milliseconds)//creates a new date object with a specified date and time.
• new Date(0)//JavaScript stores dates as number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated).
• new Date(date string)//creates a new date object from a date string:

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


All Date()/ format
<script>
var d = new Date(); O/P: Mon Nov 30 2020 14:33:20 GMT+0530 (India Standard Time)

var d = new Date(2018, 11, 24, 10, 33, 30, 0); [year, month, day, hours, minutes, seconds, milliseconds]
o/p : Mon Dec 24 2018 10:33:30 GMT+0530 (India Standard Time)

var d = new Date(2018, 11, 24, 10, 33, 30);[6 numbers specify year, month, day, hour, minute, second: ]
O/P: Mon Dec 24 2018 10:33:30 GMT+0530 (India Standard Time)
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Date Format
There are generally 3 types of JavaScript date input formats:

Type Example
ISO Date "2015-03-25" (The International
Standard)
Short Date "03/25/2015"
Long Date "Mar 25 2015" or "25 Mar 2015"

The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


DEMO
<script>
var s="2015-03-25"
var d = new Date(s);
document.write( d);
document.write( "<hr/>");
var msec = Date.parse("March 21, 2012");
document.write( msec);
document.write( "<hr/>");
var d = new Date(msec);
document.write( d);

var sdate = Date.parse("Mar-21-2012");


var dat = new Date(sdate);
document.write( dat);

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


String to Date/ Parsing
var s="2015-03-25"
var d = new Date(s);
document.write( d);
The computed date will be relative to your time zone.
Depending on your time zone, the result above will vary between March 24 and March 25.

Date Input - Parsing Dates


If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.
Date.parse() returns the number of milliseconds between the date and January 1, 1970:

var msec = Date.parse("March 21, 2012");


var d = new Date(msec);
document.write( d);

d=new Date()
console.log(Date)
console.log(d.__proto__)/ / d._ _ proto _ _
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
GetDate/Time
Method Description
getFullYear() Get the year as a four digit number
(yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since
January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

The getTime() Method


The getTime() method returns the number of milliseconds since January 1, 1970:

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<script type="text/javascript">

var a=new Date();

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

document.write("Date " + a.getDate() + "<br/>");

document.write("Day " + a.getDay() + "<br/>");

document.write("Hours " + a.getHours() + "<br/>");

document.write("Minutes " + a.getMinutes() + "<br/>");


document.write("Seconds " + a.getSeconds() + "<br/>");
document.write("Time " + a.getTime() + "<br/>");

O/P document.write("Month " + a.getMonth() + "<br/>");


Date Mon Nov 30 2020 15:19:26 GMT+0530 (India
Standard Time) document.write("the getMonth() method returns values 0-11");
Date 30 document.write("MillSec " + a.getMilliseconds() + "<br/>");
Day 1
Hours 15 document.write("FullYear " + a.getFullYear() + "<br/>");
Minutes 19
</script>
Seconds 26
Time 1606729766545
Month 10
the getMonth() method returns values 0-11MillSec 545
FullYear 2020
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January
1, 1970)

Some Demo:
//optionally set month and day
var d = new Date();
var d = new Date();
d.setFullYear(2020, 11, 3);
d.setFullYear(2020);
var d = new Date();
var d = new Date(); d.setDate(15);
d.setMonth(11);
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Digital clock
<html><head>
<script type="text/javascript">
function startTime()
{ var today=new Date()
//document.write(today);
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)
h=checkTime(h)
document.getElementById('txt').innerHTML=h+":"+m+":"+s
t=setTimeout('startTime()',500)//500miliseconds
}
function checkTime(i)
{
if (i<10)
{
i="0" + i}
return i
}</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html> USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


random is static method
Refresh the page and observe output
<script> 0.025623787930399766
document.write(Math.random());

document.write("<hr/>")

a=(Math.random()*4);
0.5626264433314665
document.write(a);

document.write("<hr/>")

x=Math.floor(a);
0
document.write(x);

</script>

Math.random() it will generate any number > 0 and < 1

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Generating random background colour

<html><head><script>
var tt;
function changebg()
{
var col=new Array("green","blue","red")

l=col.length
var rnd_no = Math.floor(l*Math.random()); //it will generate any number between [0 to 2]

//alert(Math.floor(l*Math.random()))

document.body.bgColor=col[rnd_no];

tt=setTimeout('changebg()',500)

}
function stopclock()
{
clearTimeout(tt)
}
</script></head>

<body onLoad="changebg()">

<input type="button" onclick="stopclock()" value="stop">

</body> </html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Some Math function
Math.PI; // returns 3.141592653589793

Math.round(4.7); // returns 5

Math.pow(8, 2); // returns 64

Math.sqrt(64); // returns 8

Math.ceil(4.4); // returns 5

Math.floor(4.7); // returns 4
Math.min(0, 150, 30, 20, -8, -200); // returns -200

Math.max(0, 150, 30, 20, -8, -200); // returns 150

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Navigator Object
The window.navigator object contains information about the visitor's browser.

<script type="text/javascript">

var browser=navigator.appName
var b_version=navigator.appVersion Browser name: Netscape
var apcode=navigator.appCodeName; Browser version: 5.0 (Windows)
var lang=navigator.language app_code: Mozilla
Var b=navigator. cookieEnabled lang: en-US
document.write("Browser name: "+ browser) true
document.write("<br />")
document.write("Browser version: "+ b_version)
document.write("<br />")
document.write("app_code: "+ apcode)
document.write("<br />")
document.write("lang: "+ lang)
document.write(“cookie enabled: "+ b)

NOTE:The appCodeName property returns the code name of the browser.


Do not rely on it! "Mozilla" is the application code name for Chrome, Firefox, IE, Safari, and
Opera.
Browscap.ini
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
The cookieEnabled property returns true if cookies are enabled, otherwise false:

The appName property returns the application name of the browser:

Strange enough, "Netscape" is the application name for both IE11, Chrome,
Firefox, and Safari.

The appCodeName property returns the application code name of the browser:
"Mozilla" is the application code name for both Chrome, Firefox, IE, Safari, and Opera.

The appVersion property returns version information about the browser:

The platform property returns the browser platform (operating system):

The onLine property returns true if the browser is online:

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


History Object
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser

//Run 1st this code and click hyperlink


<html><body>
<a href="copy.html">go to next file</a>

<input type="button" value="next" onclick="history.forward()")


</body>
</html>

File name: copy.html


<html>
<head><script>
function copy()
{document.getElementById("b").value= document.getElementById("a").value
}
</script></head>
<body>
<input type="text" id="a">
<input type=button onClick=copy() value="copy data">
<input id="b">
<input type="button" value="back" onclick="history.back()">
</body></html>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Entire page is array of data
Elements[0]
radiobutton Forms-[0]
Elements[1] Elements[2]
radiobutton button
Forms-[1]
Elements[0]
radiobutton
Elements[1] Elements[2]
radiobutton button

All data in page are in form of Array

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<html><head><script>
function call()
{ var v=document.forms[0].elements.length
alert(document.forms.length);
alert(v)

for(let i=0;i<v;i++)
document.getElementById("n").innerHTML+=(document.forms[0].elements[i].value)

}
function call2()
{ alert ("hi"); }
</script></head><body>
<p id="n">hello</p>

<fieldset >
<legend align="center">Forms[0]</legend>
<form>
<p id="n">hello</p>
<input type="radio" name="rd" value="better"/>better
<input type="radio" name="rd" value="best"/>best
<input type="button" value="click" onclick="call(),call2()">
</form>
</fieldset>
<fieldset>
<legend align="center">Forms[1]</legend>
<form legend="Form[1]">
<p id="mm">hello</p>
<input type="radio" name="dd" value="yes"/>yes
<input type="radio" name="dd" value="no"/>no
<input type="button" value="second frm" onclick="call(),call2()">
</form>
</fieldset>
</body></html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Programming the Web
DHTML
• The DHTML Document Object Model (DOM)

window

event navigator history document location screen frames

all location children forms selection body links

text radio button textarea select


password checkbox submit
option
file reset

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Java script DOM
<html><head><script>
function call()
{
var a=document.frm.t1;
var b=document.frm.t2
b.value=a.value;
}

</script></head><body>
<form name="frm" action="a.html" onsubmit="return true">
name<input name="t1"/>

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

copied name<input name="t2"/>


<input type="submit"/>

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

How to access text box with name t1?


Observe foe also has name so we will be using
let obj=window. document.frm.t1 with this line you will get textbox object.
To get value of text box just use obj. value

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


How to pass form in a function :this.form
<html><head>
<script>
function call(a)
{ v=a.length
alert(a)
alert(v)
let data=“”; a
pobj=document.getElementById("pp");
for(i=0;i<v;i++)
{ data=data+a.elements[i].value; form

}
pobj.innerHTML=data;
} this.form
</script></head><body>
<p id="pp">
<form>
<input type="radio" name="rd" value="good">good
<input type="radio" name="rd" value="better">better
<input type="radio" name="rd" value="best">best
<input type="button" value="click" onclick="call(this.form)">
</form></body></html>
`

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


How to read value of radio button and checked keyword
<html><head><script>
function readradio()
{
var l=document.frm.rd.length pobj
let pobj=document.getElementById("pp")

if(document.frm.rd[0].checked)
pobj.innerHTML=document.frm.rd[0].value <p id="pp"> </p>
else
pobj.innerHTML=document.frm.rd[1].value

}
function cc()
{
document.frm.rd[0].checked=true;
document.frm.rd[0].value
}
</script></head>
<body>
<p id="pp"></p>
<form name="frm">
<input type="radio" name
<input type="radio" name="rd" value="yes" />yes
<input type="radio" name="rd" value="no" checked/>no ="rd" value="yes" />yes
<input type="button" value="read" onclick="readradio()">
<input type="button" value="chk" onclick="cc()">

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

if(document.frm.rd[0].checked)
Checked keyword return Boolean
value
If radio button is checked then
return true else false
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
new Document new Form

0 1
frm
document
new InputElemnt
checked
return true

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<html><head><script> How to read value of check box
function readchk()
{
var sldata="";
if(document.frm.a.checked)
sldata+=document.frm.a.value

if(document.frm.b.checked)
sldata+=document.frm.b.value

if(document.frm.c.checked)
sldata+=document.frm.c.value

document.getElementById("dd").innerHTML=sldata;
}
</script></head><body>
<form name="frm">
<input type="checkbox" name="a" value="dance"/>dance
<input type="checkbox" name="b" value="music"/>music
<input type="checkbox" name="c" value="sports"/>sports
<div id="dd"></div>
<input type="button" value="read" onclick="readchk()">
</form></body></html>

if(document.frm.a.checked)
Checked keyword return Boolean value
If checkbox is checked then return
true else false
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
How to read selected value of dropdown
<html><head><script> if(document.frm.sl[0]. selected)
function readradio()
{
Checked keyword return Boolean value
var l=document.frm.sl.length If option is selected then return
for(i=0;i<l;i++) true else false
{ if(document.frm.sl[i].selected)
document.frm.t.value=(document.frm.sl[i].value) selectedIndex
}
let pobj=document.getElementById("pp");
This keyword will return the
pobj.innerHTML=document.frm.sl.selectedIndex index of selected option
let index=document.frm.sl.selectedIndex;
pobj.innerHTML+=(document.frm.sl[index].text)
}
</script> text
</head><body><p id="pp"></p>
<form name="frm"> <option value="0">dance</option>
<select name="sl“ onchange="readradio()" >
<option value="0">dance</option>
<option value="1">music</option>
<option value="2">sports</option> value
</select>
<input disabled name="t"/>
<input type="button" value="read" onclick="readradio()">
</form>
</body></html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<html><script>
Create a dynamic form
function call() f.appendChild(t);
{ f.appendChild(r1);
var f=document.createElement('form’) f.appendChild(l1);
f.name='frm' f.appendChild(r2);
var t= document.createElement('input')
t.type='text' f.appendChild(l2);
t.maxlength=5; f.appendChild(s);
t.name="t1" //f.appendChild(c1);
document.getElementById('dd').appendChild(f);
r1= document.createElement('input')
}
l1=document.createElement('label')
</script>
r2= document.createElement('input') <body>
l2=document.createElement('label') <input type="button" onclick="call()"/>
r1.type="radio" <div id='dd'> </div>
r2.type="radio" </body>
r1.name="nm"
r2.name="nm" <form name="frm">
newText1=document.createTextNode("yes");
<input type="text" name="t1">
newText2=document.createTextNode("No");
<input type="radio" name="nm">
l1.appendChild(newText1); <label>yes</label>
l2.appendChild(newText2);
var s= document.createElement('select') ; <input type="radio" name="nm">
var o=document.createElement('option') <label>No</label>
var o1=document.createElement('option')
<select>
o.innerHTML="India"; <option>India</option>
o1.innerHTML="USA"; <option>USA</option>
s.appendChild(o);
s.appendChild(o1); </select>
</form>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Form level event  onsubmit="return check()"
<html><head>
function setcur()
<style>.err{color:red}</style>
{//autofocus
<script> var tobj=document.frm.nm
function check() tobj.focus()
{
var tobj=document.frm.nm //textbox }
</script></head>
data=tobj.value //value of textbox
<body onLoad="setcur()">
var len=data.length
let sobj=document.getElementById("ter"); <form name="frm" action="blur.html"
//required onsubmit="return check()">
if(len==0)
<label>Password</label>
{
sobj.innerHTML= "password can not be blank" <input type="text" name="nm" >
document.frm.nm.focus() <span id="ter" class="err"></span>
return false
} <input type="submit" value="submit" >
else if(len<8||len>16)
</form></body></html>
{
sobj.innerHTML="minimum 8 character required and can n
ot exceed 15" In above example check function return false if password is blank or password is < 8
return false character or >16 character.
}
else It also print appropriate message in span tag.
sobj.innerHTML=""
By default onsubmit event has return value true and it is form level event , get fires
} when you click on submit button

So if function not returning any value for valid data then it will read as true and
control will go to blur.html page
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
How to make Dum button intelligent: Dynamically submitting form

<html> if(bool==true)
<style>.err{color:red}</style> document.frm.submit();//dynamically firing event
<script> }
function setcur()
function check()
{//autofocus
{ bool=true; document.frm.nm.focus()
var data=document.frm.nm.value
var len=data.length }
let sobj=document.getElementById("ter"); </script>
//required
if(len==0) <body onLoad="setcur()">
{ <form name="frm" action="blur.html">
sobj.innerHTML= "password can not b <label>Password</label>
e blank" <input type="text" name="nm" ><span id="ter" class="
document.frm.nm.focus() err"></span>
<input type="button" value="dum" onclick="check()">
bool= false
return bool; </form>
}

else if(len<8||len>16) </body>


</html>
{
sobj.innerHTML= "minimum 8 character required
and can not exceed 15"
bool= false
return bool;
}
else
sobj.innerHTML=""

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Task
Q1. Create three textbox and two radio button [+ ,*] On click of radio button result of operation should be displayed in third text box
give basic validation.
Q2. create 3 check box displaying book name and price, as per selection of user, display total amount of book purchased in a disabled
text box.
Q3. create a dropdown list displaying state on change of it display selected state in a textbox.
Q4. create 3 textbox and a dropdown list displaying mathematical operation. On click of button it should display result in 3 rd text box
Q5. Using JavaScript Create banner, include 4 images. Images should rotate after time gap of 1 second.
Q6. Create a web page for entering all personal details Information should containName, Date of Birth (use select drop down
list), Gender, Address, Ps. No. , batch No. and Date of Joining (use select drop down list) Validate this form
Q7. Display digital clock

Refer folder student data for more examples and logic

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Answer Q1.

<html> <head>
<script>
function dotask(operation) function validate(a,sid)
{ { alert("hh")
let n1=document.getElementById("n1") //let n1=document.getElementById("n1")
let n2=document.getElementById("n2") let s1=document.getElementById(sid)
let n3=document.getElementById("n3")
if(a.value.length==0||a.value=="")
//+before string convert string to number
if(operation=="+") s1.innerHTML="Text field can not be blank"
{ n3.value= +n1.value + +n2.value if(isNaN(a.value))
} s1.innerHTML="only number value allowed"
}
else if(operation=="*") </script></head>
n3.value= n1.value*n2.value

<body>
<form>
<input type=“text" id="n1" onchange="validate(this,'err1')"/><span id="err1"></span>
<input type=“text" id="n2" onchange="validate(this,'err2')"/><span id="err2"></span>
<input type="radio" name="r1" value="+" onchange="dotask(this.value)"/>+
<input type="radio" name="r1" value="*" onchange="dotask(this.value)"/>*
<input type="number" id="n3" disabled/>
</form>
</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


isNaN() return boolean
<script>
a=isNaN("56 ket");
document.write("data is not a no "+a);//true
b=isNaN(5)
document.write("<br> 5 is not a no. "+b);//false
c=isNaN("5")
document.write("5 takenn as string is not a no "+c)//false
b=isNaN(5+5)//false

</script>
isNaN(“5”)==check entered data is number or not?
Even if number is in “” it will call valueOf()

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Answer Q2
<html><head><script>
function dosum()
{
var sldata=0;
if(document.frm.a.checked)
sldata+= +document.frm.a.value

if(document.frm.b.checked)
sldata+= +document.frm.b.value

if(document.frm.c.checked)
sldata+= +document.frm.c.value

document.getElementById("dd").innerHTML=sldata;
}

</script></head><body>
<form name="frm">
<input type="checkbox" name="a" value="250"/>C 250/-
<input type="checkbox" name="b" value="750"/>c# 750/-
<input type="checkbox" name="c" value="550"/>JavaScript 550/-
<div id="dd"></div>
<input type="button" value="read" onclick="dosum()">
</form></body></html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


What is a Regular Expression?
• A regular expression is a sequence of characters that forms a search
pattern.
• When you search for data in a text, you can use this search pattern to
describe what you are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text
replace operations.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


WHY regular expression ====Remove space from given string

<script>

var str = "Neo| Trinity |Morpheus | Smith| Tank";

result = str.split("|");

document.write(result)
// iterate over result array

for(i = 0; i < result.length; i++)

{ alert(result[i]);
}

alert(result)

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Regular expression is better and less coding
<script>

var str = "Neo| Trinity |Morpheus | Smith| Tank";


var pattern = /\s*\|\s*/;

// split the string using the regular expression as the separator


//\s means space
//* means 0 or more occurrence of previous character ( m* m can occure in string 0 or more time[mita, nita])
// “|” it has meaning OR to escape and to indicate that read it as “|” character use \|
result = str.split(pattern);

// iterate over result array

document.write(result)

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


There are situation where you want to check that particular character is there or not

Eg. password should have one capital. One small letter, one digit
if(num.test(str))
<html><head>
{a=a+1;
<script>
}
function check_pass()
else
{let a;
let cap=/[A-Z]{1,13}/
{a=0 VITA
alert("number is missing")
let small=/[a-z]{1,13}/
}
let num=/[0-9]{1,13}/
if(a==3)
return true
let str =document.getElementById("tt").value;
else
if(cap.test(str))
return false
{a=1;
}
}
function vali()
else
{
{alert("letter is missing")
let r=check_pass()
a=0;
return r;
}
}
if(small.test(str))
</script></head><body>
{a=a+1;
<form action="go.html" onsubmit="return vali()">
}
<input id="tt" onchange="check_pass()"/>
else
<input type="submit"/>
{ a=0;
</form>
alert("small letter is missing")
</body>
}
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Validation
• ^ begins with
• $ ends with
• {10} exact 10 countoccurance
• Let pcom=/^[A-Za-z0-9_]{8,15}$/
• Let num=/^[0-9]{10}$/ =10 digit mobile
• Let pass=/^[A-Za-z]{8,15}$/ password only character min 8 max 15
• Let age=/^[0-9]{1,2}$/ =age in 2 digit
• Let dt=/^[0-9]{2}\/[0-9]{2}\/[0-9]{2,4}$/  basic date format
• Match this format of dtae: 03/12/2020
• Prob: 31/33/1920

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


String regexp methods
.match(regexp) returns first match for this string
against the given regular
expression; if global /g flag is
used, returns array of all matches
.replace(regexp, text) replaces first occurrence of the
regular expression with the given
text; if global /g flag is used,
replaces all occurrences
.search(regexp) returns first index where the
given regular expression occurs
.split(delimiter[,limit]) breaks apart a string into an array
of strings using the given regular
as the delimiter; returns the
array of tokens

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The search(..) method
Searches a string for a match to the supplied regular expression.

//Example 1 : Output 
<script language="JavaScript">
When you run this script, you should see the following:
// define string to be searched
Sorry, Trinity is not in The Matrix.
var str = "The Matrix";

// define search pattern


var pattern = /trinity/; Explanation

// search and return result The search() method returns the position of the substring matching the regular
if(str.search(pattern) == -1) expression, or -1 if no match exists. In the example above, it is clear that the
{ pattern "trinity" does not exist in the string "The Matrix," hence the error
alert("Sorry, Trinity is not in The Matrix."); message.
}
else
{
alert("Trinity located in The Matrix at character " + str.search(pattern));
}

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The search(..) method
Output 
//Example 2 :
<script language="JavaScript">
This time round, the JavaScript interpreter will return a match (and the location
// define string to be searched where it found the match). Here's the output:
var str = " The Matrix";
Tri located in The Matrix at character 7
// define search pattern
var pattern = /tri/;

// search and return result


if(str.search(pattern) == -1)
{
alert("Sorry, Trinity is not in The Matrix.");
} else
{
alert(“tri ocated in The Matrix at character " + str.search(pattern));
}

</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Basic regexes

/abc/

• a regular expression literal in JS is written /pattern/


• the simplest regexes simply match a given substring

• the above regex matches any line containing "abc"


• YES : "abc", "abcdef", "defabc", ".=.abc.=."
• NO : "fedcba", "ab c", "AbC", "Bash", ...
• /abc/.test(“abc”)

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Wildcards and anchors

. (a dot) matches any character except \n


• /.oo.y/ matches "Doocy", "goofy", "LooPy", ...
• use \. to literally match a dot . character

^ matches the beginning of a line; $ the end


• /^if$/ matches lines that consist entirely of if

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


String match

string.match(regex)

• if string fits pattern, returns matching text; else null


• can be used as a Boolean truthy/falsey test:
if (name.match(/[a-z]+/)) { ... }

• g after regex for array of global matches


• "obama".match(/.a/g) returns ["ba", "ma"]

• i after regex for case-insensitive match


• name.match(/Marty/i) matches "marty", "MaRtY"

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


String replace

string.replace(regex, "text")

• replaces first occurrence of pattern with the given text


• var state = "Mississippi";
state.replace(/s/, "x") returns "Mixsissippi"

• g after regex to replace all occurrences


• state.replace(/s/g, "x") returns "Mixxixxippi"

• returns the modified string as its result; must be stored


• state = state.replace(/s/g, "x");

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Special characters

| means OR
• /abc|def|g/ matches lines with "abc", "def", or "g“
• /abc|def|g/.test(“hello go to school”)

() are for grouping


• /(Homer|Marge) Simpson/ matches lines containing
"Homer Simpson" or "Marge Simpson"

\ starts an escape sequence


• many characters must be escaped: / \ $ . [ ] ( ) ^ * + ?

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Quantifiers: * + ?

* means 0 or more occurrences


• /abc*/ matches "ab", "abc", "abcc", "abccc", ...
• /a(bc)*/" matches "a", "abc", "abcbc", "abcbcbc", ...
• /a.*a/ matches "aa", "aba", "a8qa", "a!?_a", ...

+ means 1 or more occurrences


• /a(bc)+/ matches "abc", "abcbc", "abcbcbc", ...
• /Goo+gle/ matches "Google", "Gooogle", "Goooogle", ...

? means 0 or 1 occurrences
• /Martina?/ matches lines with "Martin" or "Martina"
• /Dan(iel)?/ matches lines with "Dan" or "Daniel"

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


More quantifiers

{min,max} means between min and max occurrences


• /a(bc){2,4}/ matches lines that contain
"abcbc", "abcbcbc", or "abcbcbcbc"

• min or max may be omitted to specify any number


• {2,} 2 or more
• {,6} up to 6
• {3} exactly 3

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Character sets

[ ] group characters into a character set;


will match any single character from the set
• /[bcd]art/ matches lines with "bart", "cart", and "dart"
• equivalent to /(b|c|d)art/ but shorter

• inside [], most modifier keys act as normal characters


• /what[.!*?]*/ matches "what", "what.", "what!", "what?**!", ...

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Character ranges vidyaN8
vifyaNidhi9

• inside a character set, specify a range of chars with –(/[a-z][A-Z][0-9]/)


• /[a-z]/ matches any lowercase letter
• /[a-zA-Z0-9]/ matches any letter or digit

• an initial ^ inside a character set negates it


• /[^abcd]/ matches any character but a, b, c, or d
• //%[^\n]

• inside a character set, - must be escaped to be matched


• /[\-+]?[0-9]+/ matches optional - or +, followed by at least one digit
.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• \b
Built-in character ranges
word boundary (e.g. spaces between words) “vita nidhi”.match(/\b/)
• \B non-word boundary
• \d any digit; equivalent to [0-9]
• /^\d{1,2}\/\d{1,2}\/\d{2,4}$/
• 33/1/2020
• \D any non-digit; equivalent to [^0-9]
• \s any whitespace character; [ \f\n\r\t\v...]
• \s any non-whitespace character
• \w any word character; [A-Za-z0-9_]
• \W any non-word character

• /\w+\s+\w+/ matches two space-separated words

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Regex flags

/pattern/g global; match/replace all occurrences


/pattern/i case-insensitive
/pattern/m multi-line mode

• flags can be combined:


/abc/gi matches all occurrences of abc, AbC, aBc, ABC, ...

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The RegExp object

new RegExp(string)
new RegExp(string, flags)

• constructs a regex dynamically based on a given string


var r = /ab+c/gi; is equivalent to
var r = new RegExp("ab+c", "gi");

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Working with RegExp

• in a regex literal, forward slashes must be \ escaped:


/http[s]?:\/\/w+\.com/
https://v.com

• in a new RegExp object, the pattern is a string, so the usual escapes


are necessary (quotes, backslashes, etc.):
new RegExp("")

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Regexes in editors and tools

• Many editors allow regexes in their Find/Replace feature

• many command-line Linux/Mac tools support regexes


grep -e "[pP]hone.*206[0-9]{7}" contacts.txt

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


JavaScript RegExp ?= Quantifier
<!DOCTYPE html>
<html>
• Definition and Usage <body>
• The ?=n quantifier matches any string that is followed by a specific string n.
• Tip: Use the ?!n quantifier to match any string that is NOT followed by a <p>Click the button to global search for "is" followed by "
specific string n.
all".</p>

• O/P is <button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = "Is this all there is";
var patt1 = /is(?= all)/;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
JavaScript RegExp ?! Quantifier
<!DOCTYPE html>
<html>
• Definition and Usage <body>
• The ?!n quantifier matches any
string that is not followed by a <p>Click the button to do a global, case insensitive search for
specific string n. "is" not followed by " all".</p>
• Tip: Use the ?=n quantifier to
match any string that IS followed <button onclick="myFunction()">Try it</button>
by a specific string n.
• <p id="demo"></p>

<script>
function myFunction() {
var str = "Is this all there is";
var patt1 = /is(?! all)/gi;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body></html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• Mobile number
• User id /^[A-Za-z]{3,15}$/
• Password
• Date /^\d{2}\/\d{2}\/\d{2,4}$/
• Pincode /^\d{6}$/

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Firstname: only letters (accept data after converting into small letters)(when user TYPE
DISPLAY IN CAPITAL)
Lastname : only letters (accept data after converting into small letters)(when user TYPE
DISPLAY IN CAPITAL)
UserId : minlength 3 max 15 combination of anything
Password: min length=8 maxlength=16 [1 capital 1 lower 1 digit 1 symbol]
ReenterPassword ReenterPassword==password[ ]
Mobile: 10digit
Address: minimum 10 max 15
Pincode: 6 digit
Email: email validation

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Event object
Event The parent of all event objects

<html><head><script type="text/javascript">
function whichType()
{ alert(event.type)
console.log(event)
}
</script>
</head>
<body onkeydown="whichType()">
<p>
press any key. An alert box will alert which type of event occurred.
</p>
</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


screenX- clientX screenX means within your desktop screen
<html>
it will return x, y coordinates
<head><script type="text/javascript">
function coordinates()
client means within a browser . It will
{
resturn x,y coordinates of browser
x=event.screenX
client,Y=0,0 screen
y=event.screenY
screenX,Y=10,10
alert("X=" + x + " Y=" + y) browser
x=event.clientX
y=event.clientY
alert("X coords: " + x + ", Y coords: " + y)

}
</script></head>
<body onmousedown="coordinates()">
<p>
Click somewhere in the document. An alert box will
alert the x and y coordinates of the cursor, relativ
e to the screen.
</p>
</body></html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


event.currentTarget
Click on a paragraph. An alert box will alert the element whose eventlistener triggered th
<!DOCTYPE html> e event.[in our example it is body tag]
<html>
Note:The currentTarget property does not necessarily
<body onclick="myFunction(event)"> return the element that was clicked on, but the element whose eventlistener triggered the
<p>Click on a paragraph. An alert box will alert the element whose eventlistener event.
triggered the event.</p>
The currentTarget event property returns the element whose
<p><strong>Note:</strong> The currentTarget property does not necessarily event listeners triggered the event.
return the element that was clicked on, but the element whose eventlistener
triggered the event.</p> This is particularly useful during capturing and bubbling.

<script> The currentTarget property always refers to the element whose event listener triggered th
function myFunction(event) e event, opposed to the target property, which returns the element that triggered the eve
nt.
{
alert(event.currentTarget.nodeName);
}
</script>

</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


event.Target
<!DOCTYPE html>
<html>
<body onclick="myFunction(event)">
<p>Click on any elements in this document to find out which element triggered the onclick event.</p>
<h1>This is a heading</h1>
<button>This is a button</button>
<p id="demo"></p>
<script>
function myFunction(event) {
var x = event.target;
document.getElementById("demo").innerHTML = "Triggered by a " + x.nodeName + " element";
}
</script></body></html>

Event.target display t which element triggered the onclick event


If you click on p tag it will print
Triggered by a " + p + " element

If you click on button


Triggered by a " + button+ " element

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


onBlur-onFocus Onblur: When a component loose focus
<html> <head>
onblur event get fired. Eg when you have
<script type="text/javascript">
two text box t1,t2. when you click on t1
function setStyle()
and then move cursor to t2 then t1 will
{
get onblur event. We can do validation
document.getElementById("lname").style.background="yellow"
of a field on blur.
}
function change()
Onfocus:when you click on a component
{
document.getElementById("fname").style.color="blue"
onfocus event get fired. Onfocus you can
}
give border to textbox.

</script></head>
<body>
First name: <input type="text" onblur="change()" id="fname">
<br />
Last name: <input type="text" onfocus="setStyle()" id="lname">
The onfocus event occurs when an object gets focus.

</body>
</html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


onmousemove

<html>
<body>

<img src="image.gif" alt="vita" onmousemove="alert('Visit Mumbai!')" />


</body>

</html>

When you move the mouse this event get fierd

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


onError
The onerror event is triggered when an error occurs loading a document or an image

<img src="imae.gif" onerror="alert('The image could not be loaded.')">

In the above example ensure that [imae.gif] image is not there in the folder. Internally it will try to
load image which is not there so it will get onerror event

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


onChange
<html><head><script type="text/javascript">
In our example when user select option from
function favBrowser()
dropdown internally it is firing onchange
{ var mylist=document.getElementById("myList")
event.
alert(mylist.selectedIndex)

document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text

}
</script></head><body>
<form>
Select your favorite browser:
<select id="myList" onchange="favBrowser()">
<option>select</option>
<option>Internet Explorer</option>
<option>Netscape</option>
<option>Opera</option>
</select>
<p>Your favorite browser is: <input type="text" id="favorite" size="20"></p>
</form></body></html>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Event: input
• The input event triggers every time after a value is modified by the user.
• Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or
using speech recognition to dictate the text.
• For instance:

<input type="text" id="input" >oninput: <span id="result"></span>
• <script>

• document.getElementById("input").oninput = function() {
• document.getElementById("result").innerHTML = document.getElementById("input").value;
• };
• </script>

• If we want to handle every modification of an <input> then this event is the best choice.
• On the other hand, input event doesn’t trigger on keyboard input and other actions that do not involve value change, e.g. pressing
arrow keys ⇦ ⇨ while in the input.
• Can’t prevent anything in oninput
• The input event occurs after the value is modified.
• So we can’t use event.preventDefault() there – it’s just too late, there would be no effect.
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Key event
• The MSDN documentation states the order in which the three events occur fairly clearly:
• Key events occur in the following order:
• KeyDown
• KeyPress
• KeyUp

• KeyDown is raised as soon as the user presses a key on the keyboard, while they're still holding it down. it also raised for noncharacter keys

• KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed. This is a "higher-
level" event than either KeyDown or KeyUp, and as such, different data is available in the EventArgs.

• KeyUp is raised after the user releases a key on the keyboard. it also raised for noncharacter keys

• Generally, you should handle the KeyUp event in your application. Actions should not be initiated in the UI until after the user releases the key. And since
KeyUp is a lower-level event than KeyPress, you'll always have plenty of information at your fingertips about the key that was pressed, and it will even
work for handling non-character keys.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Keypress By default all event return true.
onkeydown="return false" when you add
The onkeydown event occurs when a keyboard key is pressed. this in input tag it will not allowed
<html><body> to type at all.
<script type="text/javascript">
function noNumbers(e) onkeypress: is raised for character keys (unlike
{ KeyDown and KeyUp, which are also raised for
var keynum noncharacter keys) while the key is pressed
var keychar
var numcheck

keynum = e.keyCode
keychar = String.fromCharCode(keynum)
alert(keychar)
numcheck = /\d/
return !numcheck.test(keychar)
}
</script>
<form>
<input type="text" onkeypress="return noNumbers(event)" />
<input type="text" onkeydown="return false" />
</form>
</body>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Mouse leave -out <body>
<div onmouseleave="myLeaveFunction()">
<!DOCTYPE html> <p>onmouseleave: <br> <span id="demo2">Mouse over and l
<html><head> eave me!</span></p>
</div>
<style>
div { <div onmouseout="myOutFunction()">
width: 100px; <p>onmouseout: <br> <span id="demo3">Mouse over and lea
ve me!</span></p>
height: 100px; </div>
border: 1px solid black; <script>
margin: 10px; var x = 0;
var y = 0;
float: left; var z = 0;
padding: 30px;
text-align: center; function myLeaveFunction() {
document.getElementById("demo2").innerHTML = x+=1;
background-color: lightgray; }
}
p { function myOutFunction() {
document.getElementById("demo3").innerHTML = y+=1;
background-color: white; }
} </script> The mouseleave event only occurs when the
</style></head> </body></html> mouse pointer is moved out of the div element.
The onmouseout event occurs when the mouse
pointer is moved out of the div element, and
when it leaves its child elements (p and
span).
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Promise
• Imagine that you’re a top singer, and fans ask day and night for your upcoming ...

• To get some relief, you promise to send it to them when it’s published. You give your fans a list. They
can fill in their email addresses, so that when the song becomes available, all subscribed parties
instantly receive it. And even if something goes very wrong, say, a fire in the studio, so that you can’t
publish the song, they will still be notified.

• Everyone is happy: you, because the people don’t crowd you anymore, and fans, because they won’t
miss the single.

• This is a real-life analogy for things we often have in programming:

• A “producing code” that does something and takes time. For instance, some code that loads the
data over a network. That’s a “singer”.
• A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions
may need that result. These are the “fans”.
• A promise is a special JavaScript object that links the “producing code” and the “consuming code”
together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever
time it needs to produce the promised result, and the “promise” makes that result available to all of
the subscribed code when it’s ready.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The constructor syntax for a promise object is:
let promise = new Promise(function(resolve, reject) {
// executor (the producing code, "singer")
});
• The function passed to new Promise is called the executor. When new Promise is created, the
executor runs automatically. It contains the producing code which should eventually produce
the result. In terms of the analogy above: the executor is the “singer”.
• Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only
inside the executor.
• When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of
these callbacks:

•resolve(value) — if the job finished successfully, with result value.

•reject(error) — if an error occurred, error is the error object.

So to summarize: the executor runs automatically and attempts to perform a job. When it is finished with the attempt it calls resolve if it was
successful or reject if there was an error.

The promise object returned by the new Promise constructor has these internal properties:

•state — initially "pending", then changes to either "fulfilled" when resolve is called or "rejected" when reject is called.
•result — initially undefined, then changes to value when resolve(value) called or error when reject(error) is called.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• So the executor eventually moves promise to one of these states:

Here’s an example of a promise constructor and a simple executor function with “producing code” that takes
time (via setTimeout):

let promise = new Promise(function(resolve, reject) {


// the function is executed automatically when the promise is constructed

// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve("done"), 1000);
});

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


function ( re,rj){
Promise
() => resolve("done")
}

F:
promise Resolve:
Reject: function ( data){
Then: data
}

function ( err){
Err
}

result=>alert(result)
function ( callback){

Callback()
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
• We can see two things by running the code above:
• The executor is called automatically and immediately (by new Promise).
• The executor receives two arguments: resolve and reject. These functions are pre-defined by the JavaScript engine, so we
don’t need to create them. We should only call one of them when ready.
• After one second of “processing” the executor calls resolve("done") to produce the result. This changes the state of the
promise object:

That was an example of a successful job completion, a “fulfilled promise”.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


And now an example of the executor rejecting the promise with an error:

let promise = new Promise(function(resolve, reject) {


// after 1 second signal that the job is finished with an error
setTimeout(() => reject(new Error("Whoops!")), 1000);
});

• The call to reject(...) moves the promise object to "rejected" state:

To summarize, the executor should perform a job (usually something that takes time) and then call resolve or reject to
change the state of the corresponding promise object.

A promise that is either resolved or rejected is called “settled”, as opposed to an initially “pending” promise.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


There can be only a single result or an error

The executor should call only one resolve or one reject. Any state
change is final.
Reject with Error objects
All further calls of resolve and reject are ignored:
In case something goes wrong, the executor
should call reject. That can be done with any type
1. let promise = new Promise(function(resolve, reject) {
of argument (just like resolve). But it is
2. resolve("done");
recommended to use Error objects (or objects that
inherit from Error). The reasoning for that will
3. reject(new Error("…")); // ignored
soon become apparent.
4. setTimeout(() => resolve("…")); // ignored
5. });

The idea is that a job done by the executor may have only one
result or an error.

Also, resolve/reject expect only one argument (or none) and will
ignore additional arguments.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• Immediately calling resolve/reject
• In practice, an executor usually does something
asynchronously and calls resolve/reject after some The state and result are internal
time, but it doesn’t have to. We also can call resolve or
reject immediately, like this: The properties state and result of the Promise
• let promise = new Promise(function(resolve, reject) { object are internal. We can’t directly access them.
• // not taking our time to do the job We can use the methods .then/.catch/.finally for
that. They are described below.
• resolve(123); // immediately give the result: 123
• });

• For instance, this might happen when we start to do a


job but then see that everything has already been
completed and cached.

• That’s fine. We immediately have a resolved promise.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• Consumers: then, catch, finally
• A Promise object serves as a link between the executor (the “producing
code” or “singer”) and the consuming functions (the “fans”), which will
receive the result or error. Consuming functions can be registered
(subscribed) using methods .then, .catch and .finally.
then For instance, here’s a reaction to a successful
The most important, fundamental one is .then. ly resolved promise:
The syntax is:
let promise = new Promise(function(resolve, rej
promise.then( ect) {
function(result) { /*handle a successful setTimeout(() => resolve("done!"), 1000);
result */ }, });
function(error) { /*handle an error */ }
); // resolve runs the first function in .then
promise.then(
The first argument of .then is a function result => alert(result), // shows "done!" aft
that runs when the promise is resolved, an er 1 second
d receives the result. error => alert(error) // doesn't run
);
The second argument of .then is a function
that runs when the promise is rejected, a The first function was executed.
nd receives the error.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


And in the case of a rejection, the second one:

let promise = new Promise(function(resolve, reject) {


setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// reject runs the second function in .then


promise.then(
result => alert(result), // doesn't run
error => alert(error) // shows "Error: Whoops!" after 1 second
);

If we’re interested only in successful completions, then we can provide only one function argument to .then:

let promise = new Promise(resolve => {


setTimeout(() => resolve("done!"), 1000);
});

promise.then(alert); // shows "done!" after 1 second

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


catch

If we’re interested only in errors, then we can use null as the first
argument:
.then(null, errorHandlingFunction). Or we can use
.catch(errorHandlingFunction), which is exactly the same:

let promise = new Promise((resolve, reject) => {


setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// .catch(f) is the same as promise.then(null, f)


promise.catch(alert); // shows "Error: Whoops!" after 1 second

The call .catch(f) is a complete analog of .then(null, f), it’s just a


shorthand.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


finally
Just like there’s a finally clause in a regular try {...} catch {...}, there’s finally in promises.
The call .finally(f) is similar to .then(f, f) in the sense that f always runs when the promise is settled: be it reso
lve or reject.
finally is a good handler for performing cleanup, e.g. stopping our loading indicators, as they are not needed anymore
, no matter what the outcome is.

Like this:
new Promise((resolve, reject) => { /* do something that takes time, and then call resolve/reject */
})
// runs when the promise is settled, doesn't matter successfully or not
.finally(() => stop loading indicator)
// so the loading indicator is always stopped before we process the result/error
.then(result => show result, err => show error)
That said, finally(f) isn’t exactly an alias of then(f,f) though. There are few subtle differences:
A finally handler has no arguments. In finally we don’t know whether the promise is successful or not. That’s all righ
t, as our task is usually to perform “general” finalizing procedures.
A finally handler passes through results and errors to the next handler.
For instance, here the result is passed through finally to then:

new Promise((resolve, reject) => { setTimeout(() => resolve("result"), 2000) })


.finally(() => alert("Promise ready")) .then(result => alert(result)); // <-- .then handles the result

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


And here there’s an error in the promise, passed through finally to catch:

new Promise((resolve, reject) => {


throw new Error("error");
}) .finally(() => alert("Promise ready")) .catch(err => alert(err)); // <-- .catch handles the error object

That’s very convenient, because finally is not meant to process a promise result. So it passes it through.

We’ll talk more about promise chaining and result-passing between handlers
We can attach handlers to settled promises

If a promise is pending, .then/catch/finally handlers wait for it. Otherwise, if a promise has already settled, they just run:

// the promise becomes resolved immediately upon creation


• let promise = new Promise(resolve => resolve("done!"));

promise.then(alert); // done! (shows up right now)

Note that this makes promises more powerful than the real life “subscription list” scenario. If the singer has already released
their song and then a person signs up on the subscription list, they probably won’t receive that song. Subscriptions in real l
ife must be done prior to the event.

Promises are more flexible. We can add handlers any time: if the result is already there, they just execute.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Promises Callbacks
Promises allow us to do things in the natural order.
We must have a callback function at our disposal , In
First, we run loadScript(script), and .then we write
other words, we must know what to do with the result
what to do with the result.
We can call .then on a Promise as many times as we
want. Each time, we’re adding a new “fan”, a new There can be only one callback.
subscribing function, to the “subscription list”.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Promise
<!DOCTYPE html>
<html><body>
Call back
<!DOCTYPE html><html><body> <h2>JavaScript Promise</h2>
<p>Wait 3 seconds (3000 milliseconds) for this
<h2>JavaScript SetTimeout()</h2> page to change.</p>
<p>Wait 3 seconds (3000 milliseconds) for th
is page to change.</p> <h1 id="demo"></h1>
<h1 id="demo"></h1><script>
<script>
setTimeout( let myPromise = new Promise(function(myResolve,
function() myReject) {
setTimeout(function(){ myResolve("I love JS !
{ myFunction("I love JS !!!");
!"); }, 3000);
}, 3000 });
);
myPromise.then(function(value) {
function myFunction(value) { document.getElementById("demo").innerHTML = v
alue;
document.getElementById("demo").innerHTML });
= value; </script></body></html>
}
</script><body></html>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Call back Promise
<!DOCTYPE html><html><body>
<!DOCTYPE html><html><body>
<h2>JavaScript Callbacks</h2><p id="demo"></p> <h2>JavaScript Promise</h2><p id="demo"></p>
<script> <script>
function myDisplayer(some) { function myDisplayer(some) {
document.getElementById("demo").innerHTML = some; document.getElementById("demo").innerHTML = some;
}
}
function getFile(myCallback) {
let myPromise = new Promise(
let req = new XMLHttpRequest(); function (myResolve, myReject) {
req.open('GET', "mycar.html"); let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() { req.onload = function() {
if (req.status == 200) { if (req.status == 200) {
myCallback(this.responseText); myResolve(req.response);
} else { } else {
myReject("File not Found");
myCallback("Error: " + req.status);
}
}
};
} req.send();
req.send(); });
} myPromise.then(function(value) {myDisplayer(value);},
getFile(myDisplayer); function(error) {myDisplayer(error);}
);</script></body></html>
</script></body></html> USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Async/await
Let’s start with the async keyword. It can be placed before a function, like this:
async function f() {
return 1;
}
The word “async” before a function means one simple thing: a function always returns a promise.
Other values are wrapped in a resolved promise automatically.
For instance, this function returns a resolved promise with the result of 1; let’s test it:

async function f() {


return 1;
}
f().then(alert); // 1
…We could explicitly return a promise, which would be the same:
async function f() {
return Promise.resolve(1);
}
f().then(alert); // 1
So,async ensures that the function returns a promise, and wraps nonpromises in it. Simple enough,
right? But not only that. There’s another keyword, await, that works only inside async functions,
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Await
The syntax:
// works only inside async functions
let value = await promise;
• The keyword await makes JavaScript wait until that promise settles and returns its result.
• Here’s an example with a promise that resolves in 1 second:

async function f() {


let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}
f();
• The function execution “pauses” at the line (*) and resumes when the promise settles, with result becoming its result. So the code above shows “done!” in one
second.
• Let’s emphasize: await literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn’t cost any
CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc.
• It’s just a more elegant syntax of getting the promise result than promise.then, easier to read and write.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Can’t use await in regular functions If we try to use await in nonasync function, there would be a synta
x error:
function f() {
let promise = Promise.resolve(1);
let result = await promise; // Syntax error
}
We may get this error if we forget to put async before a function. As said, await only works inside an asyn
c function.
async function myFunction() { <!DOCTYPE html>
return "Hello"; <html> <body>
} <h2>JavaScript async / await</h2>
Above code is same as bellow code <p id="demo"></p>
async function myFunction() { <script>
return Promise.resolve("Hello"); function myDisplayer(some) {
} document.getElementById("demo").innerHTML =
some;
}
async function myFunction() {return "Hello";}
Here is how to use the Promise: myFunction().then(
myFunction().then( function(value) {myDisplayer(value);},
function(value) { /* code if successful */ }, function(error) {myDisplayer(error);}
function(error) { /* code if some error */ } );</script>
); </body> </html>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<!DOCTYPE html> <html> <body>
<h2>JavaScript async / await</h2>
<p id="demo"></p>

<script>
async function getFile() {
let mayPromise = new Promise(function(myRes
olve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
document.getElementById("demo").innerHTML =
await myPromise;
}
getFile();
</script> </body> </html>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
<!DOCTYPE html> <html><body>
<h2>JavaScript async / await</h2>
<p id="demo"></p><script>
async function getFile() {
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
}
else { myResolve("File not Found");
}
};
req.send();
});
document.getElementById("demo").innerHTML = await myPromise;
}
getFile();
</script></body></html> USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Fetch
• JavaScript can send network requests to the server and load new information whenever it’s needed.

• For example, we can use a network request to:

• Submit an order,
• Load user information,
• Receive latest updates from the server,
• …etc.

• …And all of that without reloading the page!

• There’s an umbrella term “AJAX” (abbreviated Asynchronous JavaScript And XML) for network requests from JavaScript. We don’t have to
use XML though: the term comes from old times, that’s why that word is there. You may have heard that term already.

• There are multiple ways to send a network request and get information from the server.

• The fetch() method is modern and versatile, so we’ll start with it. It’s not supported by old browsers (can be polyfilled), but very well
supported among the modern ones.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


The basic syntax is:
let promise = fetch(url, [options])
url – the URL to access.
options – optional parameters: method, headers etc.
Without options, this is a simple GET request, downloading the contents of the url.
The browser starts the request right away and returns a promise that the calling code should use to get the result.
Getting a response is usually a two-stage process.
First, the promise, returned by fetch, resolves with an object of the built-in Response class as soon as the server responds with headers.
At this stage we can check HTTP status, to see whether it is successful or not, check headers, but don’t have the body yet.
The promise rejects if the fetch was unable to make HTTP-request, e.g. network problems, or there’s no such site. Abnormal HTTP-statuses, such as
404 or 500 do not cause an error.
We can see HTTP-status in response properties:
status – HTTP status code, e.g. 200.
ok – boolean, true if the HTTP status code is 200-299.
For example:
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Second, to get the response body, we need to use an additional method call.

Response provides multiple promise-based methods to access the body in various formats:
response.text() – read the response and return as text,
response.json() – parse the response as JSON,
response.formData() – return the response as FormData object (explained in the next chapter),
response.blob() – return the response as Blob (binary data with type),
response.arrayBuffer() – return the response as ArrayBuffer (low-level representation of binary data),
additionally, response.body is a ReadableStream object, it allows you to read the body chunk-by-chunk, we’ll see an example later.

let url = 'https://api/data';


let response = await fetch(url);
let commits = await response.json(); // read response body and parse as JSON
alert(commits);

For instance, let’s get a JSON-object with latest commits from GitHub:
Or, the same without await, using pure promises syntax:

fetch('ejson.json')
.then(response => response.json())
.then(commits => alert(commits[0].author.login));

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


To get the response text, await response.text() instea
d of .json():
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
let text = await response.text(); // read response body as text
alert(text.slice(0, 80) + '...’);

We can choose only one body-reading method.

If we’ve already got the response with response.text(), then response.json() won’t work, as the body content has already been pro
cessed.

let text = await response.text(); // response body consumed


let parsed = await response.json(); // fails (already consumed)

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Response headers
• The response headers are available in a Map-like headers object in response.headers.
• It’s not exactly a Map, but it has similar methods to get individual headers by name or
iterate over them:

let response = await fetch('ejson.json');

// get one header


alert(response.headers.get('Content-
Type')); // application/json; charset=utf-8

// iterate over all headers


for (let [key, value] of response.headers) {
alert(`${key} = ${value}`);
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Request headers
To set a request header in fetch, we can use the headers
option. It has an object with outgoing headers, like th
is:

let response = fetch(protectedUrl, {


headers: {
Authentication: 'secret'
}
});

USM’s Shriram Mantri Vidyanidhi Info Tech Academy



…But there’s a list of forbidden HTTP headers that we can’t set:

Accept-Charset, Accept-Encoding
• Access-Control-Request-Headers
• Access-Control-Request-Method
• Connection
• Content-Length
• Cookie, Cookie2
• Date
• DNT
• Expect
• Host
• Keep-Alive
• Origin
• Referer
• TE
• Trailer
• Transfer-Encoding
• Upgrade
• Via
• Proxy-*
• Sec-*

These headers ensure proper and safe HTTP, so they are controlled exclusively by the browser.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


<p id="p"></p>
<script>
async function getdata()
{
res= await fetch('ejson.json');
data=await res.json()
let fd="";
for(let x of data)
{console.log(x)
for(let b in x)
{console.log(x[b])
fd+=x[b]+"<br/>"
}
fd+="<hr/>";
}
document.getElementById('p').innerHTML=fd;
}
getdata();
</script>

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


let user = {
POST requests name: 'John',
surname: 'Smith'
To make a POST request, or a request with another method, we };
need to use fetch options: let response = await fetch('/article/fetch/p
method – HTTP-method, e.g. POST, ost/user', {
method: 'POST',
body – the request body, one of:
headers: {
• a string (e.g. JSON-encoded), 'Content-
• FormData object, to submit the data as form/multipart, Type': 'application/json;charset=utf-8'
},
• Blob/BufferSource to send binary data, body: JSON.stringify(user)
• URLSearchParams, to submit the data in x-www-form- });
urlencoded encoding, rarely used.
The JSON format is used most of the time. let result = await response.json();
alert(result.message);
For example, this code submits user object as JSON:

Please note, if the request body is a string, then Content-Type


header is set to text/plain;charset=UTF-8 by default.

But, as we’re going to send JSON, we use headers option to send


application/json instead, the correct Content-Type for JSON-
encoded data. USM’s Shriram Mantri Vidyanidhi Info Tech Academy
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
Json

Javascript Script Object Notation


JSON

• JSON: JavaScript Object Notation.


• JSON is a syntax for storing and exchanging data.
• JSON is text, written with JavaScript object
notation

• JSON is a lightweight data-interchange format


• JSON is "self-describing" and easy to understand
• JSON is language independent *
Why JSON

• It is a lightweight data-interchange format.


• It is easy for humans to read and write.
• It is easy for machines to parse and generate.
• It is based on a subset of the JavaScript Programming Language, Standard
ECMA-262 3rd Edition - December 1999.
• JSON is a text format that is completely language independent but uses
conventions that are familiar to programmers of the C-family of languages,
including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
• These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
• A collection of name/value pairs.
• In various languages, this is realized as an object, record, struct,
dictionary, hash table, keyed list, or associative array.
• An ordered list of values.
• In most languages, this is realized as an array, vector, list, or sequence
• These are universal data structures.
• Virtually all modern programming languages support them in one form or
another.
• It makes sense that a data format that is interchangeable with
programming languages also be based on these structures.
Much Like XML
JSON is plain text
JSON is "self-describing" (human readable)
JSON is hierarchical (values within values)
JSON can be parsed by JavaScript
JSON data can be transported using AJAX

Much Unlike XML


No end tag
Shorter
Quicker to read and write
Can be parsed using built-in JavaScript eval()
Uses arrays
No reserved words
• Why JSON?

• For AJAX applications, JSON is faster and easier than XML:

• Using XML

• Fetch an XML document


• Use the XML DOM to loop through the document
• Extract values and store in variables

• Using JSON

• Fetch a JSON string


• eval() the JSON string
In JSON, they take on these forms:
• An object is an unordered set of name/value
pairs.
• An object begins with { (left brace) and ends
with } (right brace).
• Each name is followed by : (colon) and the
name/value pairs are separated by , (comma).
An array is an ordered collection of values. An array begins with [ (left bracket) and end
with ] (right bracket). Values are separated by , (comma).
<!DOCTYPE html>
<html><body>
<h2>Store and retrieve data from local storage.</h2> • When storing data, the data
<p id="demo"></p> has to be a certain format, and
<button onclick="go()" >set Json String</button> regardless of where you
choose to store it, text is
<button onclick="getdata()">Get Object</button> always one of the legal
formats.
<script>
var myObj, myJSON, text, obj;
• JSON makes it possible to store
function go() JavaScript objects as text.
{

// Storing data:
myObj = { name: "John", age: 31, city: "New York" };

myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
}

function getdata()
{// Retrieving data:
text = localStorage.getItem("testJSON");

obj = JSON.parse(text);

document.getElementById("demo").innerHTML = obj.name + " "+obj.age;


}
</script></body></html>
JSON Values

In JSON, values must be one of the following data types:

a string
a number
an object (JSON object)
an array
a boolean
null

In JavaScript values can be all of the above, plus any other valid JavaScript
expression, including:

a function
a date
undefined
• In JSON, values must be one of the following data types:
In JSON, keys must be strings, written with double quotes

• { "name":“Vita" }
• a string • { “age":30 }
• a number • {"employee": { "name":“Vita", "age":30,
• an object (JSON object) "city": “Mumbai" }
}
• an array • { "employees":[ “Raj", “Mona", “Geeta" ] }

• A Boolean • { "sale":true }

• null • { "middlename":null }
<!DOCTYPE html>
<html><body><p>How to access nested JSON objects.</p><p id="demo"></p>
<button onclick="readdata()">read data</button>
<script>
var myobj = { "name":"John",
"age":30,
"cars": { "car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
function readdata()
{
//document.getElementById("demo").innerHTML += myObj.cars.car2 + "<br>";
//or:
//document.getElementById("demo").innerHTML += myObj.cars["car2"];
for(let x in myobj)
{ console.log(typeof(myobj[x]))
if(typeof(myobj[x]) != "object")
document.getElementById("demo").innerHTML += myobj[x];
else
{ for(let subx in myobj[x])
document.getElementById("demo").innerHTML += myobj[x][subx];}
}
}
</script></body></html>
<!DOCTYPE html> <html> <body>
<p>How to access nested Array.</p>
<p id="demo"></p> <button onclick="readdata()">read data</button>
<script>
var myobj = [
[ "Power Steering",
"Front and rear power windows",
"Anti-lock braking system"
],
[ "Power Windows",
"Automatic Climate Controll"
],
[ "Alloy Wheels",
"Driver Airbag"
],
[ null
],
[ null
]
]
function readdata()
{
for(let x of myobj)
{
for(let subx of x)
document.getElementById("demo").innerHTML += subx +"<br/>";

}
}
</script> </body> </html>
http://www.vidyanidhi.com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
AJAX stands for Asynchronous
JavaScript And XML.
Not a new programming language
• AJAX is not a new programming language, but a technique for
creating better, faster, and more interactive web applications.
• With AJAX, your JavaScript can communicate directly with the
server, using the JavaScript XMLHttpRequest object. With this
object, your JavaScript can trade data with a web server, without
reloading the page.
• AJAX uses asynchronous data transfer (HTTP requests) between the
browser and the web server, allowing web pages to request small
bits of information from the server instead of whole pages.
• The AJAX technique makes Internet applications smaller, faster and
more user-friendly.
• AJAX is a browser technology independent of web server software.
• AJAX is based on the following web standards:
• JavaScript
• XML
• HTML
• CSS
AJAX Uses HTTP Requests

• In traditional JavaScript coding, if you want to get any information


from a database or a file on the server, or send user information to
a server, you will have to make an HTML form and GET or POST data
to the server. The user will have to click the "Submit" button to
send/get the information, wait for the server to respond, then a
new page will load with the results.
• Because the server returns a new page each time the user submits
input, traditional web applications can run slowly and tend to be
less user-friendly.
• With AJAX, your JavaScript communicates directly with the server,
through the JavaScript XMLHttpRequest object
• With an HTTP request, a web page can make a request to, and get a
response from a web server - without reloading the page. The user
will stay on the same page, and he or she will not notice that scripts
request pages, or send data to a server in the background.
• AJAX allows web pages to be updated asynchronously by exchanging data
with a web server behind the scenes. This means that it is possible to
update parts of a web page, without reloading the whole page.

Sending part of data

Receiving data not page.[JSON or XML]

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript
• The keystone of AJAX is the XMLHttpRequest
object.
• Different browsers use different methods to
create the XMLHttpRequest object.
• Internet Explorer uses an ActiveXObject, while
other browsers uses the built-in JavaScript
object called XMLHttpRequest.
The onreadystatechange is event

• The onreadystatechange is event


• The readyState Property
• The readyState property holds the status of the server's response. Each time the readyState
changes, the onreadystatechange function will be executed.
• Here are the possible values for the readyState property:
• State
• Description
• 0 (uninitialized)
• The request is not initialized
• 1(loading)
• The request has been set up
• 2(loaded)
• The request has been sent
• 3(interactive)
• The request is in process
• 4(complete)
• The request is complete
responseText
• The responseText Property
• The data sent back from the server can be
retrieved with the responseText property.
Open/send
• To send off a request to the server, we use the
open() method and the send() method.
• The open() method takes three arguments. The
first argument defines which method to use when
sending the request (GET or POST). The second
argument specifies the URL of the server-side
script. The third argument specifies that the
request should be handled
asynchronously.(default is true)
• The send() method sends the request off to the
server.
• xmlHTTPRequestobj.open()
This method simply keep the configaration ready to
communicate to server(it does not connect the
object to the server)
• xmlHTTPRequestobj.send()
This method connect to server and start download
the data
xmlHTTPRequestobj.onreadystatechange property
is basicaly event which fired when server start
downloading the data.
• xmlHTTPRequestobj.send();
• This method take two argument key(ie.string)
And value which you want to send to server
through post method.
When you send data to server through post you
have to add one more method
xmlHTTPRequestobj.setRequestHeader(‘Content
-Type’, ‘application/x-www-form-urlencoded’)
XMLHttpRequest Object Methods

Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
Specifies the request

method: the request type GET or POST


open(method, url, async,
url: the file location
user, psw)
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
Sends the request to the server
send()
Used for GET requests
Sends the request to the server.
send(string)
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
XMLHttpRequest Object Properties

Property Description
Defines a function to be called when the readyState
onreadystatechange
property changes
Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
readyState
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Returns the status-number of a request
200: "OK"
status 403: "Forbidden"
404: "Not Found"

statusText Returns the status-text (e.g. "OK" or "Not Found")


<!DOCTYPE html><html><body>
Basic example
<h2>The XMLHttpRequest Object</h2>
<h3>IN console type location.protocol and if you run through server it wi
ll print<br/>
"http:" else <br/>
File</h3>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var fd="";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText
}
};
xhttp.open("GET", "ejson.json", true);
xhttp.send();
}
</script></body></html>
<!DOCTYPE html><html><body>
<h2>The XMLHttpRequest Object</h2>
Demo 1 readjson
<h3>IN console type location.protocol and if you run
through server it will print<br/>
[{ "code": "emp101",
"http:" else <br/>
"name": "Tom",
File</h3> "gender": "Male",
<button type="button" onclick="loadDoc()">Request da "annualSalary": "5500",
ta</button>
"dateOfBirth": "6/25/1988"
<p id="demo"></p>
},
<script>
{ "code": "emp102",
function loadDoc() {
"name": "Alex",
var fd=""; "gender": "Male",
var xhttp = new XMLHttpRequest(); "annualSalary": "5700.95",
xhttp.onreadystatechange = function() { "dateOfBirth": "9/6/1982 "
if (this.readyState == 4 && this.status == 200) },
{
{ "code": "emp10",
let arr=JSON.parse(this.responseText);
"name": "Mike",
console.log(arr[0].code) "gender": "Male",
for(let x of arr) "annualSalary": "5900",
{ console.log(x) "dateOfBirth": "12/8/1979"
for(let b in x) },
{ console.log(x[b]) { "code": "emp104",
fd+=x[b]+"<br/>" "name": "Mary",
} "gender": "Female",
fd+="<hr/>"; annualSalary": "6500.826",
} "dateOfBirth": "10/14/1980"
document.getElementById("demo").innerHTML = fd }
} ]
};
xhttp.open("GET", "ejson.json", true);
xhttp.send();
• However, always use POST requests when:
• A cached file is not an option (update a file or
database on the server).
• Sending a large amount of data to the server
(POST has no size limitations).
• Sending user input (which can contain
unknown characters), POST is more robust and
secure than GET.
<!DOCTYPE html>
The URLSearchParams interface defines
<html> <body> <h2>The XMLHttpRequest Object</h2>
<p id="demo"></p> utility methods to work with the query
<form> string of a URL.
<label>Name</label><input name="fnm"/>
<label>Age</label><input name="ag"/> Try:
var paramsString =
<button type="button" onclick="loadDoc()">Send Form data
</button>
"q=URLUtils.searchParams&topic
</form> =api";
<script> var searchParams = new
function loadDoc() { URLSearchParams(paramsString)
var form = document.querySelector('form');
var data=new URLSearchParams(new FormData(form)).toString()
;

console.log(data); //Iterate the search parameters.


var xhttp = new XMLHttpRequest(); for (let p of searchParams) {
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(p);
}
document.getElementById("demo").innerHTML = "Data inserte
d"
}
};

xhttp.open("POST","ejson.php" , true);
xhttp.setRequestHeader('Content-Type','application/x-www-
form-urlencoded');
xhttp.send(data);
}
</script>
Using a Callback Function
• A callback function is a function passed as a
parameter to another function.

• If you have more than one AJAX task in a website,


you should create one function for executing the
XMLHttpRequest object, and one callback
function for each AJAX task.

• The function call should contain the URL and


what function to call when the response is ready.
<!DOCTYPE html>
<html><body>
<div id="demo"></div>
<div id="dd"></div>
<h1>demo</h1>
<button type="button" onclick="loadDoc('ajax_info.txt',myFunction)">get ajax</button>
<button type="button" onclick="loadDoc('read_data.txt',go)">read_data</button>
<script>
function loadDoc(url,cFunction) {
var xhttp;
alert("hello")
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
cFunction(this);
} function myFunction(xhttp){
}; document.getElementById("demo").innerHTML=
xhttp.open("GET",url,true); xhttp.responseText;
}
xhttp.send();
}
function go(xhttp){
document.getElementById("dd").innerHTML=
xhttp.responseText;
}
</script></body></html>
1) What is JavaScript?
JavaScript is a scripting language. It is different from Java language. It is object-based,
lightweight, cross-platform translated language. It is widely used for client-side
validation. The JavaScript Translator (embedded in the browser) is responsible for
translating the JavaScript code for the web browser. More details.

2) List some features of JavaScript.


Some of the features of JavaScript are:

o Lightweight
o Interpreted programming language
o Good for the applications which are network-centric
o Complementary to Java
o Complementary to HTML
o Open source

Cross-platform

3) List some of the advantages of JavaScript.


Some of the advantages of JavaScript are:

o Server interaction is less


o Feedback to the visitors is immediate
o Interactivity is high
o Interfaces are richer

4) List some of the disadvantages of JavaScript.


Some of the disadvantages of JavaScript are:

o No support for multithreading


o No support for multiprocessing
o Reading and writing of files is not allowed
o No support for networking applications.
5) Define a named function in JavaScript.
The function which has named at the time of definition is called a named function. For
example

1. function msg()
2. {
3. document.writeln("Named Function");
4. }
5. msg();

6) Name the types of functions


The types of function are:

o Named - These type of functions contains name at the time of definition. For
Example:
1. function display()
2. {
3. document.writeln("Named Function");
4. }
5. display();

o Anonymous - These type of functions doesn't contain any name. They are
declared dynamically at runtime.

1. var display=function()
2. {
3. document.writeln("Anonymous Function");
4. }
5. display();

7) Define anonymous function


It is a function that has no name. These functions are declared dynamically at runtime
using the function operator instead of the function declaration. The function operator is
more flexible than a function declaration. It can be easily used in the place of an
expression. For example:

1. var display=function()
2. {
3. alert("Anonymous Function is invoked");
4. }
5. display();
8) Can an anonymous function be assigned to a variable?
Yes, you can assign an anonymous function to a variable.

9) In JavaScript what is an argument object?


The variables of JavaScript represent the arguments that are passed to a function.

10) Define closure.


In JavaScript, we need closures when a variable which is defined outside the scope in
reference is accessed from some inner scope.

1. var num = 10;


2. function sum()
3. {
4. document.writeln(num+num);
5. }
6. sum();

11) If we want to return the character from a specific index


which method is used?
The JavaScript string charAt() method is used to find out a char value present at the
specified index. The index number starts from 0 and goes to n-1, where n is the length
of the string. The index value can't be a negative, greater than or equal to the length of
the string. For example:

1. var str="Javatpoint";
2. document.writeln(str.charAt(4));

12) What is the difference between JavaScript and JScript?


Netscape provided the JavaScript language. Microsoft changed the name and called it
JScript to avoid the trademark issue. In other words, you can say JScript is the same as
JavaScript, but Microsoft provides it.
13) How to write a hello world example of JavaScript?
A simple example of JavaScript hello world is given below. You need to place it inside the
body tag of HTML.

1. <script type="text/javascript">
2. document.write("JavaScript Hello World!");
3. </script>
More details.

14) How to use external JavaScript file?


I am assuming that js file name is message.js, place the following script tag inside the
head tag.

1. <script type="text/javascript" src="message.js"></script>


More details.

15) Is JavaScript case sensitive language?


Yes, JavaScript is a case sensitive language. For example:

1. Var msg = "JavaScript is a case-


sensitive language"; //Here, var should be used to declare a variable
2. function display()
3. {
4. document.writeln(msg); // It will not display the result.
5. }
6. display();

16) What is BOM?


BOM stands for Browser Object Model. It provides interaction with the browser. The
default object of a browser is a window. So, you can call all the functions of the window
by specifying the window or directly. The window object provides various properties like
document, history, screen, navigator, location, innerHeight, innerWidth,

More Details: Browser Object Model

17) What is DOM? What is the use of document object?


DOM stands for Document Object Model. A document object represents the HTML
document. It can be used to access and change the content of HTML.

More Details: Document Object Model

18) What is the use of window object?


The window object is created automatically by the browser that represents a window of a
browser. It is not an object of JavaScript. It is a browser object.

The window object is used to display the popup dialog box. Let's see with description.

Method Description

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

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

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

open() opens the new window.

close() closes the current window.

setTimeout() performs the action after specified time like calling function, evaluating expres
More details.

19) What is the use of history object?


The history object of a browser can be used to switch to history pages such as back and
forward from the current page or another page. There are three methods of history
object.

1. history.back() - It loads the previous page.


2. history.forward() - It loads the next page.
3. history.go(number) - The number may be positive for forward, negative for
backward. It loads the given page number.

More details.

20) How to write a comment in JavaScript?


There are two types of comments in JavaScript.
1. Single Line Comment: It is represented by // (double forward slash)
2. Multi-Line Comment: Slash represents it with asterisk symbol as /* write
comment here */

More details.

21) How to create a function in JavaScript?


To create a function in JavaScript, follow the following syntax.

1. function function_name(){
2. //function body
3. }
More details.

22) What are the JavaScript data types?


There are two types of data types in JavaScript:

1. Primitive Data Types - The primitive data types are as follows:

Data Type Description

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

Number represents numeric values, e.g., 100

Boolean represents boolean value either false or true

Undefined represents an undefined value

Null represents null, i.e., no value at all

2. Non-primitive Data Types - The non-primitive data types are as follows:

Data Type Description

Object represents an instance through which we can access members

Array represents a group of similar values

RegExp represents regular expression


More details.

23) What is the difference between == and ===?


The == operator checks equality only whereas === checks equality, and data type, i.e.,
a value must be of the same type.

24) How to write HTML code dynamically using JavaScript?


The innerHTML property is used to write the HTML code using JavaScript dynamically.
Let's see a simple example:

1. document.getElementById('mylocation').innerHTML="<h2>This is heading using JavaScr


ipt</h2>";
More details.

25) How to write normal text code using JavaScript


dynamically?
The innerText property is used to write the simple text using JavaScript dynamically.
Let's see a simple example:

1. document.getElementById('mylocation').innerText="This is text using JavaScript";


More details.

26) How to create objects in JavaScript?


There are 3 ways to create an object in JavaScript.

1. By object literal
2. By creating an instance of Object
3. By Object Constructor

Let's see a simple code to create an object using object literal.

1. emp={id:102,name:"Rahul Kumar",salary:50000}
More details.

27) How to create an array in JavaScript?


There are 3 ways to create an array in JavaScript.
1. By array literal
2. By creating an instance of Array
3. By using an Array constructor

Let's see a simple code to create an array using object literal.

1. var emp=["Shyam","Vimal","Ratan"];
More details.

28) What does the isNaN() function?


The isNan() function returns true if the variable value is not a number. For example:

1. function number(num) {
2. if (isNaN(num)) {
3. return "Not a Number";
4. }
5. return "Number";
6. }
7. console.log(number('1000F'));
8. // expected output: "Not a Number"
9.
10. console.log(number('1000'));
11. // expected output: "Number"

29) What is the output of 10+20+"30" in JavaScript?


3030 because 10+20 will be 30. If there is numeric value before and after +, it treats as
binary + (arithmetic operator).

1. function display()
2. {
3. document.writeln(10+20+"30");
4. }
5. display();

30) What is the output of "10"+20+30 in JavaScript?


102030 because after a string all the + will be treated as string concatenation operator
(not binary +).

1. function display()
2. {
3. document.writeln("10"+20+30);
4. }
5. display();

31) Difference between Client side JavaScript and Server side


JavaScript?
Client-side JavaScript comprises the basic language and predefined objects which are
relevant to running JavaScript in a browser. The client-side JavaScript is embedded
directly by in the HTML pages. The browser interprets this script at runtime.

Server-side JavaScript also resembles client-side JavaScript. It has a relevant


JavaScript which is to run in a server. The server-side JavaScript are deployed only after
compilation.

32) In which location cookies are stored on the hard disk?


The storage of cookies on the hard disk depends on the OS and the browser.

The Netscape Navigator on Windows uses a cookies.txt file that contains all the cookies.
The path is c:\Program Files\Netscape\Users\username\cookies.txt

The Internet Explorer stores the cookies on a file username@website.txt. The path is:
c:\Windows\Cookies\username@Website.txt.

33) What is the real name of JavaScript?


The original name was Mocha, a name chosen by Marc Andreessen, founder of
Netscape. In September of 1995, the name was changed to LiveScript. In December
1995, after receiving a trademark license from Sun, the name JavaScript was adopted.

34) What is the difference between undefined value and null


value?
Undefined value: A value that is not defined and has no keyword is known as
undefined value. For example:

1. int number;//Here, a number has an undefined value.

Null value: A value that is explicitly specified by the keyword "null" is known as a null
value. For example:
1. String str=null;//Here, str has a null value.

35) How to set the cursor to wait in JavaScript?


The cursor can be set to wait in JavaScript by using the property "cursor". The following
example illustrates the usage:

1. <script>
2. window.document.body.style.cursor = "wait";
3. </script>

36) What is this [[[]]]?


This is a three-dimensional array.

1. var myArray = [[[]]];

37) Are Java and JavaScript same?


No, Java and JavaScript are the two different languages. Java is a robust, secured and
object-oriented programming language whereas JavaScript is a client-side scripting
language with some limitations.

38) What is negative infinity?


Negative Infinity is a number in JavaScript which can be derived by dividing the negative
number by zero. For example:

1. var num=-5;
2. function display()
3. {
4. document.writeln(num/0);
5. }
6. display();
7. //expected output: -Infinity

39) What is the difference between View state and Session


state?
"View state" is specific to a page in a session whereas "Session state" is specific to a
user or browser that can be accessed across all pages in the web application.

40) What are the pop-up boxes available in JavaScript?


o Alert Box
o Confirm Box
o Prompt Box

Example of alert() in JavaScript

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

Example of confirm() in JavaScript

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

Example of prompt() in JavaScript

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

41) How can we detect OS of the client machine using


JavaScript?
The navigator.appVersion string can be used to detect the operating system on the
client machine.

42) How to submit a form using JavaScript by clicking a link?


Let's see the JavaScript code to submit the form by clicking the link.

1. <form name="myform" action="index.php">


2. Search: <input type='text' name='query' />
3. <a href="javascript: submitform()">Search</a>
4. </form>
5. <script type="text/javascript">
6. function submitform()
7. {
8. document.myform.submit();
9. }
10. </script>

43) Is JavaScript faster than ASP script?


Yes, because it doesn't require web server's support for execution.

44) How to change the background color of HTML document


using JavaScript?
1. <script type="text/javascript">
2. document.body.bgColor="pink";
3. </script>

45) How to handle exceptions in JavaScript?


By the help of try/catch block, we can handle exceptions in JavaScript. JavaScript
supports try, catch, finally and throw keywords for exception handling.

46) How to validate a form in JavaScript?


1. <script>
2. function validateform(){
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5.
6. if (name==null || name==""){
7. alert("Name can't be blank");
8. return false;
9. }else if(password.length<6){
10. alert("Password must be at least 6 characters long.");
11. return false;
12. }
13. }
14. </script>
15. <body>
16. <form name="myform" method="post" action="abc.jsp" onsubmit="return validatefor
m()" >
17. Name: <input type="text" name="name"><br/>
18. Password: <input type="password" name="password"><br/>
19. <input type="submit" value="register">
20. </form>
Test it Now

Visit here: JavaScript form validation.

47) How to validate email in JavaScript?


1. <script>
2. function validateemail()
3. {
4. var x=document.myform.email.value;
5. var atposition=x.indexOf("@");
6. var dotposition=x.lastIndexOf(".");
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
8. alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
9. return false;
10. }
11. }
12. </script>
13. <body>
14. <form name="myform" method="post" action="#" onsubmit="return validateemail();"
>
15. Email: <input type="text" name="email"><br/>
16.
17. <input type="submit" value="register">
18. </form>
Test it Now

Visit here: JavaScript Email validation.

48) What is this keyword in JavaScript?


The this keyword is a reference variable that refers to the current object. For example:

1. var address=
2. {
3. company:"Javatpoint",
4. city:"Noida",
5. state:"UP",
6. fullAddress:function()
7. {
8. return this.company+" "+this.city+" "+this.state;
9. }
10. };
11. var fetch=address.fullAddress();
12. document.writeln(fetch);

49) What is the requirement of debugging in JavaScript?


JavaScript didn't show any error message in a browser. However, these mistakes can
affect the output. The best practice to find out the error is to debug the code. The code
can be debugged easily by using web browsers like Google Chrome, Mozilla Firebox.

To perform debugging, we can use any of the following approaches:

o Using console.log() method


o Using debugger keyword
50) What is the use of debugger keyword in JavaScript?
JavaScript debugger keyword sets the breakpoint through the code itself. The debugger
stops the execution of the program at the position it is applied. Now, we can start the
flow of execution manually. If an exception occurs, the execution will stop again on that
particular line.. For example:

1. function display()
2. {
3. x = 10;
4. y = 15;
5. z = x + y;
6. debugger;
7. document.write(z);
8. document.write(a);
9. }
10. display();

51) What is the role of a strict mode in JavaScript?


The JavaScript strict mode is used to generates silent errors. It provides "use strict";
expression to enable the strict mode. This expression can only be placed as the first
statement in a script or a function. For example:

1. "use strict";
2. x=10;
3. console.log(x);

52) What is the use of Math object in JavaScript?


The JavaScript math object provides several constants and methods to perform a
mathematical operation. Unlike date object, it doesn't have constructors. For example:

1. function display()
2. {
3. document.writeln(Math.random());
4. }
5. display();

53) What is the use of a Date object in JavaScript?


The JavaScript date object can be used to get a year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.

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

54) What is the use of a Number object in JavaScript?


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

1. function display()
2. {
3. var x=102;//integer value
4. var y=102.7;//floating point value
5. var z=13e4;//exponent value, output: 130000
6. var n=new Number(16);//integer value by number object
7. document.write(x+" "+y+" "+z+" "+n);
8. }
9. display();

55) What is the use of a Boolean object in JavaScript?


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

1. function display()
2. {
3. document.writeln(10<20);//true
4. document.writeln(10<5);//false
5. }
6. display();

56) What is the use of a TypedArray object in JavaScript?


The JavaScript TypedArray object illustrates an array like a view of an underlying binary
data buffer. There is any number of different global properties, whose values are
TypedArray constructors for specific element types.

1. function display()
2. {
3. var arr1= [1,2,3,4,5,6,7,8,9,10];
4. arr1.copyWithin(2) ;
5. document.write(arr1);
6. }
7. display();

57) What is the use of a Set object in JavaScript?


The JavaScript Set object is used to store the elements with unique values. The values
can be of any type i.e. whether primitive values or object references. For example:

1. function display()
2. {
3. var set = new Set();
4. set.add("jQuery");
5. set.add("AngularJS");
6. set.add("Bootstrap");
7. for (let elements of set) {
8. document.writeln(elements+"<br>");
9. }
10. }
11. display();

58) What is the use of a WeakSet object in JavaScript?


The JavaScript WeakSet object is the type of collection that allows us to store weakly
held objects. Unlike Set, the WeakSet are the collections of objects only. It doesn't
contain the arbitrary values. For example:

1. function display()
2. {
3. var ws = new WeakSet();
4. var obj1={};
5. var obj2={};
6. ws.add(obj1);
7. ws.add(obj2);
8. //Let's check whether the WeakSet object contains the added object
9. document.writeln(ws.has(obj1)+"<br>");
10. document.writeln(ws.has(obj2));
11. }
12. display()

59) What is the use of a Map object in JavaScript?


The JavaScript Map object is used to map keys to values. It stores each element as key-
value pair. It operates the elements such as search, update and delete on the basis of
specified key. For example:

1. function display()
2. {
3. var map=new Map();
4. map.set(1,"jQuery");
5. map.set(2,"AngularJS");
6. map.set(3,"Bootstrap");
7. document.writeln(map.get(1)+"<br>");
8. document.writeln(map.get(2)+"<br>");
9. document.writeln(map.get(3));
10. }
11. display();

60) What is the use of a WeakMap object in JavaScript?


The JavaScript WeakMap object is a type of collection which is almost similar to Map. It
stores each element as a key-value pair where keys are weakly referenced. Here, the
keys are objects and the values are arbitrary values. For example:

1. function display()
2. {
3. var wm = new WeakMap();
4. var obj1 = {};
5. var obj2 = {};
6. var obj3= {};
7. wm.set(obj1, "jQuery");
8. wm.set(obj2, "AngularJS");
9. wm.set(obj3,"Bootstrap");
10. document.writeln(wm.has(obj2));
11. }
12. display();
1. Use of java script

2. Const var let

3. Anonymous function => self invoking function and callback

4. OOPS class extends duper new.target toString overriding immutable object

5. DOM getElementById(), getElementsByTagName() getElementsByClassName()


ClassLIst/add/remove/ Toggle/replace

6. how to create tag at runtime

7. catch try finally

8. Array and string function

9. why regular expression

10. Ajax / Async-await/ Promise

11. events onmoseover/out/leave/enter keyup/down/press oninput blure/focus onchane

12. how to redirect

13. what is ?? and ?. = obj?.name

14. datatypes typeof usestrict

15. what is closure

You might also like