0% found this document useful (0 votes)
7K views99 pages

Javascript Course Material

JavaScript is a programming language initially designed to interact with elements of web pages. It allows adding interactivity to web pages by modifying HTML and CSS dynamically with JavaScript code. JavaScript code is executed by the JavaScript engine in web browsers after HTML and CSS have been downloaded. JavaScript has evolved over time with standards like ECMAScript and now supports features like classes, modules, and async/await.

Uploaded by

babujaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views99 pages

Javascript Course Material

JavaScript is a programming language initially designed to interact with elements of web pages. It allows adding interactivity to web pages by modifying HTML and CSS dynamically with JavaScript code. JavaScript code is executed by the JavaScript engine in web browsers after HTML and CSS have been downloaded. JavaScript has evolved over time with standards like ECMAScript and now supports features like classes, modules, and async/await.

Uploaded by

babujaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

JAVA SCRIPT

Introduction to JavaScript:

JavaScript is a programming language initially designed to interact with elements of web pages.

Within web browsers, JavaScript consists of three main parts:

• ECMAScript provides the core functionality. (ES5, ES6)


• The Document Object Model (DOM) provides interfaces for interacting with elements on
web pages
• The Browser Object Model (BOM) provides the browser API for interacting with the web
browser.

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.

Hence, two distinct versions of JavaScript were in the market:

JavaScript in Netscape Navigator

JScript in Internet Explorer.

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

How to Work with JavaScript?

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:

• Embed JavaScript code directly into the HTML page.


• Reference an external JavaScript code file.

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

To include a JavaScript from an external file:

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.

The following shows the contents of the app.js file:

console.log('Hello, Krishna!');

The following displays the contents of the index.html file:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Example</title>

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

The async and defer attributes

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:

<script async src="service.js"></script>

<script async src="app.js"></script>

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.

<script defer src="defer-script.js"></script>

JavaScript Syntax

JavaScript syntax includes

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

The following JavaScript code doesn’t use whitespace:

let formatted = true; if (formatted) {console.log('The code is easy to read');}

It is equivalent to the following code that uses whitespace. Hence, this code is much easier to read:

let formatted = true;

if (formatted) {

console.log('The code is easy to read');

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:

let message = "Welcome to JavaScript";

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

console.log('The local storage is supported');

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.

JavaScript supports both single-line and block 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:

// this is a single-line comment

Code language: JSON / JSON with Comments (json)

Block comments

A delimited comment begins with a forward slash and asterisk /* and ends with the opposite */ as in
the following example:

/* This is a block comment

that can span multiple lines */

Expressions

An expression is a piece of code that evaluates to a value. For example:

2+1

The above expression returns three.

Keywords & Reserved words

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:

break case catch

continue debugger default

else export extends

function if import

new return super

throw try null

void while with

class delete finally

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:

enum implements let

protected private public

await interface package

implements public

Java script Variables:

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.

Variable names are case-sensitive.

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)

and Complex data type: object

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:

var counter = 120; // counter is a number

counter = false; // counter is now a boolean

counter = "foo"; // counter is now a string

To determine the current type of the value stored in a variable, you use the typeof operator:

var counter = 120;

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

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.

Consider the following example:

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:

console.log(typeof undeclaredVar); // undefined

The null type

The null type is the second primitive data type that also has only one value null. For example:

var obj = null;

console.log(typeof obj); // object

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 defines that null is equal to undefined as follows:

console.log(null == undefined); // true

The number type

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:

var num = 100;

To represent a floating-point number, you include a decimal point followed by at least one number.
For example:

var price = 12.5;

var discount = 0.05;

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:

var price = 200.00; // interpreted as an integer 200

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:

console.log(Number.MAX_VALUE + Number.MAX_VALUE); // Infinity

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;

The NaN has two special characteristics:

Any operation with NaN returns NaN.

The NaN does not equal any value, including itself.

Here are some examples:

console.log(NaN/2); // NaN

console.log(NaN == NaN); // false

The string type

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:

var greeting = 'Hi';

var message = "Bye";

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:

var str = 'JavaScript';

str = str + ' String';

In this example:

First, declare the str variable and initialize it to a string of 'JavaScript'.

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)

The output is:

'JavaScript'

But not:

'javaScript'

The boolean type

The boolean type has two literal values: true and false in lowercase. The following example declares
two variables that hold the boolean values.

