JavaScript Merged Merged
JavaScript Merged Merged
com/
ketkiacharya.net@gmail.com
Ketki Acharya
From: SM VITA ATC
of CDAC
9769201036
ketkiacharya.net@gm
ail.com
<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>
<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.
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
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
White Space
JavaScript ignores extra spaces. You can add white
space to your script to make it more readable. The
following lines are equivalent:
document.write("Hello \
World!")
document.write \ ("Hello
World!")
Properties
<script type="text/javascript">
var txt="Hello World!“
document.write(txt.length)
</script>
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Methods
document.write(“upper”+str.toUpperCase())
</script>
window
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
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:
// 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.
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“
};
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.
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.
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
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
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:
// later
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.
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;
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.
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:
console.log(clonedColors); console.log(clonedColors);
//"[red,green,blue]" //"[red,green,blue]"
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:
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:
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
You must declare variable with var, let or const key word
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>
// 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
MY_OBJECT
Key=value
otherValue
Name=“vita”
MY_OBJECT.Key = 'otherValue';
MY_OBJECT.Name = ‘vita';
iter
1 2 3 5 'key': 'value
MY_OBJECT
'key’: ‘Othervalue’
MY_OBJECT
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
console.log(r);//Undefine }
document.write(typeof(go)); //function
document.write("<hr/>");
</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.
</script>
5
• 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).
<script> x y z
"use strict";
0 1 2
function myFunction(x, y, z)
{ return x+y+z;
} args
console.log(r);
</script>
• Any argument in the argument list can use spread syntax and it can be used multiple times.
v w y
x
<script>
-1 0 1 2
"use strict";
function myFunction(v, w, x, y, z) { }
myFunction(-1, ...args, 2) -1 0 1 2
<script> args
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
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
</script>
}
go function(w)
) {
w
Alert( w(5));
}
</script>
<script>
function mydata(param1, param2, callback) {
alert('Started learning at.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}
</script>
</script>
})(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
var sum = function(num1, num2) { var sum1 = (num1, num2) => num1 + num2;
return num1 + num2; document.write(sum1(5,7));
};
document.write(sum(5,5));
}
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();)
console.log(map1);
// expected output: Array [2, 8, 18, 32]
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)
The constructor object has its properties and methods defined with the
keyword 'this' in front of it, whereas the literal version does not.
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
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
<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>
document getElementById()
New ParagraphElement ()
innerHTML
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
obj sayhi
• Here’s an example of a class expression:
Alert()
'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} }
alert open
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
}
Vita.DAC
Import vita from ‘./vita’
}
set _cbalance(value) {this.#balance=value;}
get _cbalance(){ return this.#balance;}
}
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
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.
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()
}
}
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();
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.
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);
•
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
console.log([...pentagon.getSides()]); // [1,2,3,4,5]
console.log(generateSequence())
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
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
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.
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.
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.
That’s just awful, one may even have problems understanding such code.
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 ?..
let x = 0;
admin() {
alert("I am admin");
};
userAdmin.admin?.(); // I am admin
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
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.
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;
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;
Due to safety reasons, JavaScript forbids using ?? together with && and || operators, unless the precedence is explicitly specified with
parentheses.
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 ||.
alert(x); // 2
• The nullish coalescing operator ?? provides a short way to choose the first
“defined” value from a list.
• The operator ?? has a very low precedence, only a bit higher than ? and =, so consider
adding parentheses when using it in an expression.
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
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
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:
</html>
</body>
</html>
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).
•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>
•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.
scrollIntoView
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>
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.
document.body.style.overflow = "hidden".
<button onclick="document.body.style.overflow = 'hidden'">document.body.style.overflow = ‘hidden’</button>
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.
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
DOM
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
DOM
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>
}
</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
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
x
var x = document.getElementById("myDIV").classList;
<p>Click the button to display the class names of the div element.</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
document.getElementById("demo").innerHTML = y[2];
}
</script>
classList.remove("anotherClass") : Remove CSS class Dynamically
<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");
document.getElementById("demo").innerHTML = x;
}
</script>
<!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");
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>
}
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>
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/>");
document.write("<hr/>");
for(x of za) 0 1 2 3
document.write(x)
document.write("<p>") 3 8 9 2
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:
<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">
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
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:
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.
• 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 ]
<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
}
index = -2;
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.
Banana,Orange,Kiwi,Kiwi
<script>
const array1= [1,4,9,16];
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/>");
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>
<script type="text/javascript">
<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.
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/>")
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
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
<!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>
<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>
<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>
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
• 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:
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>
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:
</script>
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.
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()
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
document.write("<hr/>")
a=(Math.random()*4);
0.5626264433314665
document.write(a);
document.write("<hr/>")
x=Math.floor(a);
0
document.write(x);
</script>
<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()">
</body> </html>
Math.round(4.7); // returns 5
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
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
<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)
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.
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
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>
window
</script></head><body>
<form name="frm" action="a.html" onsubmit="return true">
name<input name="t1"/>
</form></body> </html>
}
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>
`
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
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>
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>
}
<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>
</script>
isNaN(“5”)==check entered data is number or not?
Even if number is in “” it will call valueOf()
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>
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
<script>
result = str.split("|");
document.write(result)
// iterate over result array
{ alert(result[i]);
}
alert(result)
</script>
document.write(result)
</script>
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>
//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";
// 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>
</script>
/abc/
string.match(regex)
string.replace(regex, "text")
| means OR
• /abc|def|g/ matches lines with "abc", "def", or "g“
• /abc|def|g/.test(“hello go to school”)
? means 0 or 1 occurrences
• /Martina?/ matches lines with "Martin" or "Martina"
• /Dan(iel)?/ matches lines with "Dan" or "Daniel"
new RegExp(string)
new RegExp(string, flags)
<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>
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
<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>
}
</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>
<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>
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
</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>
<html>
<body>
</html>
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
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>
• 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.
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
• 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.
• 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.
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.
Here’s an example of a promise constructor and a simple executor function with “producing code” that takes
time (via setTimeout):
// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve("done"), 1000);
});
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:
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.
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.
If we’re interested only in successful completions, then we can provide only one function argument to .then:
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:
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:
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:
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.
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
<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
• Submit an order,
• Load user information,
• Receive latest updates from the server,
• …etc.
• 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.
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.
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));
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.
Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com
Json
• Using XML
• Using JSON
// 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);
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
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
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"
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.
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
1. function msg()
2. {
3. document.writeln("Named Function");
4. }
5. msg();
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();
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.
1. var str="Javatpoint";
2. document.writeln(str.charAt(4));
1. <script type="text/javascript">
2. document.write("JavaScript Hello World!");
3. </script>
More details.
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
setTimeout() performs the action after specified time like calling function, evaluating expres
More details.
More details.
More details.
1. function function_name(){
2. //function body
3. }
More details.
1. By object literal
2. By creating an instance of Object
3. By Object Constructor
1. emp={id:102,name:"Rahul Kumar",salary:50000}
More details.
1. var emp=["Shyam","Vimal","Ratan"];
More details.
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"
1. function display()
2. {
3. document.writeln(10+20+"30");
4. }
5. display();
1. function display()
2. {
3. document.writeln("10"+20+30);
4. }
5. display();
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.
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.
1. <script>
2. window.document.body.style.cursor = "wait";
3. </script>
1. var num=-5;
2. function display()
3. {
4. document.writeln(num/0);
5. }
6. display();
7. //expected output: -Infinity
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
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()"/>
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()"/>
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);
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();
1. "use strict";
2. x=10;
3. console.log(x);
1. function display()
2. {
3. document.writeln(Math.random());
4. }
5. display();
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();
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();
1. function display()
2. {
3. document.writeln(10<20);//true
4. document.writeln(10<5);//false
5. }
6. display();
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();
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();
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()
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();
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