Javascript Course Material
Javascript Course Material
Introduction to JavaScript:
JavaScript is a programming language initially designed to interact with elements of web pages.
JavaScript allows you to add interactivity to a web page. Typically, you use JavaScript with HTML and
CSS to enhance a web page’s functionality, such as validating forms, creating interactive maps, and
displaying animated charts.
When a web page is loaded, i.e., after HTML and CSS have been downloaded, the JavaScript engine
in the web browser executes the JavaScript code. The JavaScript code then modifies the HTML and
CSS to update the user interface dynamically.
The JavaScript engine is a component of web browsers responsible for interpreting and executing
JavaScript code. It includes a parser to analyze the code, a compiler to convert it into machine code,
and an interpreter to run the compiled code.
JavaScript History
In 1995, JavaScript was developed by Brendan Eich, a Netscape developer. Initially named Mocha, it
was later renamed to LiveScript.
Netscape decided to rebrand LiveScript to JavaScript to capitalize on the popularity of Java. The
decision was made shortly before the release of Netscape Navigator 2 web browser, leading to the
introduction of JavaScript version 1.0.
Netscape launched JavaScript 1.1 in Netscape Navigator 3. In the meantime, Microsoft introduced its
web browser called Internet Explorer 3 (IE 3) as a competitor to Netscape. However, IE featured its
own JavaScript implementation called JScript. Microsoft used the name JScript to avoid potential
licensing conflicts with Netscape.
At this time, JavaScript lacked standardized syntax and features, prompting the community to
advocate for the standardization of the language.
In 1997, JavaScript 1.1 was proposed to the European Computer Manufacturers Association (ECMA)
as a proposal. Technical Committee #39 (TC39) was assigned the task of standardizing the language,
maiming to transform it into a general-purpose, cross-platform, and vendor-neutral scripting
language.
1
TC39 came up with ECMA-262, establishing a standard for defining a new scripting language called
ECMAScript (often pronounced Ek-ma-script).
Following that, the International Organization for Standardization and International Electrotechnical
Commissions (ISO/IEC) adopted ECMAScript (ISO/IEC-16262).
To insert JavaScript into an HTML page, you use the <script> element. There are two ways to use
the <script> element in an HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
<script>
console.log('Hello, Krishna!');
</script>
</head>
<body>
</body>
</html>
First, create a file whose extension is .js, for example, app.js and place it in the js directory. Note that
while placing the JavaScript file in the js directory is not required, it is considered good practice.
Then, use the URL to the JavasScript source code file in the src attribute of the <script> element.
console.log('Hello, Krishna!');
2
<script src="app.js"></script>
</head>
<body>
</body>
</html>
To modify how the browser load and execute JavaScript files, you use one of two attributes of the
<script> element: async and defer. These attributes take effect only on the external script files.
async attribute
The async attribute instructs the web browser to execute the JavaScript file asynchronously.
However, it does not guarantee that the script files will execute in the order in which they appear. For
example:
The app.js file might execute before the service.js file. Therefore, you must ensure that there is no
dependency between them.
defer attribute
The defer attribute requests the web browser to execute the script file after the HTML document has
been parsed.
JavaScript Syntax
• whitespace
• statements
• identifiers
• comments
• expressions
• keywords
Whitespace
Whitespace refers to characters that provide the space between other characters. JavaScript has the
following whitespace:
• Carriage return
• Space
• New Line
• tab
3
JavaScript engine ignores whitespace. However, you can use whitespace to format the code to make
it easy to read and maintain.
It is equivalent to the following code that uses whitespace. Hence, this code is much easier to read:
if (formatted) {
Note that JavaScript bundlers remove all whitespace from JavaScript files and put them into a single
file for deployment. By doing this, JavaScript bundlers make the JavaScript code lighter and faster to
load in web browsers.
Statements
A statement is a piece of code that either declares a variable or instructs the JavaScript engine to
perform a task. A simple statement is concluded by a semicolon (;).
Although the semicolon (;) is optional; you should always use it to terminate a statement.
For example, the following declares a variable and shows it to the console:
console.log(message);
Blocks
A block is a sequence of zero or more simple statements. A block is delimited by a pair of curly
brackets {}.
For example:
if (window.localStorage) {
Identifiers
An identifier is a name you choose for variables, parameters, functions, classes, etc.
An identifier name starts with a letter (a-z, or A-Z), an underscore(_), or a dollar sign ($) and is
followed by a sequence of characters including (a-z, A-Z), numbers (0-9), underscores (_), and dollar
signs ($).
Note that the letter is not limited to the ASCII character set and may include extended ASCII or
Unicode, though it is not recommended.
Identifiers in JavaScript are case-sensitive. For example, the message is different from the Message.
4
Comments
Comments allow you to include notes or hints in JavaScript code. When executing the code, the
JavaScript engine ignores the comments.
Single-line comments
A single-line comment starts with two forward-slashes characters (//). It turns all the text following
the // on the same line into a comment. For example:
Block comments
A delimited comment begins with a forward slash and asterisk /* and ends with the opposite */ as in
the following example:
Expressions
2+1
JavaScript defines a list of reserved keywords that have specific uses. Consequently, you cannot use
the reserved keywords as identifiers or property names due to the language rules.
The following table displays the JavaScript reserved words as defined in ECMA-262:
function if import
in switch typeof
yield const do
5
for instanceof this
var
In addition to the reserved keywords, ECMA-252 also defines a list of future reserved words that
cannot be used as identifiers or property names:
implements public
A Variable is a label that References a value like a number or string. To Declare a Variable, we use var
keyword followed by identifier.
var message;
var a;
var condition;
ES6
let
const
A Variable name can be any valid identifier. By default, the Variable has a special value undefined if
we have not assigned a value to it.
var message;
var Message;
var msg;
var mSg;
Variable names can only contain letters, numbers, underscores, or dollar signs and cannot contain
spaces. (a-z / A-Z),(0-9),$,_ but spaces not allowed. Variable names must begin with a letter, an
underscore(_)or $ Variable names Cannot use reserved keywords
6
JavaScript has the primitive data types:
1.null
2.undefined
3.boolean
4.number
5.string
6.symbol (ES6)
7.bigint (ESNext)
JavaScript is a dynamically typed language, meaning that a variable isn’t associated with a specific
type. In other words, a variable can hold a value of different types.
For example:
To determine the current type of the value stored in a variable, you use the typeof operator:
console.log(typeof(counter)); // "number"
counter = false;
console.log(typeof(counter)); // "boolean"
counter = "Hi";
console.log(typeof(counter)); // "string"
Output:
"number"
"boolean"
"string"
The undefined type is a primitive type that has only one value undefined. By default, when a variable
is declared but not initialized, it defaults to undefined.
var counter;
console.log(counter); // undefined
7
console.log(typeof counter); // undefined
In this example, the counter is a variable. Since counter hasn’t been initialized, it is assigned the
value undefined. The type of counter is also undefined.
It’s important to note that the typeof operator also returns undefined when you call it on a variable
that hasn’t been declared:
The null type is the second primitive data type that also has only one value null. For example:
The typeof null returns object is a known bug in JavaScript. A proposal to fix was rejected due to the
potential to break many existing sites.
JavaScript uses the number type to represent both integer and floating-point numbers.
The following statement declares a variable and initializes its value with an integer:
To represent a floating-point number, you include a decimal point followed by at least one number.
For example:
Note that JavaScript automatically converts a floating-point number into an integer if the number
appears to be a whole number.
The reason is that Javascript always wants to use less memory since a floating-point value uses twice
as much memory as an integer value. For example:
To get the range of the number type, we use Number.MIN_VALUE and Number.MAX_VALUE. For
example:
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
Also, you can use Infinity and -Infinity to represent the infinite number. For example:
8
console.log(-Number.MAX_VALUE - Number.MAX_VALUE); // -Infinity
NaN
NaN stands for Not a Number. It is a special numeric value that indicates an invalid number. For
example, the division of a string by a number returns NaN:.
console.log('a'/2); // NaN;
console.log(NaN/2); // NaN
In JavaScript, a string is a sequence of zero or more characters. A string literal begins and ends with
either a single quote(') or a double quote (").
A string that begins with a double quote must end with a double quote, and a string that begins with
a single quote must also end with a single quote. For example:
If you want to use single quotes or double quotes in a literal string, you need to use the backslash to
escape them. For example:
var message = 'I\'m also a valid string'; // use \ to escape the single quote (')
JavaScript strings are immutable, meaning that they cannot be modified once created. However, you
can create a new string from an existing one. For example:
In this example:
Second, use the + operator to combine 'JavaScript' with ' String' to make its value as 'Javascript
String'.
Behind the scene, the JavaScript engine creates a new string that holds the new string 'JavaScript
String' and destroys the original strings 'JavaScript' and ' String'.
The following example attempts to modify the first character of the string JavaScript:
var s = 'JavaScript';
9
s[0] = 'j';
console.log(s)
'JavaScript'
But not:
'javaScript'
The boolean type has two literal values: true and false in lowercase. The following example declares
two variables that hold the boolean values.
JavaScript allows values of other types to be converted into boolean values of true or false.
To convert values of other types into boolean values, you use the Boolean() function.
undefined undefined
For example:
console.log(Boolean('Hi'));// true
console.log(Boolean('')); // false
console.log(Boolean(20)); // true
console.log(Boolean(Infinity)); // true
console.log(Boolean(0)); // false
console.log(Boolean(null));// false
JavaScript introduced a new primitive type in ES6: the symbol. Unlike other primitive types, the
symbol type does not have a literal form.
10
var s1 = Symbol();
The Symbol function creates a new unique value every time you call it.
Note that you’ll learn more about symbols in the symbol tutorial.
The bigint type represents the whole numbers that are larger than 253 – 1. To form a bigint literal
number, you append the letter n at the end of the number:
console.log(typeof(pageView)); // 'bigint'
The numeric separator allows you to create a visual separation between groups of digits by using
underscores (_) as separators.
For example, the following number is very difficult to read especially when it contains long digit
repetitions:
JavaScript allows you to use numeric separators for both integer and floating-point numbers. For
example:
It’s important to note that all numbers in JavaScript are floating-point numbers.
Also, you can use the numeric separators for factional and exponent parts. For example:
It’s important to notice that you can use the numeric separator for bigint literal, binary literal, octal
literal, and hex literal. For example:
// BigInt
// binary
11
let nibbles = 0b1011_0101_0101;
// octal
// hex
JavaScript Objects
In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a
property. The key of a property can be a string. The value of a property can be any value, e.g., a
string, a number, an array, and even a function.
JavaScript provides you with many ways to create an object. The most commonly used one is to use
the object literal notation.
The following example creates an empty object using the object literal notation:
To create an object with properties, you use the key:value within the curly braces. For example, the
following creates a new person object:
let person = {
firstName: 'Krishna',
lastName: 'Mohan'
};
The person object has two properties firstName and lastName with the corresponding values
'Krishna' and 'Mohan'.
When an object has multiple properties, you use a comma (,) to separate them like the above
example.
Accessing properties
To access a property of an object, you use one of two notations: the dot notation and array-like
notation.
The following illustrates how to use the dot notation to access a property of an object:
objectName.propertyName
For example, to access the firstName property of the person object, you use the following
expression:
person.firstName
12
This example creates a person object and shows the first name and last name to the console:
let person = {
firstName: 'Krishna',
lastName: ‘Mohan’
};
console.log(person.firstName);
console.log(person.lastName);
The following illustrates how to access the value of an object’s property via the array-like notation:
objectName['propertyName']
For example:
let person = {
firstName: 'Krishna',
lastName: ‘Mohan’
};
console.log(person['firstName']);
console.log(person['lastName']);
When a property name contains spaces, you need to place it inside quotes. For example, the
following address object has the 'building no' as a property:
let address = {
state: 'CA',
country: 'USA'
};
To access the 'building no' property, you need to use the array-like notation:
address['building no'];
address.'building no';
Error:
13
Note that it is not a good practice to use spaces in the property names of an object.
Reading from a property that does not exist will result in an undefined. For example:
console.log(address.district);
Output:
undefined
To change the value of a property, you use the assignment operator (=). For example:
let person = {
firstName: 'Krishna',
lastName: ‘Mohan’
};
person.firstName = 'Jaanu';
console.log(person);
Output:
In this example, we changed the value of the firstName property of the person object from 'Krishna'
to 'Jaanu'.
Unlike objects in other programming languages such as Java and C#, you can add a property to an
object after object creation.
The following statement adds the age property to the person object and assigns 25 to it:
person.age = 25;
delete objectName.propertyName;
The following example removes the age property from the person object:
delete person.age;
If you attempt to reaccess the age property, you’ll get an undefined value.
propertyName in objectName
14
The in operator returns true if the propertyName exists in the objectName.
The following example creates an employee object and uses the in operator to check if the ssn and
employeeId properties exist in the object:
let employee = {
firstName: 'Peter',
lastName: ‘Mohan’,
employeeId: 1
};
console.log('ssn' in employee);
console.log('employeeId' in employee);
Output:
false
true
JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value is called an element specified by an
index
JavaScript provides you with two ways to create an array. The first one is to use the Array constructor
as follows:
If you know the number of elements that the array will hold, you can create an array with an initial
size as shown in the following example:
To create an array and initialize it with some elements, you pass the elements as a comma-separated
list into the Array() constructor.
For example, the following creates the scores array that has five elements (or numbers):
Note that if you use the Array() constructor to create an array and pass a number into it, you are
creating an array with an initial size.
15
However, when you pass a value of another type like string into the Array() constructor, you create an
array with an element of that value. For example:
let scores = new Array(1, 2, 3); // create an array with three numbers 1,2 3
let signs = new Array('Red'); // creates an array with one element 'Red'
JavaScript allows you to omit the new operator when you use the Array() constructor. For example,
the following statement creates the artists array.
The more preferred way to create an array is to use the array literal notation:
The array literal form uses the square brackets [] to wrap a comma-separated list of elements.
The following example creates the colors array that holds string elements:
To create an empty array, you use square brackets without specifying any element like this:
JavaScript arrays are zero-based indexed. In other words, the first element of an array starts at index
0, the second element starts at index 1, and so on.
To access an element in an array, you specify an index in the square brackets []:
arrayName[index]
The following shows how to access the elements of the mountains array:
console.log(mountains[0]); // 'Everest'
console.log(mountains[1]); // 'Fuji'
To change the value of an element, you assign that value to the element like this:
mountains[2] = 'K2';
console.log(mountains);
16
Output:
Typically, the length property of an array returns the number of elements. The following example
shows how to use the length property:
console.log(mountains.length); // 3
The following explains some basic operations on arrays. You’ll learn advanced operations such as
map(), filter(), and reduce() in the next tutorials.
To add an element to the end of an array, you use the push() method:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
seas.push('Red Sea');
console.log(seas);
Output:
[ 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea', 'Red Sea' ]
To add an element to the beginning of an array, you use the unshift() method:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
seas.unshift('Red Sea');
console.log(seas);
Output:
[ 'Red Sea', 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea' ]
To remove an element from the end of an array, you use the pop() method:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
console.log(lastElement);
Output:
Baltic Sea
17
4) Removing an element from the beginning of an array
To remove an element from the beginning of an array, you use the shift() method:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
console.log(firstElement);
Output:
Black Sea
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
console.log(index); // 2
console.log(Array.isArray(seas)); // true
JavaScript Operators :
Arithmetic Operators
* (Asterik )
var a = 20;
var b = 6;
console.log(a % b);// 2
Assignment Operators :
= a=b
-= a -= b a=a-b
18
*=
/=
%=
&= AND
|= OR
^= XOR
>>>=
>
<
<=
>=
== equal
!= not equal
var a = '20';
var b = 20;
19
Logical Operators
|| (Logical OR)
console.log(!undefined); // true
console.log(!null); // true
console.log(!20); // false
console.log(!0); // true
console.log(!NaN); // true
console.log(!{}); // false
console.log(!''); // true
console.log(!'Text'); // false
console.log(!false); // true
console.log(!true); // false
Logical OR ||
a b a || b
a b a && b
var a = true;
var b = false;
console.log(a || b);
20
var a = 10 && 20;
console.log(a);
var b = 30 || 40;
console.log(b);
var a, b = 3 && 4;
a += b; // a = a + b
console.log(a,b); // NaN 4
var a = 3 && 4, b = 5 || 6;
console.log(a + b); // 9
||=
&&=
x ??= y
x ?? (x = y)
** Objects
console.log(title);
Exponentiation Operators
**
var result = 2 ** 2;
console.log(result); // 4
result = 2 ** 3;
console.log(result); // 8
21
Conditional Statements :
if
if..else
Syntax : if(condition)
statement;
if(condition){
// statements
if(a == 20){
console.log('Equal to 20');
}else{
Example :
var a = 60;
if(a == 20)
console.log('Equal to 20');
console.log("Equals to 30");
console.log("Equals to 40");
22
}
console.log("Equals to 50");
else
Example :
var message;
// if(age >= 16 ){
// }else{
// }
console.log(message);
Switch
switch (expression){
case value1 :
statement1;
break;
case value2 :
statement2;
break;
23
default:
statement;
values, and executes the statement associated with the matching case value
Example :
var day = 4;
var dayName;
switch(day) {
case 1 :
dayName = "Sunday";
break;
case 2 :
dayName = "Monday";
break;
case 3 :
dayName = "Tuesday";
break;
case 4 :
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
24
default:
console.log(dayName);
Loops
while statement creates a loop that executes a block as long as a condition evaluates to true.
while(expression){
// statements
var count = 1;
console.log(count); // 1 3 5 7 9
count += 2;
-------------------------------------------------------------------------------------------------------------------------------------
while(count > 0 ){
console.log(count); // 10 8 6 4 2
count -= 2;
--------------------------------------------------------------------------------------------------------------------------------------
do{
// statement
} while(expression);
var count = 1;
do{
console.log(count);
count += 2;
25
var count = 10;
do{
console.log(count);
count -= 2;
}while(count > 0 );
forloop
syntax :
// statements
The for statement executes the initializer only once the loop
initializer.
for( ; ; ){ }
Example :
console.log(i);
-----------------------------------------------------------------------------------------------------------
26
var sum = 0;
console.log(sum);
if(i == 5){
break;
console.log(i);
continue statement terminates the execution of the statement in the current iteration of a loop such
as in for,while and do..while loop and Immediately continues to the next iteration.
continue;
console.log(i);
label :we can use the label for later use. The label can be any valid identifier. Once defining the label,
we can reference it in the break or continue statement.
Example :
console.log(i,j);
27
functions
To avoid repeating the same code all over the places, we can use a function to wrap that code and
reuse it. function is a block of code to implement code reusability.
syntax:
function fnName(parameters){
// function body
To declare a function, we use the function keyword, followed by the function name,
To use a function, we need to call it. calling a function is also known as invoking a function.
To call a function, we use its name followed by arguments enclosing in the parenthesis
fnName(arguments);
greet("Krishna"); // arguments
greet("Abhinav");
getData()
isValid()
function greet(){
console.log("Hello");
greet();
function greet(name){
greet("Abhi");
greet("Balu");
greet("Ciya");
28
function sum(a,b){
console.log(a + b);
sum(2,3);
sum(4,5);
sum(7,8);
Inside the function declaration, we use return statement to return a value from a function explicitly.
function sum(a,b){
return a + b;
var x = sum(2,3);
var y = sum(4,5);
var z = sum(7,8);
console.log(x,y,z);
arguments
we can access an object called arguments that represents the named arguments of the function.
The arguments object behaves like an array though it is not an instance of the Array type.
function add(){
var sum = 0;
console.log(arguments);
sum += arguments[i];
return sum;
console.log(add(1,2,3));
console.log(add(5,6,8,9,2,4,2));
console.log(add(7,2));
29
Assign function to a Variable
function add(){
var sum = 0;
sum += arguments[i];
return sum;
console.log(result);
function average(a,b,fn){
return fn(a,b)/2;
function add(a,b){
return a + b;
console.log(result);
Example :
function cmToIn(cm){
return cm/2.54;
function inToCm(inch){
function convert(fn,val){
return fn(val);
30
console.log(convert(cmToIn,10));
console.log(convert(inToCm,10));
console.log('Anonymous function');
greet();
(function(){
})();
Recursive functions
function countDown(fromNumber){
console.log(fromNumber);
countDown(nextNumber);
countDown(5);
return a + b;
console.log(sum());
31
Object Methods
An Object is a collection of key/value pairs of properties . when the value is a function the property
becomes a method. Methods used to describe the object behaviors.
var obj = {
oName : "abc",
oAge : 23,
greet : function(){
console.log("Hello")
obj.greet();
var person = {
firstName : 'Abhi',
lastName : 'Krishna',
greet(){
console.log("Hello ");
},
age : 21
};
person.greet();
Inside a method, the 'this' value References the object that invokes the method.
var person = {
firstName : 'Abhi',
lastName : 'Krishna',
getFullName(){
};
console.log(person.getFullName());
var student = {
firstName : 'Abhi',
32
lastName : 'Krishna',
age : 23,
marks : [50,60,70,50,60],
getTotalMarks(){
};
var student = {
firstName : 'Abhi',
lastName : 'Krishna',
getFullName(){
},
age : 21,
marks : [30,40,50,60,70]
};
console.log(person);
console.log(person.getFullName());
Constructor function
We need to create similar objects like person object, for that we use a constructor function to define
a custom type and the "new" operator to create multiple objects from this type.
function Person(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
33
console.log(person1);
console.log(person2);
Objects can inherit features from one to another using prototypes. Every object has its own property
called prototype.
Function Context :
- Function invocation
- Method invocation
- Constructor invocation
Object Properties
[[]]
- Data Properties
- Accessor Properties
Data Properties
4 attributes
delete operator
1. An Object
34
var person = {};
person.age = 25;
console.log(person);
delete person.age;
console.log(person);
Example :
'use strict';
person.age = 25;
console.log(person);
delete person.age;
console.log(person);
Object.defineProperty(person,'age',{
configurable : false,
writable : false,
value : 24
});
console.log(person);
delete person.age;
person.age = 30;
console.log(person);
Accessor Properties
4 attributes
35
Example :
var person = {
firstName : 'Abhi',
lastName : 'Krishna'
};
Object.defineProperty(person,'age',{
configurable : false,
writable : false,
value : 24
});
Object.defineProperty(person,'fullName',{
get : function(){
});
Object.defineProperties(person,{
address : {
value : "Hyderabad"
},
salary : {
value : 10000
})
console.log(person);
delete person.age;
person.age = 30;
console.log(person);
console.log(Object.getOwnPropertyDescriptor(person,'firstName'));
36
Advanced Function Types / methods
In JavaScript all functions are objects. They are the instances of the Function type. Because functions
are objects, they have properties and methods like other object.
instanceof
- property / operator
length
prototype
function declaration.
apply()
call()
bind()
console.log(message);
console.log(message);
37
say.call(car,'How many wheelsss ?');
The apply() and call() methods call a function with a given this value and arguments.
The difference between apply() and call() is that we need to pass the arguments to
the apply() method as an array-like object, where as we pass the arguments to the
bind() method creates a new function instance whose this value is bound to the
var car = {
speed : 50,
start : function(){
var aircraft = {
speed : 200,
fly : function(){
console.log('Flying');
comp();
closures - is a function that References Variables in the outer scope from its inner scope.
function greeting(){
function sayHi(){
console.log(msg);
38
return sayHi;
var hi = greeting();
hi();
Lexical scoping describes how the Javascript engine uses the location of the variable in the code to
determine where that Variable is available.
The Document Object Model (DOM) is an Application Programming Interface(API) for manipulating
HTML documents. The DOM represents an HTML document as a tree of nodes. The DOM Provides
functions that allow to add, remove, modify of the document effectively.
In this DOM tree, the document is the root node. The root node has one child node which is the
<html> element. The <html> element is called the document element.
Each document can have only one document element. In an HTML document, the document
element is the <html> element. Each markup can be represented by a node in the tree.
Each node in the DOM tree is identified by a node type. JavaScript uses integer numbers to
determine the node types. The following table illustrates the node type constants:
39
Node and Element
Sometimes it’s easy to confuse between the Node and the Element.A node is a generic name of any
object in the DOM tree. It can be any built-in DOM element such as the document. Or it can be any
HTML tag specified in the HTML document like <div> or <p>.
In other words, the node is the generic type of element. The element is a specific type of the node
with the node type Node.ELEMENT_NODE.
The following picture illustrates the relationship between the Node and Element types:
40
Node Relationships
Any node has relationships to other nodes in the DOM tree. The relationships are the same as the
ones described in a traditional family tree.
For example, <body> is a child node of the <html> node, and <html> is the parent of the <body>
node.
The <body> node is the sibling of the <head> node because they share the same immediate parent,
which is the <html> element.
document.getElementsByTagName
with the matching tag name in the order which they appear in the document.
document.getElementsByClassName
classname.
document.getElementsByName
method accepts a name which is the value of the name attribute of the
41
getting the Element
document.getElementById
that matches a specific string.if the document has no element with the specific id,
document.querySelector
is a method of the Element interface. this method allows to select the first element that matches one
or more CSS selectors.
document.querySelector('#demo') - Id selectors
document.querySelectorAll
method returns a static NodeList of elements that match the CSS Selectors. if no element matches, it
returns an empty NodeList.
Example :
document.querySelector('demo1')
null
42
document.querySelector('.demo1')
<div class="demo1">…</div>
document.querySelectorAll('p')
NodeList(4) [p, p, p, p]
document.querySelectorAll('div')
document.querySelectorAll('#demo')
NodeList [div#demo]
document.querySelectorAll('.demo1')
NodeList [div.demo1]
document.querySelectorAll('*')
To get the parent node of a specified node in the DOM tree, you use the parentNode property:
The Document and DocumentFragment nodes do not have a parent. Therefore, the parentNode will
always be null. If you create a new node but haven’t attached it to the DOM tree, the parentNode of
that node will also be null.
43
Get the next siblings
To get the next sibling of an element, you use the nextElementSibling attribute:
The nextElementSibling returns null if the specified element is the last one in the list.
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li>About Us</li>
</ul>
The following example uses the nextElementSibling property to get the next sibling of the list item
that has the current class:
console.log(nextSibling);
Output:
<li>Careers</li>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Child Elements</title>
</head>
<body>
<ul id="menu">
<li class="first">Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li class="last">About Us</li>
</ul>
</body>
</html>
To get the first child element of a specified element, you use the firstChild property of the element:
44
let firstChild = parentElement.firstChild;
If the parentElement does not have any child element, the firstChild returns null. The firstChild
property returns a child node which can be any node type such as an element node, a text node, or a
comment node. The following script shows the first child of the #menu element:
console.log(firstChild);
Output:
#text
The Console window shows #text because a text node is inserted to maintain the whitespace
between the opening <ul> and <li> tags. This whitespace creates a #text node.
Note that any whitespace such as a single space, multiple spaces, returns, and tabs will create a #text
node. To remove the #text node, you can remove the whitespaces as follows:
Or to get the first child with the Element node only, you can use the firstElementChild property:
The following code returns the first list item which is the first child element of the menu
console.log(content.firstElementChild);
Output:
<li class="first">Home</li>
In this example:
Second, get the first child element by using the firstElementChild property.
To get the last child element of a node, you use the lastChild property:
In case the parentElement does not have any child element, the lastChild returns null.
The lastChild property returns the last element node, text node, or comment node. If you want to
select only the last child element with the element node type, you use the lastElementChild
property:
45
The following code returns the list item which is the last child element of the menu:
console.log(main.lastElementChild);
To get a live NodeList of child elements of a specified element, you use the childNodes property:
The childNodes property returns all child elements with any node type. To get the child element with
only the element node type, you use the children property:
The following example selects all child elements of the element with the Id main:
console.log(children);
Output:
Create Elements
document.createElement is used to create new HTML elements. it accepts an HTML tag name and
returns a new Node with the Element type. To Attach the created Element to the Document Body, we
use appendChild() method
div.id = 'content';
var p = document.createElement('p');
div.appendChild(p);
document.body.appendChild(div);
46
47
createElement()
appendChild()
insertBefore()
insertAfter()
replaceChild()
removeChild()
cloneNode()
append()
prepend()
48
49
removeChild() example
50
Working with attributes:
setAttribute()
To set a value of an attribute on a specified element, you use the setAttribute() method:
element.setAttribute(name, value);
Parameters
The name specifies the attribute name whose value is set. It’s automatically converted to lowercase
if you call the setAttribute() on an HTML element.
The value specifies the value to assign to the attribute. It’s automatically converted to a string if you
pass a non-string value to the method.
Return value
Note that if the attribute already exists on the element, the setAttribute() method updates the value;
otherwise, it adds a new attribute with the specified name and value.
Typically, you use the querySelector() or getElementById() to select an element before calling the
setAttribute() on the selected element.
To get the current value of an attribute, you use the getAttribute() method. To remove an attribute,
you call the removeAttribute() method.
51
Working with Styles
The getComputedStyle() is a method of the window object, which returns an object that contains the
computed style an element:
Parameters
element is the element that you want to return the computed styles. If you pass another node type
e.g., Text node, the method will throw an error.
For example, if you want to get the computed value of all the CSS properties of a link with the hover
state, you pass the following arguments to the getComputedStyle() method:
console.log(style);
52
Note that window is the global object, therefore, you can omit it when calling get the
getComputedStyle() method.
Return value
The getComputedStyle() method returns a live style object which is an instance of the
CSSStyleDeclaration object. The style is automatically updated when the styles of the element are
changed.
53
JavaScript Events
An event is an action that occurs in the web browser, which the web browser feedbacks to you so that
you can respond to it. For example, when users click a button on a webpage, you may want to respond
to this click event by displaying a dialog box. Each event may have an event handler which is a block
of code that will execute when the event occurs. An event handler is also known as an event listener.
It listens to the event and executes when the event occurs.
To define the code that will be executed when the button is clicked, you need to register an event
handler using the addEventListener() method:
function display() {
alert('It was clicked!');
}
btn.addEventListener('click',display);
How it works.
• First, select the button with the id btn by using the querySelector() method.
• Then, define a function called display() as an event handler.
• Finally, register an event handler using the addEventListener() so that when users click the
button, the display() function will be executed.
A shorter way to register an event handler is to place all code in an anonymous function, like this:
btn.addEventListener('click',function() {
alert('It was clicked!');
});
Event flow
<html>
<head>
<title>JS Event Demo</title>
</head>
<body>
<div id="container">
<button id='btn'>Click Me!</button>
</div>
</body>
54
When you click the button, you’re clicking not only the button but also the button’s container, the div,
and the whole webpage.
Event flow explains the order in which events are received on the page from the element where the
event occurs and propagated through the DOM tree.
There are two main event models: event bubbling and event capturing.
Event bubbling
In the event bubbling model, an event starts at the most specific element and then flows upward
toward the least specific element (the document or even window).
When you click the button, the click event occurs in the following order:
1. button
2. div with the id container
3. body
4. html
5. document
The click event first occurs on the button which is the element that was clicked. Then the click event
goes up the DOM tree, firing on each node along its way until it reaches the document object.
The following picture illustrates the event bubbling effect when users click the button:
Note that modern web browsers bubble the event up to the window object.
Event capturing
In the event capturing model, an event starts at the least specific element and flows downward toward
the most specific element.
When you click the button, the click event occurs in the following order:
1. document
55
2. html
3. body
4. div with the id container
5. button
DOM level 2 events specify that event flow has three phases:
• First, event capturing occurs, which provides the opportunity to intercept the event.
• Then, the actual target receives the event.
• Finally, event bubbling occurs, which allows a final response to the event.
The following picture illustrates the DOM Level 2 event model when users click the button:
56
Event object
When the event occurs, the web browser passed an Event object to the event handler:
btn.addEventListener('click', function(event) {
console.log(event.type);
});
Output:
The following table shows the most commonly used properties and methods of the event object:
preventDefault() cancel the default behaviour for the event. This method is only
effective if the cancelable property is true
Note that the event object is only accessible inside the event handler. Once all the event handlers
have been executed, the event object is automatically destroyed.
preventDefault()
To prevent the default behavior of an event, you use the preventDefault() method.
For example, when you click a link, the browser navigates you to the URL specified in
the href attribute:
<a href="https://www.google.com/">Link</a>
However, you can prevent this behavior by using the preventDefault() method of the event object:
57
let link = document.querySelector('a');
link.addEventListener('click',function(event) {
console.log('clicked');
event.preventDefault();
});
Note that the preventDefault() method does not stop the event from bubbling up the DOM. And an
event can be cancelled when its cancelable property is true.
stopPropagation()
The stopPropagation() method immediately stops the flow of an event through the DOM tree.
However, it does not stop the browsers default behaviour.
btn.addEventListener('click', function(event) {
console.log('The button was clicked!');
event.stopPropagation();
});
document.body.addEventListener('click',function(event) {
console.log('The body was clicked!');
});
Without the stopPropagation() method, you would see two messages on the Console window.
However, the click event never reaches the body because the stopPropagation() was called on
the click event handler of the button.
Handling Events :
When an event occurs, we can create an event handler which is a piece of code that will execute to
respond to that event. An event handler is also known as an event listener. it listens to the event and
responds accordingly. An event listener is a function with an explicit name if it is reusable or an
Anonymous function in case it is used one time. An event can be handled at one or multiple event
handlers. if an event has multiple event handlers, all the event handlers will be executed when the
event is fired.
58
1. HTML Event Handler Attributes
Event handlers typically have names that begin with 'on' for example : onclick
To Assign an event handler to an event associated with an HTML element, we can use an HTML
attribute with the name of the event handler.
function dosomething() {
console.log('Hello I am clicked');
Disadvantages :
1. event handlers code is mixed with the html code, which will make the code more difficult to
maintain and extend.
2. Timing Issue.if the element is loaded fully before the JavaScript code, users can start interacting
with the element on the webpage which will cause an error.
console.log('Do Something');
The DOM Level assigns an event handler to the element event handler properties in the script.
DOM Level 2 event handlers provides 2 main methods for dealing with the registering / deregistering
event listeners.
59
addEventListener() method accepts 3 arguments :
event name
Example :
<button id="btn">click</button>
console.log('clicked me ');
btn.removeEventListener('click',show);
btn.addEventListener('click',show);
60
Mouse Events :
click
dblclick
mousedown
mouseup
mouseover
mouseout
mouseenter
mouseleave
Keyboard events
keyup
keydown
keypress
scroll onscroll
61
JavaScript Form
Form basics
The <form> element has two important attributes: action and method.
• The action attribute specifies a URL that will process the form submission. In this
example, the action is the /signup URL.
• The method attribute specifies the HTTP method to submit the form with.
Usually, the method is either post or get.
Generally, you use the get method when you want to retrieve data from the server
and the post method when you want to change data on the server.
Referencing forms
To reference the <form> element, you can use DOM selecting methods such
as getElementById():
An HTML document can have multiple forms. The document.forms property returns a
collection of forms (HTMLFormControlsCollection) on the document:
document.forms
To reference a form, you use an index. For example, the following statement returns
the first form of the HTML document:
document.forms[0]
Submitting a form
62
Typically, a form has a submit button. When you click it, the browser sends the form
data to the server. To create a submit button, you use <input> or <button> element
with the type submit:
Or
<button type="submit">Subscribe</button>
If the submit button has focus and you press the Enter key, the browser also submits
the form data.
When you submit the form, the submit event is fired before the request is sent to the
server. This gives you a chance to validate the form data. If the form data is invalid,
you can stop submitting the form.
To stop the form from being submitted, you call the preventDefault() method of
the event object inside the submit event handler like this:
Typically, you call the event.preventDefault() method if the form data is invalid. To
submit the form in JavaScript, you call the submit() method of the form object:
form.submit();
To access form fields, you can use DOM methods. Also, you can use
the elements property of the form object. The form. Elements property stores a
collection of the form elements. JavaScript allows you to access an element by index,
id, or name. Suppose that you have the following signup form with
two <input> elements:
63
<label for="name">Name:</label>
<input type="text" id="name" name="name"
placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="text" id="email" name="email"
placeholder="Enter your email address" />
<small></small>
</div>
<button type="submit">Subscribe</button>
</form>
To access the elements of the form, you get the form element first:
And use index, id, or name to access the element. The following accesses the first form
element:
form.elements[0]; // by index
form.elements['name']; // by name
form.elements['name']; // by id (name & id are the same in this case)
form.elements[1]; // by index
form.elements['email']; // by name
form.elements['email']; // by id
After accessing a form field, you can use the value property to access its value, for
example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Form Demo</title>
<meta name="viewport" content="width=device-width,
initial-scale=1.0" />
64
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<form action="signup.html" method="post"
id="signup">
<h1>Sign Up</h1>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name"
placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="text" id="email"
name="email" placeholder="Enter your
email address" />
<small></small>
</div>
<div class="field">
<button
type="submit"
class="full">Subscribe</button>
</div>
</form>
</div>
<script src="js/app.js"></script>
</body>
</html>
The HTML document references the style.css and app.js files. It uses
the <small> element to display an error message in case the <input> element has
invalid data.
Submitting the form without providing any information will result in the following error:
65
Submitting the form with the name but invalid email address format will result in the
following error:
function showSuccess(input) {
return showMessage(input, "", true);
}
66
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+")
)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-
0-9]+\.)+[a-zA-Z]{2,}))$/;
67
Browser Object Model is the core of the JavaScript on the web.The BOM provides us with objects that
expose the web browser's Functionality. JavaScript window object which is the global object of
JavaScript in the browser.
Window properties
The window object has 4 properties related to the size of the window :
innerHeight
innerWidth
outerHeight
outerWidth
console.log(innerHeight,innerWidth,outerHeight,outerWidth);
window.open(url,windowName,[windowFeatures]);
window.resizeTo(width,height);
window.moveTo(x,y)
pop-up / dialog
alert()
confirm()
to invoke a dialog with a question with 2 buttons ok & cancel, we use confirm() method
function simple(){
68
var message = result ? 'Clicked on OK' : 'Clicked on CANCEL';
alert(message);
The Confirm() returns true if the OK button was clicked or false if the CANCEL button was clicked.
prompt()
function simple(){
alert(feeback);
sets a timer and executes a callback function after the timer expires.
setTimeout(cb,[,delay],arg1,arg2,arg3.....);
delay - is the time in milliseconds that the timer should wait before executing the callback function.if
we omit it, the delay defaults to 0.
setTimeout(function(){
console.log("Hello");
}, 5000);
function something(a){
console.log("Hello",a);
69
var timeoutID;
function simple(a){
function clearAlert(){
clearTimeout(timeoutID);
setInterval()
is the method of the window and it repeatedly calls a function with a fixed delay between each call.
setInterval(callback,delay,[arg1,arg2,...]);
var IntervalID;
function simple(a){
function clearAlert(){
clearInterval(IntervalID);
href
protocol
host
port
hostname
70
origin
pathname
search
hash
username
password
methods :
assign()
reload()
replace()
Navigator Object provides information about the web browser and its capabilities.
Screen object provides the attributes of the screen on which the current window is being rendered.
History is an object of window - stack stores the current page and previous page that we visited.
71
ES6
72
New ES6 Syntax:
let const vs var
let
In ES5, when we declare a Variable using var keyword, the scope of the Variable.
is either global or local. if we declare a Variable outside of a function, the scope of
the Variable is global. when we declare a Variable inside a function, the scope of the
Variable is local.
ES6 provides a new way of declaring a Variable by using let keyword. The let keyword
is similar to the var keyword, except that these Variables are blocked scope.
const
ES6 provides a new way of declaring a constant by using const keyword. The const
Spread Operator
ES6 provides a new operator called spread operator that consists of three dots (...).
The Spread operator allows us to spread out elements of an iterable object such as
an Array. Map or set.
Spread Operator
73
Rest Parameter (...)
ES6 provides a new kind of parameter called Rest-parameter that has a prefix of
of arguments as an array.
function sum(...args){
let total = 0;
console.log(args);
for(let a = 0; a < args.length; a ++){
total += args[a];
}
return total;
}
console.log(sum(1,2,3,5,6,7,7,8));
for loops
ES6 Introduced a new statement for...of that iterates over an iterable object such
as Array,String,Map,Set.
for..of
for..in
The for...in loop iterates over all enumerable properties of an object. it doesn't
74
Template Literals
in ES6, we can create template literal by wrapping up the text or expressions in
backticks (``);
let a = 10;
let msg = 'The value of a :' + a;
let msg1 = `The Value of a : ${a}`;
console.log(msg,msg1);
let machine = {
console.log(machine);
75
Destructuring
is a new feature introduced in ES6, Destructuring assignment allows to Destructure
properties of an object or elements of an array into individual variables.
Array Destructuting
let arr = [2,3,4];
//let a = arr[0], b = arr[1];
let [a,b,c] = arr;
console.log(a + b + c);
Object Destructuting
let obj = { a : 1, b : 2, c : 3};
//let a = obj.a, b = obj.b;
let {a,b,c} = obj;
console.log(a,b,c);
-------------------------
let obj = { a : 1, b : 2, c : 3};
let {a : x, b : y, c : z} = obj;
console.log(x,y,z);
Arrow functions
ES6 arrow functions provide with an alternative way to write a shorter syntax
compared to the function expression.
let add = (x,y) => x + y;
console.log(add(5,2)); // 7
--------------------------------------------------------------
let greet = msg => console.log(msg);
greet("Hello"); // Hello
--------------------------------------------------------------
let simple = () => {
let a = 10;
console.log("The Value of a: " + a);
}
simple(); // The Value of a : 10
76
let val = () => 20;
console.log(val()); //20
--------------------------------------------------------------
let something = () => {
let b = 30, c = 40;
return b + c;
}
console.log(something()); // 70
--------------------------------------------------------------
// let setColor = function(color){
// return {value : color};
// }
let setColor = color => ({value : color});
// Object literal should be returned by wrapping up inside parenthesis
let backgroundColor = setColor('red');
console.log(backgroundColor);
--------------------------------------------------------------
77
ES6 Classes***:
Class is a Blueprint for creating Objects.
constructor() method is default method of class, where we can initialise the properties
of an instance. JavaScript automatically calls the constructor() method when we
instantiate an object of the class.
ES6 provides specific syntax for defining the getter and setter using the get and set
keywords.
Example :
class Person{
constructor(name){
this.name = name;
}
getName(){
return this.name;
}
78
setName(newName){
newName = newName.trim();
if(newName === ''){
console.error("Should not be blank")
}
this.name = newName;
}
}
let person = new Person("Krishna");
console.log(person);
person.setName("Abhinav");
console.log(person);
Example :
class Person{
constructor(name){
this.name = name;
}
get name(){ return this._name; }
set name(newName){
newName = newName.trim();
if(newName === ''){
console.error("Should not be blank")
}
this._name = newName;
}
}
let person = new Person("Krishna");
console.log(person);
person.name = "Akhil";
console.log(person.name);
79
class expressions :
Singleton Design pattern that limits the instantiation of a class to a single instance.
let app = new class{
constructor(name){
this.name = name;
}
start(){
console.log(`Starting the ${this.name}`);
}
}('Dosomething Application');
app.start();
it ensures that only one instance of a class can be created throughout the system.
Class expressions can be used to create a Singleton by calling the class constructor
Immediately. To do that, we use new operator with a class expression and include the
parenthesis at the end of class declaration.
Computed Property :
let name1 = 'fullName';
class Person{
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
80
get [name1](){
return `${this.firstName} . ${this.lastName}`;
}
}
let person = new Person('Krishna','Rama');
console.log(person.fullName);
ES6 allows to use an expression in brackets [ ]. Like an Object literal, we can use
computed properties for getters and setters of a class.
Static Methods :
By Definition, static methods are bound to a class, not the instances of that class.
Therefore, static methods are useful for defining helper or utility methods.
Like a static method, a static property is not shared by all instances of a class.
81
Inheritance :
In ES6, we use extends keyword to implement the Inheritance. The Class to be
extended is called a base class or parent class. The class that extends the base class
or parent class is called the derived class or child class. Call the super(arguments) in
the child class's constructor to invoke the parent class's constructor. we use super
keyword to call methods of the parent class in the methods of the child class.
class Animal {
constructor(legs){
this.legs = legs;
}
walk(){
console.log(`Walking on ${this.legs} legs`);
}
}
class Bird extends Animal{
constructor(legs,color){
super(legs);
this.color = color;
}
fly(){
console.log(`flying`);
}
getColor(){
return this.color;
}
}
let bird = new Bird(2, "white");
bird.walk();
bird.fly();
console.log(bird.getColor());
82
Promises***
A Promise is an object that encapsulates the result of an asynchronous operation. A
Promise object has a state that can be one of the 3 states:
Pending
in the beginning, the state of the promise is pending, indicating that the asynchronous
operation is in progress. Depending on the result of the asynchronous operation, the
state changes to either Fulfilled or rejected.
creating a promise :
The executor accepts 2 callback functions with the name resolve and reject.
if the asynchronous operation completes successfully, the executor will call the
resolve() function to change the state of the promise from pending to fulfilled with a
value. in case of an error, the executor will call the reject() function to change the
state of the promise from pending to rejected with a reason.
Once a promise reaches either fulfilled or rejected state, it stays in that state and can't
go to another state.
Consuming a Promise :
then
catch
finally
83
The then() method :
To get the value of Promise when it's fulfilled, we call then() method of the promise
object.
promise.then(onFullfilled,onRejected)
The then() method accepts 2 callback functions :
onFullfilled
onRejected
if we want to get the error only when the state of the promise is rejected, we can use
the catch() method of the Promise Object.
if we want to execute the some piece of code whether the promise is fulfilled or
rejected, we use finally() method.
Example:
let success = true;
function getUsers(){
return new Promise((resolve,reject) => {
setTimeout(() => {
if(success){
resolve([
{
userName : 'Krishna', email :
'[email protected]'
}
]);
}else{
reject('Failed to get the User List');
}
}, 1000);
});
}
const promise = getUsers();
84
console.log(promise);
promise
.then((users) => {console.log(users)})
.catch((error) => console.log(error))
.finally(() => console.log("Finally"));
Promise Chaining:
Examples:
let p = new Promise((resolve,reject) => {
setTimeout(() => {
resolve(10);
}, 2000);
});
p.then(result => {
console.log(result);
return result * 2;
}).then(result => {
console.log(result);
return result * 3;
}).then(result => {
console.log(result);
return result * 4;
}).then(result => {
console.log(result);
})
85
Example:
function getUser(userId){
return new Promise((resolve,reject) => {
console.log('Getting Users');
setTimeout(() => {
resolve({
userId : userId,
userName : 'Admin'
})
},2000);
})
}
function getServices(user){
return new Promise((resolve,reject) => {
console.log(`Getting Services of ${user.userName}`);
setTimeout(() => {
resolve(['Email','Print','Fax']);
},2000);
})
}
function getServiceCost(services){
return new Promise((resolve,reject) => {
console.log(`Calculating the services cost of
${services}`);
setTimeout(() => {
resolve(services.length * 200)
},2000);
})
}
getUser(100).then(getServices).then(getServiceCost)
.then(console.log);
86
Promise.all()
The Promise.all() method accepts a list of promises and returns a new Promise that
resolve to an array of results of the input promises if all the input promises resolved. else
reject with an error of the first promise rejected.
Promise.race()
Promise.any()
Promise.any() method takes the list of the promises and return a promise that fulfils first.
Promise.allSettled() ES2020
when we raise an exception outside the promise, we must catch it with try/catch
function getUser(userId){
return new Promise((resolve,reject) => {
console.log('Getting Users');
setTimeout(() => {
resolve({
userId : userId,
userName : 'Admin'
})
},2000);
})
}
function getServices(user){
return new Promise((resolve,reject) => {
console.log(`Getting Services of ${user.userName}`);
setTimeout(() => {
resolve(['Email','Print','Fax']);
},2000);
})
}
87
function getServiceCost(services){
return new Promise((resolve,reject) => {
console.log(`Calculating the services cost of
${services}`);
setTimeout(() => {
resolve(services.length * 200)
},2000);
})
}
try{
getUser(100).then(getServices).then(getServiceCost).then(conso
le.log);
}
catch (error){
console.log(`Caught by try/catch ${error}`);
}
Async/Await :
88
function getServices(user){
return new Promise((resolve,reject) => {
console.log(`Getting Services of ${user.userName}`);
setTimeout(() => {
resolve(['Email','Print','Fax']);
},2000);
})
}
function getServiceCost(services){
return new Promise((resolve,reject) => {
console.log(`Calculating the services cost of
${services}`);
setTimeout(() => {
resolve(services.length * 200)
},2000);
})
}
async function showServiceCost(){
try
{
let user = await getUser(100);
let services = await getServices(user);
let cost = await getServiceCost(services);
console.log(`The Services Cost : ${cost}`);
}
catch(error){
console.log(error);
}
}
showServiceCost();
89
WEB API***
Fetch API
The Fetch API is a modern interface that allows to make HTTP requests to servers from
web Browsers.
XMLHttpRequest(XHR)
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data));
---------------------------------------------------------------------------------------------------------------------------
async function fetchData(){
let url = 'https://jsonplaceholder.typicode.com/users';
let reponse = await fetch(url);
let data = await reponse.json();
console.log("data",data);
}
fetchData();
Modules***
An ES6 module is a JavaScript file that executes in strict mode only.it means that any
Variables or functions declared in the module won't be added automatically to the
global scope.
90
app.js
export let message = "I am from APP";
export function getMessage(){
return message;
}
export function setMessage(msg){
message = msg;
}
sort.js
export default function(arr){
arr.sort();
return arr;
}
Index.html
<script type="module" src="script.js" defer></script>
Collections:
A Map object holds key-value pairs. keys are unique in a Map's collection.
Map()
let map = new Map([iterable])
Methods and properties :
set(key,value)
get(key)
has(key)
clear()
delete(key)
entries()
keys()
values()
size
91
WeakMap is similar to a Map except the keys of WeakMap must be objects.
get(key)
set(key,value)
has(key)
delete(key)
Set
stores a collection of unique values of any type.
add(value)
clear()
delete(value)
entries()
has(value)
keys()
let chars = new Set(['a','b','a','c','b','a']);
console.log(chars);
92
symbol
is a new primitive type.
93
result = this.amount + this.currency;
break;
}
return result;
}
var price = new Money(799, 'USD');
console.log('Price is ' + price); // Price is 799USD
console.log(+price + 1); // 800
console.log(String(price)); // 799USD
-----------------------------------------------------------------------------------------------------------------------
Example :
class Sequence {
constructor(start = 0, end = Infinity, interval = 1){
this.start = start;
this.end = end;
this.interval = interval;
}
[Symbol.iterator](){
let counter = 0;
let nextIndex = this.start;
return{
next : () => {
if(nextIndex <= this.end){
let result = { value : nextIndex, done :
false}
nextIndex += this.interval;
counter ++;
return result
}
return {value : counter, done : true}
94
},
return : () =>{
console.log('cleaning up...')
}
}
}
};
Generator
ES6 introduces a new kind of function that is differnent from a regular function.
A generator can pause midway and then continues from where it paused yield
statement returns a value and pauses the execution of the function.
function* generate(){
console.log('First Time');
yield 1;
console.log('Second Time');
yield 2;
}
let gen = generate();
gen.next();
gen.next();
gen.next();
95
function* loop(){
let index = 0;
while(true){
yield index++;
}
}
let a = loop();
console.log(a.next());
console.log(a.next());
console.log(a.next());
console.log(a.next());
console.log(a.next());
96
Web Storage:
Client Storage
Cookies
A HTTP Cookie is a piece of data that server sends to a web Browser. Then, the
web browser stores the HTTP Cookie on the user's computer and sends it back
to the same server in the later requests. An HTTP Cookie is also known as a web
Cookie or browser cookie. and it is commonly called a cookie.
HTTP is stateless.
cookies serve the following :
- Session Management
- Personalization - user settings, themes etc .,
- Tracking - record and analyse user behaviors (advertising)
Cookie Details :
Name
Value
Domain
Path
Expiration
Secure flag
Manage Cookies :
Get a cookie
document.cookie
Set a cookie
document.cookie = "userName = admin"
Remove a cookie
97
localStorage:
localStorage is used to store persistant data. The Storage type is designed to
store name -value pairs.
Methods :
setItem(name,value)
getItem(name)
removeItem(name)
key(index)
clear()
Storage Properties :
domain
key
newValue
oldValue
localStorage is an instance of the Storage type that allows to store persistant
data in the web Browsers. localStorage can store only strings. To Store objects,
we convert them to strings using JSON.stringify() method. We convert the
strings into objects when we retrieve them from the localStorage using the
JSON.parse() method.
SessionStorage
The SessionStorage object stores data only for a session. it means that the data
stored in the sessionStorage will be deleted when the browser is closed. The
Storage type is designed to store name -value pairs.
Methods :
setItem(name,value)
getItem(name)
removeItem(name)
key(index)
clear()
98
IndexedDB :
IndexedDB is a large-scale object store built into the browser. The IndexedDB
allows to persistently store the data using key-value pairs. The values can be
any JavaScript type including Boolean, number, string, undefined, null, date,
object, array, regex, blob, and files. IndexedDB allows to create web
applications that can work online and offline.
Databases
Object stores
Indexes
features have to try :
Drag and Drop API
FileReader API
Notification API
Geolocation API
99