var inProgress = true;

var completed = false;

console.log(typeof completed); // boolean

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.

The following table displays the conversion rules:

Type true false

string non-empty string empty string

number non-zero number and Infinity 0, NaN

object non-null object null

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({foo: 100})); // true on non-empty object

console.log(Boolean(null));// false

The symbol type

JavaScript introduced a new primitive type in ES6: the symbol. Unlike other primitive types, the
symbol type does not have a literal form.

To create a symbol, you call the Symbol function as follows:

10
var s1 = Symbol();

The Symbol function creates a new unique value every time you call it.

console.log(Symbol() == Symbol()); // false

Note that you’ll learn more about symbols in the symbol tutorial.

The bigint type

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:

var pageView = 9007199254740991n;

console.log(typeof(pageView)); // 'bigint'

JavaScript Numeric Separator

Introduction to the JavaScript numeric separator

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:

const budget = 1000000000;

Is this a billion or a hundred million?

The numeric separator fixes this readability issue as follows:

const budget = 1_000_000_000;

As you can see, the number is now very easy to interpret.

JavaScript allows you to use numeric separators for both integer and floating-point numbers. For
example:

let amount = 120_201_123.05; // 120201123.05

let expense = 123_450; // 123450

let fee = 12345_00; // 1234500

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:

let amount = 0.000_001; // 1 millionth

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

const max = 9_223_372_036_854_775_807n;

// binary

11
let nibbles = 0b1011_0101_0101;

// octal

let val = 0o1234_5670;

// hex

let message = 0xD0_E0_F0;

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:

let empty = {};

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.

1) The dot 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);

2) Array-like notation ( [])

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

'building no': 3960,

street: 'North 1st street',

state: 'CA',

country: 'USA'

};

To access the 'building no' property, you need to use the array-like notation:

address['building no'];

If you use the dot notation, you’ll get an error:

address.'building no';

Error:

SyntaxError: Unexpected string

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

Modifying the value of a property

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:

{ firstName: 'Jaanu', lastName: ‘Mohan’ }

In this example, we changed the value of the firstName property of the person object from 'Krishna'
to 'Jaanu'.

Adding a new property to an object

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;

Deleting a property of an object

To delete a property of an object, you use the delete operator:

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.

Checking if a property exists

To check if a property exists in an object, you use the in operator:

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

A JavaScript array has the following characteristics:

Creating JavaScript arrays

JavaScript provides you with two ways to create an array. The first one is to use the Array constructor
as follows:

let scores = new Array();

The scores array is empty, which does hold any elements.

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:

let scores = Array(10);

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

let scores = new Array(9,10,8,7,6);

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 athletes = new Array(3); // creates an array with initial size 3

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.

let artists = Array();

In practice, you’ll rarely use the Array() constructor to create an array.

The more preferred way to create an array is to use the array literal notation:

let arrayName = [element1, element2, element3, ...];

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:

let colors = ['red', 'green', 'blue'];

To create an empty array, you use square brackets without specifying any element like this:

let emptyArray = [];

Accessing JavaScript array elements

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:

let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];

console.log(mountains[0]); // 'Everest'

console.log(mountains[1]); // 'Fuji'

console.log(mountains[2]); // 'Nanga Parbat'

To change the value of an element, you assign that value to the element like this:

let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];

mountains[2] = 'K2';

console.log(mountains);

16
Output:

[ 'Everest', 'Fuji', 'K2' ]

Getting the array size

Typically, the length property of an array returns the number of elements. The following example
shows how to use the length property:

let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];

console.log(mountains.length); // 3

Basic operations on arrays

The following explains some basic operations on arrays. You’ll learn advanced operations such as
map(), filter(), and reduce() in the next tutorials.

1) Adding an element to the end of an array

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

2) Adding an element to the beginning of an array

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

3) Removing an element from the end of an array

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'];

const lastElement = seas.pop();

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'];

const firstElement = seas.shift();

console.log(firstElement);

Output:

Black Sea

5) Finding an index of an element in the array

To find the index of an element, you use the indexOf() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];

let index = seas.indexOf('North Sea');

console.log(index); // 2

6) Check if a value is an array

To check if a value is an array, you use Array.isArray() method:

console.log(Array.isArray(seas)); // true

JavaScript Operators :

Arithmetic Operators

* (Asterik )

Remainder Operator (modulas)

var a = 20;

var b = 6;

console.log(a % b);// 2

Assignment Operators :

= a=b

+= a += b which means a=a+b

-= a -= b a=a-b

18
*=

/=

%=

&= AND

|= OR

^= XOR

<<= shifting left

>>= shifting right

>>>=

Unary Operators : works on a value

+x - convert a value into a number

-x - covert a value and negate it

++x Pre increment

--x Pre Decrement

x++ Post increment

x-- Post Decrement

Comparision Operators : result will be a boolean value

>

<

<=

>=

== equal

!= not equal

=== strictly equal

!== strictly not equal

var a = '20';

var b = 20;

console.log(a === b);// false

console.log(a == b); // true

19
Logical Operators

! (Logical NOT ) (!!) Double Negation

|| (Logical OR)

&& (Logical AND)

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

true true true

true false true

false true true

false false false

Logical AND &&

a b a && b

true true true

true false false

false true false

false false false

var a = true;

var b = false;

console.log(a || b);

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

Logical Assignment Operators

||=

&&=

??= nullish coalescing assignment (ES Next)

x ??= y

x ?? (x = y)

** Objects

var title = "Somethimg";

title ||= 'untitled';

console.log(title);

Exponentiation Operators

**

**= -> x **= y ---> x = x ** y;

var result = 2 ** 2;
console.log(result); // 4

result = 2 ** 3;
console.log(result); // 8

21
Conditional Statements :

if

if..else

if.. elseif.. else

Syntax : if(condition)

statement;

if(condition){

// statements

Example : var a = 30;

if(a == 20){

console.log('Equal to 20');

}else{

console.log("Not Equals to 20");

Example :

var a = 60;

if(a == 20)

console.log('Equal to 20');

else if(a == 30)

console.log("Equals to 30");

else if(a == 40)

console.log("Equals to 40");

22
}

else if(a == 50)

console.log("Equals to 50");

else

console.log("Not Equals to 20 /30/ 40/ 50");

Conditional Ternary Operator : "?:"

( condition ) ? True Statements : False Statements ;

condition is an expression, if the the condition is true , True statements

will execute else False statements will execute.

Example :

var age = 13;

var message;

// if(age >= 16 ){

// message = 'Above 16';

// }else{

// message = 'Below 16';

// }

age >= 16 ? (message = 'Above 16') : (message = 'Below 16');

console.log(message);

Switch

switch (expression){

case value1 :

statement1;

break;

case value2 :

statement2;

break;

23
default:

statement;

Switch statement evaluates an expression, compares its result with case

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:

dayName = "Invalid Number";

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;

while(count < 10){

console.log(count); // 1 3 5 7 9

count += 2;

-------------------------------------------------------------------------------------------------------------------------------------

var count = 10;

while(count > 0 ){

console.log(count); // 10 8 6 4 2

count -= 2;

--------------------------------------------------------------------------------------------------------------------------------------

dowhile statement creates a loop that executes a block until

a condition evaluates to false.

do{

// statement

} while(expression);

var count = 1;

do{

console.log(count);

count += 2;

}while(count < 10)

25
var count = 10;

do{

console.log(count);

count -= 2;

}while(count > 0 );

forloop

creates a loop with 3 optional expressions

syntax :

for (initializer; condition; iterator){

// statements

initializer - once the loop starts

The for statement executes the initializer only once the loop

starts. we declare and initialize a local loop Variable in the

initializer.

condition - boolean expression that deteremines the iteration

The Condition is a boolean expression that determines whether

the for loop should execute the next iteration.

The for statement evaluates the condition before each iteration.

if the condition is true, it executes the next iteration else

it will end the loop.

iterator - executes in each iteration

The for statement executes the iterator after each iteration.

for( ; ; ){ }

Example :

for(var i = 0; i < 10; i++){

console.log(i);

-----------------------------------------------------------------------------------------------------------

26
var sum = 0;

for(var i = 0; i <= 9; i++, sum += i);

console.log(sum);

break statement is used to terminate a nested loop.

for(var i = 0; i < 10; i++){

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.

for(var i = 0; i < 10; i++){

if(i % 2 === 0){

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 :

outer : for(var i = 0; i < 4; i++){

for(var j = 0; j < 4 ; j++){

if(i + j == 3) continue outer;

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,

a list of parameters in parenthesis (), and function body follows in {}.

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

function greet(str){ // parameters

console.log("Hello " + str);

greet("Krishna"); // arguments

greet("Abhinav");

When declaring a function, we specify the parameters, when calling a

function, we pass the arguments that are corresponding to the parameters.

getData()

isValid()

function greet(){

console.log("Hello");

greet();

function greet(name){

console.log("Hello " + 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);

function Return a value

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

for(var i =0; i < arguments.length; i++){

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;

for(var i =0; i < arguments.length; i++){

sum += arguments[i];

return sum;

var addition = add; // storing functions into variables

var result = addition(2,3,4,5,6,7,8,9,20,10);

console.log(result);

Passing function to another function

function average(a,b,fn){

return fn(a,b)/2;

function add(a,b){

return a + b;

var result = average(10,20,add);

console.log(result);

Example :

function cmToIn(cm){

return cm/2.54;

function inToCm(inch){

return inch * 2.54;

function convert(fn,val){

return fn(val);

30
console.log(convert(cmToIn,10));

console.log(convert(inToCm,10));

Anonymous function: functions without name

var greet = function(){

console.log('Anonymous function');

greet();

IIFE / Self Invoking Functions

Immediately Invoked Function Execution

(function(){

console.log("I am from Anonymous");

})();

Recursive functions

function countDown(fromNumber){

console.log(fromNumber);

var nextNumber = fromNumber - 1;

if(nextNumber > 0){

countDown(nextNumber);

countDown(5);

function default parameters

function sum(a = 5,b = 6){

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(){

return this.firstName + " " + this.lastName;

};

console.log(person.getFullName());

var student = {

firstName : 'Abhi',

32
lastName : 'Krishna',

age : 23,

marks : [50,60,70,50,60],

getTotalMarks(){

};

Assignment : get student Total Marks, Result , Average

var student = {

firstName : 'Abhi',

lastName : 'Krishna',

getFullName(){

return this.firstName + ' ' + this.lastName;

},

age : 21,

marks : [30,40,50,60,70]

};

console.log(person);

console.log(person.getFullName());

// Assignment : getResult and getTotalMarks

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;

var person1 = new Person('Krishna','Aravind');

var person2 = new Person('Abhi','Anu');

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

- indirect invocation (call(), apply())

Object Properties

[[]]

Object is having 2 types of properties

- Data Properties

- Accessor Properties

Data Properties

contains a single location for a data value

4 attributes

[[Configurable]] - determines a property can be redefined or removed using

delete operator

[[Enumerable]] - indicates if a property can be returned in for..in loop

[[Writable]] - specifies the value of property can be changed

[[Value]] - actual value

To Change any attribute of a property, we can use Object.defineProperty() method.

The Object.defineProperty() method accepts 3 arguments :

1. An Object

2. A Property name of the object

3. A Property Descriptor object that has 4 attributes :

configurable,enumerable,writable and value

34
var person = {};

person.age = 25;

console.log(person);

delete person.age;

// To delete a property from an object we use delete operator

console.log(person);

Example :

'use strict';

var person = {};

person.age = 25;

console.log(person);

delete person.age;

console.log(person);

var 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

contains a single location for a data value

4 attributes

[[Configurable]] - determines a property can be redefined or removed using


delete operator

[[Enumerable]] - indicates if a property can be returned in for..in loop


[[Get]] - returns a Value

[[Set]] - Assign a value

35
Example :

var person = {

firstName : 'Abhi',

lastName : 'Krishna'

};

Object.defineProperty(person,'age',{

configurable : false,

writable : false,

value : 24

});

Object.defineProperty(person,'fullName',{

get : function(){

return this.firstName + ' ' + this.lastName;

});

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

Each function has 2 important properties

length

prototype

length property determines the number of named arguments specified in the

function declaration.

prototype property References the actual function object.

A function object has 3 important methods :

apply()

call()

bind()

Example for apply:

var car = {type : 'Car', wheels : 4};

var bus = {type : 'Bus', wheels : 6};

var say = function(message){

console.log(message);

console.log(this.type + ' has ' + this.wheels + 'Wheels');

say.apply(car,['How many wheels ?']);

say.apply(bus,['How many Wheels ?']);

Example for call:

var car = {type : 'Car', wheels : 4};

var bus = {type : 'Bus', wheels : 6};

var say = function(message){

console.log(message);

console.log(this.type + ' has ' + this.wheels + 'Wheels');

37
say.call(car,'How many wheelsss ?');

say.call(bus,'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

call() method individually.

bind() method creates a new function instance whose this value is bound to the

object that we provide.

Example for bind:

var car = {

speed : 50,

start : function(){

console.log('Start with' + this.speed + ' km/h');

var aircraft = {

speed : 200,

fly : function(){

console.log('Flying');

var comp = car.start.bind(aircraft);

comp();

closures - is a function that References Variables in the outer scope from its inner scope.

function greeting(){

var msg ='Hi';

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.

Document Object Model

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

An element is a node with a specific node type Node.ELEMENT_NODE, which is equal to 1.

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.

The following picture illustrates the relationships between nodes:

Getting Elements from DOM :

getting the Elements

document.getElementsByTagName

method accepts a tag name and returns a live HTMLCollection of Elements

with the matching tag name in the order which they appear in the document.

document.getElementsByClassName

method returns an array-like of objects of the child elements with a specified

classname.

document.getElementsByName

method accepts a name which is the value of the name attribute of the

elements and returns a live NodeList of elements.

41
getting the Element

document.getElementById

method returns an element object that represents an HTML element with an id

that matches a specific string.if the document has no element with the specific id,

the document.getElementById() returns null.

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('p') - first element of the p

document.querySelector('#demo') - Id selectors

document.querySelector('.demo1') - Class 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')

NodeList(2) [div#demo, div.demo1]0: div#demo1: div.demo1length: 2[[Prototype]]: NodeList

document.querySelectorAll('#demo')

NodeList [div#demo]

document.querySelectorAll('.demo1')

NodeList [div.demo1]

document.querySelectorAll('*')

Get the Parent Element parentNode

To get the parent node of a specified node in the DOM tree, you use the parentNode property:

let parent = node.parentNode;

The parentNode is read-only.

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:

let nextSibling = currentNode.nextElementSibling;

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:

let current = document.querySelector('.current');

let nextSibling = current.nextElementSibling;

console.log(nextSibling);

Output:

<li>Careers</li>

Getting Child Elements of a Node

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

Get the first child element

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:

let content = document.getElementById('menu');

let firstChild = content.firstChild.nodeName;

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:

<article id="content"><h2>Heading</h2><p>First paragraph</p></article>

Or to get the first child with the Element node only, you can use the firstElementChild property:

let firstElementChild = parentElement.firstElementChild;

The following code returns the first list item which is the first child element of the menu

let content = document.getElementById('menu');

console.log(content.firstElementChild);

Output:

<li class="first">Home</li>

In this example:

First, select the #menu element by using the getElementById() method.

Second, get the first child element by using the firstElementChild property.

Get the last child element

To get the last child element of a node, you use the lastChild property:

let lastChild = parentElement.lastChild;

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:

let lastChild = parentElement.lastElementChild;

45
The following code returns the list item which is the last child element of the menu:

let menu = document.getElementById('menu');

console.log(main.lastElementChild);

Output: <li class="last">About Us</li>

Get all child elements

To get a live NodeList of child elements of a specified element, you use the childNodes property:

let children = parentElement.childNodes;

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:

let children = parentElement.children;

The following example selects all child elements of the element with the Id main:

let menu = document.getElementById('menu');

let children = menu.children;

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

var div = document.createElement('div');

div.id = 'content';

//div.innerHTML = '<p>Content in Paragraph</p>';

var p = document.createElement('p');

p.innerText = "Some Other Content";

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

The setAttribute() returns undefined.

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:

let style = window.getComputedStyle(element [,pseudoElement]);

Parameters

The getComputedStyle() method accepts two arguments:

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.

pseudoElement specifies the pseudo-element to match. It defaults to null.

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:

let link = document.querySelector('a');

let style = getComputedStyle(link,':hover');

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.

Suppose you have a button with the id btn:

<button id="btn">Click Me!</button>

To define the code that will be executed when the button is clicked, you need to register an event
handler using the addEventListener() method:

let btn = document.querySelector('#btn');

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:

let btn = document.querySelector('#btn');

btn.addEventListener('click',function() {
alert('It was clicked!');
});

Event flow

Assuming that you have the following HTML document:

<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

The following picture illustrates the event capturing effect:

DOM Level 2 Event flow

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:

let btn = document.querySelector('#btn');

btn.addEventListener('click', function(event) {
console.log(event.type);
});

Output:

'click'Code language: JavaScript (javascript)

The following table shows the most commonly used properties and methods of the event object:

Property / Method Description

bubbles true if the event bubbles

cancelable true if the default behavior of the event can be canceled

currentTarget the current element on which the event is firing

defaultPrevented return true if the preventDefault() has been called.

detail more information about the event

eventPhase 1 for capturing phase, 2 for target, 3 for bubbling

preventDefault() cancel the default behaviour for the event. This method is only
effective if the cancelable property is true

stopPropagation() cancel any further event capturing or bubbling. This method


only can be used if the bubbles property is true.

target the target element of the event

type the type of event that was fired

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.

See the following example:

let btn = document.querySelector('#btn');

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.

Three ways to assign Event Handlers :

1. HTML Event Handler Attributes

2. DOM Level 0 Event Handlers

3. DOM Level 2 Event Handlers

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.

<button onclick="dosomething()">Click me </button>

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.

2. DOM Level 0 Event Handlers

<button id="btn">Click me</button>

var btn = document.getElementById('btn');

btn.onclick = function (){

console.log('Do Something');

The DOM Level assigns an event handler to the element event handler properties in the script.

3. DOM Level 2 event Handlers

DOM Level 2 event handlers provides 2 main methods for dealing with the registering / deregistering
event listeners.

addEventListener() - register an Event Handler

removeEventListener() - remove an Event Handler

These methods are available in all DOM Nodes.

59
addEventListener() method accepts 3 arguments :

event name

event handler function

a boolean value - true - event Capturing false - event bubbling.

removeEventListener() removes an event listener that was added by addEventListener.

Example :

<button id="btn">click</button>

var btn = document.querySelector('#btn');

var show = function show(){

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

To create a form in HTML, you use the <form> element:

<form action="/signup" method="post" id="signup">


</form>

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.

JavaScript uses the HTMLFormElement object to represent a form.


The HTMLFormElement has the following properties that correspond to the HTML
attributes:

• action – is the URL that processes the form data. It is equivalent to


the action attribute of the <form> element.
• method – is the HTTP method which is equivalent to the method attribute of
the <form> element.

The HTMLFormElement element also provides the following useful methods:

• submit() – submit the form.


• reset() – reset the form.

Referencing forms

To reference the <form> element, you can use DOM selecting methods such
as getElementById():

const form = document.getElementById('subscribe');

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:

<input type="submit" value="Subscribe">

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 attach an event listener to the submit event, you use


the addEventListener() method of the form element as follows:

const form = document.getElementById('signup');

form.addEventListener('submit', (event) => {


// handle the form data
});

To stop the form from being submitted, you call the preventDefault() method of
the event object inside the submit event handler like this:

form.addEventListener('submit', (event) => {


// stop form submission
event.preventDefault();
});

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();

Accessing form fields

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:

<form action="signup.html" method="post" id="signup">


<h1>Sign Up</h1>
<div class="field">

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:

const form = document.getElementById('signup');

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)

The following accesses the second input element:

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:

const form = document.getElementById('signup');


const name = form.elements['name'];
const email = form.elements['email'];

// getting the element's value


let fullName = name.value;
let emailAddress = email.value;

Put it all together: signup form

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

The following shows the complete app.js file:

// show a message with a type of the input


function showMessage(input, message, type) {
// get the small element and set the message
const msg = input.parentNode.querySelector("small");
msg.innerText = message;
// update the class for the input
input.className = type ? "success" : "error";
return type;
}

function showError(input, message) {


return showMessage(input, message, false);
}

function showSuccess(input) {
return showMessage(input, "", true);
}

function hasValue(input, message) {


if (input.value.trim() === "") {
return showError(input, message);
}
return showSuccess(input);
}

function validateEmail(input, requiredMsg, invalidMsg) {


// check if the value is not empty
if (!hasValue(input, requiredMsg)) {
return false;
}
// validate email format
const emailRegex =

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,}))$/;

const email = input.value.trim();


if (!emailRegex.test(email)) {
return showError(input, invalidMsg);
}
return true;
}

const form = document.querySelector("#signup");

const NAME_REQUIRED = "Please enter your name";


const EMAIL_REQUIRED = "Please enter your email";
const EMAIL_INVALID = "Please enter a correct email address format";

form.addEventListener("submit", function (event) {


// stop form submission
event.preventDefault();

// validate the form


let nameValid =hasValue(form.elements["name"], NAME_REQUIRED);
let emailValid = validateEmail(form.elements["email"],
EMAIL_REQUIRED, EMAIL_INVALID);
// if valid, submit the form.
if (nameValid && emailValid) {
alert("Demo only. No form was posted.");
}
});

In the submit event handler:

1. Stop the form submission by calling the event.preventDefault() method.


2. Validate the name and email fields using
the hasValue() and validateEmail() functions.
3. If both name and email are valid, show an alert. In a real-world application,
you need to call the form.submit() method to submit the form.

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

To Open a new Window or Tab, we use window.open() method

window.open(url,windowName,[windowFeatures]);

To resize a window we use resizeTo() method of the window object

window.resizeTo(width,height);

To move a window to a specified coordinate, we use moveTo() method

window.moveTo(x,y)

To close a window, we use the window.close() method

pop-up / dialog

Browser can invoke a system dialog to display information to the user

alert()

windows alert method / dialog popup

method is used to display information that users has to acknowledge.

confirm()

to invoke a dialog with a question with 2 buttons ok & cancel, we use confirm() method

function simple(){

var result = confirm('Are you surely want to delete?');

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

dialog with input text with 2 buttons ok and cancel

function simple(){

var ageStr = prompt("How old are you ?");

var age = Number(ageStr);

var feeback = age >= 16 ? 'Elgible to Join' : 'Must be atleast 16 years';

alert(feeback);

setTimeout() is a method of window Object.

sets a timer and executes a callback function after the timer expires.

setTimeout(cb,[,delay],arg1,arg2,arg3.....);

cb - callback function to be executed after the timer expires

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.

arg1,arg2... are arguments passed to the callback function

setTimeout(function(){

console.log("Hello");

}, 5000);

setTimeout(something, 5000, "Krishna");

function something(a){

console.log("Hello",a);

69
var timeoutID;

function simple(a){

console.log("Timeout Text :",a);

timeoutID = setTimeout(simple,3000, 'SetTime Out Here');

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

console.log("Interval Text :",a);

Interval = setInterval(simple,3000, 'SetTime Out Here');

function clearAlert(){

clearInterval(IntervalID);

Location Object represents the current location (URL) of a document

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.

History object provides 3 Methods : back() forward() go()

71
ES6

ECMASCRIPT 2015 or ES2015 or ES6 is a significant update to the

JavaScript programming language. it is the first major update to

the language since ES5 which was standardised in 2009.

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

keyword creates a read-only Reference to a value.


const CONSTANT_VALUE = value;
By convention, the constant identifiers are in uppercase.

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

(...) - spread out the values of an iterable object - array,map,set


let odd = [1,3,5];
let combined = [2,4,6,...odd];
console.log(combined);
let names = ['Abhi','Arjun','Akhil'];
let moreNames = ['Balu','Babitha'];
//[].push.apply(names,moreNames);
names.push(...moreNames);
console.log(names);

73
Rest Parameter (...)

ES6 provides a new kind of parameter called Rest-parameter that has a prefix of

three dots(...). A Rest parameter allows us to represent an indefinite number

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

iterate over a collection such as Array,Map,Set.


let arr = [1,2,3,4,5];
let obj = {a : 1, b : 2, c : 3};
for(let a of arr){
console.log(a);
}
for(let o in obj){
console.log(o + "--> " + obj[o]);
}

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

Object Literal Syntax:


Object literal is one of the most popular patterns for creating objects in JavaScript
because of its simplicity.ES6 makes the object literal more succinct and powerful by
extending the syntax in some ways.
function createProperty(name,status){
return{
name,
status}
}
Computed Property Name :
let name1 = 'Employee';
let person = {
[name1] : 'Krishna',
'address' : 'Hyderabad'
};
console.log(person);
We use [ ] square brackets to enable the computed property names of the
properties on objects.

let prefix = 'machine';

let machine = {

[prefix + ' name'] : 'server',

[prefix + ' hours'] : 1000

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

Arrow functions vs regular function:


There are 2 main differences between an arrow function and a regular function :

1. In the arrow functions, this,arguments,super,new.target are lexical. it means


that the arrow function uses these variables (or constructs) from the enclosing
lexical scope.
2. An Arrow function cannot be used as a function constructor. if we use new
keyword to create a new object from an arrow function, we will get an error.

arrow functions will not allow this


const counter = {
count : 0,
next : function() {return ++this.count} ,
current : function() { return this.count}
}
console.log(counter.next());

77
ES6 Classes***:
Class is a Blueprint for creating Objects.

A class encapsulates data and functions that manipulate data

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.

class Name identifier will be in CamelCase


class Person{
constructor(name){
this.name = name;
}
// getName(){
// return this.name;
// }
}
let person = new Person("Krishna");
console.log(person.name);
let person1 = new Person("Abhi");
console.log(person1);
-------------------------------------------

Getters and Setters :

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 :

A class expression provides an alternative way to define a new class


let Person = class{
constructor(name){
this.name = name;
}
}
let std = new Person("Krishna");
console.log(std);
Singleton Design Pattern :

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.

use the className.staticMethodName() or this.constructor.staticMethodName() to


call a static method in a class constructor or an instance method.
class Person{
constructor(name){
this.name = name;
}
getName(){
return this.name;
}
static createAnonymous(gender){
let name = (gender == "Male") ? "Krishna" :
"Someone Else";
return new Person(name);
}
}
let std = new Person("Krishna");
console.log(person);
let anony = Person.createAnonymous("Male");
console.log(anony);
Static Properties :

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

Fulfilled with a value

Rejected with a reason

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 :

To Create a promise, we use Promise() constructor.


const promise = new Promise((resolve,reject) => {
// operations
if(success){
resolve(value);
}else{
reject(error)
}
});
The Promise constructor accepts a callback function that typically performs an
asynchronous operation. This function is often referred to as an executor.

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 :

we have 3 methods to consume 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

The catch() method

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.

The finally() method

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:

JavaScript promise chaining pattern that chains the promises to execute


asynchronous operations in sequence.

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

The Promise.race(iterabale) method returns a new Promise that fulfils or rejects as


soon as one of the promises in an iterabale fulfils or rejects with the value or error from
that promise.

Promise.any()

Promise.any() method takes the list of the promises and return a promise that fulfils first.

Promise.allSettled() ES2020

Handle Errors in Promises :

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 :

Async / Await is new way to handle asynchronous operations.


function getUser(userId){
return new Promise((resolve,reject) => {
console.log('Getting Users');
setTimeout(() => {
resolve({
userId : userId,
userName : 'Admin'
})
},2000);
})
}

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.

export and import


import { message as msg,setMessage } from "./app.js";
setMessage("Hello ES6 Module");
console.log(message);
or
import * as sam from './app.js';
import anything from './sort.js';
sam.setMessage("Hello Sam");
console.log(sam.message);
console.log(anything([2,1,4,5,3]));

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)

let emp1={name:"Abhi"},emp2={name:"Balu"},emp3={name: "Cita"};


let userRoles = new Map();
console.log(typeof(userRoles));
userRoles.set(emp1,'Developer').set(emp2,'Designer').set(emp3,
"Admin");
console.log(userRoles.size);
console.log(userRoles.values());
let a = 'abhi',b = 'Balu';
----------------------------------------------------
let users = new Map();
users.set(a,"Developer").set(b,'Designer');
console.log(users);

Set
stores a collection of unique values of any type.

let setObj = new Set(iterableObject);

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.

Symbol doesn't have a literal form.


var numbers = [4,5,6,7,8];
// for(let num of numbers){
// console.log(num);
// }
var iterator = numbers[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
Example :
function Money(amount, currency) {
this.amount = amount;
this.currency = currency;
}
Money.prototype[Symbol.toPrimitive] = function(hint) {
var result;
switch (hint) {
case 'string':
result = this.amount + this.currency;
break;
case 'number':
result = this.amount;
break;
case 'default':

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...')
}
}
}
};

let evenNumbers = new Sequence(2,10,2);


console.log(evenNumbers);
for(const num of evenNumbers){
// if(num > 6){
// break;
// }
console.log(num);
}

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

Static Methods of Cookie :


get()
set()
remove()

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

You might also like