0% found this document useful (0 votes)
105 views15 pages

INP MOD2 JavaScript

Uploaded by

Ms. Noah Naomi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
105 views15 pages

INP MOD2 JavaScript

Uploaded by

Ms. Noah Naomi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

MODULE 2

Java Script
CHAPTER 2

Syllabus
Introduction to
ES6, Difference between ES5 and ES6.
Variables, Condition, Loops, Functions, Events. Arrow functions.
DOM manipulation, Classes and Inheritance.
Iterators and Generators, Promise, client-server
Self Study: Asynchronous JavaScript, JSON communication, Fetch

2.1 Introduction to ES6. *****°********a*** ******************s****


e************aona** *** *****a******************************°**s* .2-3
*

2.1.1 What is ES6 ? . .


*°°*7°*********Ia9****************°°*°**°****°°*"****°**********°°*******°°****°'***°******* *** **************************:.2-3
2.1.2 History... ***"**°******"******"******"**°*"°** *********** 2-3
2.1.3 ES6 Environment Setup..
****e**********a********************a*******aaonnse***************""********e*******************
2.1.4 ES6 Syntax. **********°****** **************"ae*****a*********************** **°°°a*******************************************************2-4
2.2 Difference between ES5 and ES6... * ***********************************. 2-4
°*"*****"******°**********"**********

2.3 ES6 Variables. *********** ****** * * * * * * * * * * * * * * * * e * * *


*°****** ****°*****"***°*"***"********as***
.2-5
2.4 ES6 Decision-Making. *************es*a***e************** ***ne"°*°**************.
**n*******uns*e**o**a**********a********************aa.2-7

2.4.1 The if Statemen.. **********a********. ************************e**************** ********senmmnueu .asnaranesren2-7

2.4.2 The if...else Statement ************************************************e********************annouasnen**ntmaone*s* . .2-8

2.4.3 The if...else if...else Statement.. ********************************************************aeesnnnsunann*** .*** Z-8


i

2.4.4 The Nested if Statement.


***********************************************************eueessadiassnasasnsoa**unsonnnnn*aaasannusaruuaaassessa.an.
2-8

2.4.5 The Switch Statement. 2-9

2.5 ES6 Loops.**a*anmeo*spanans*p**ss*******************a*n********* 2-10

2.5.1 Definite Loops..


sopupanpesnoarrdnsosenaaas*nae**ap******* ***********a*************uteuexen****4sannnsanenaarsus . 2-10

2.5.1.1 Thefor (;) Loop.. *s*s******vepopnonp****************************"********"************ *a*seaganum aaerorasese 2-10

2.5.1.2 The for...in Loop. 2-10

2.5.1.3 The for...of Loop. 2-11

2.5.2 Indefinite Loops..


supp2aernoesnoassoousspos*sossepa*********************"********a*************tsda*a*******a **attainsa*****assdshaaa***so**r2-12

2.5.2.1 The while Loop... * 2-122

2.5.2.2 The do...while Loop *upnuenee************9*****s*************************** sss*ammag**eA*aran 2-12


(Java Scipt)..Page no. (2-2)
****************
*******************
***************

2-12 Internet Programming (MU -Sem 5-IT)


5-11 Java Script.Page no.(23
intermet Programming (MU Sem
**

***
**************

2-13
i
*********

* * * *************

******************* * *
Eich commented that "ECMAScript was always an unwanted trade
2.6 ES6 Functions. s
******************

* * * **
**"* * * * * * * *
********
***************
***"*****

2-13 2.1 INTRODUCTION TO ES6 name which sounds like a skin disease (eczema)
Parameterized Funcions. **********
2.6.1 ****************
Function....
***********************************"**

**************
***********
.. ******"***************sk
*********.

2-13 2.1.1 What is ES6?


2.6.2 Anonymous 2.1.3 ES6 Environment Setup
********************** *******************
******** ****°«
14
2.7 ES6 Arrow Function.. ***********
GQ Explain ES6 in detail. (10Marks) JavaScript can run on any host, any operating system, and on
with Parameters.
**************

******************"*
*******************°

2-15 *****
2.7.1 Arrow Function
*******

any browser. To start experimenting with JavaScript, you


****************
ES6 is an acronym of ECMAScript 6 and also known as
2.7.2 Advantages of Arrow
Funcions
***
**********..

2-15 have to download the latest version of the Node.


~****************************
ECMAScript 2015.ES6 or ECMAScript 2015 is the 6th version of
*****************************
***
*"***************** ..2-16
*****
the ECMAScript programming language. ECMAScript is the
Node is a platform that runs on the V8 JavaScript engine (t Moui
2.8 ES6 HTML DOM . *****************
****

is a JavaScript engine that is responsible for running the


2.8.1 Types of D O M . .
****************
*********************°2 - 1 8 standardization of Javascript which was released in 2015, and 2
*********** JavaScript code) of Google. It helps you to create scalable
*"'****"***************************** subsequently renamed as ECMAScript 2015.
2.9 Classes and Inhentance.
**********************" ***
* *************
*************.
18 and fast applications by using pure JavaScript.
********************

2 - 12 9
ES6 or ECMAScriptó is a scripting language specification You will require the following for writing and testing ofa
ES6 Classes.
*********************** . . ,
*
************
2.9.1
*

****************************"
which is standardized by ECMAScript International. ECMAScript
* * JavaScript program standard:
*
2.9.2 Class inheritance.. ****************************
*
**
****************
.2-20 is generally used for client-side scripting, and it is also used for
**************************************
writing server applications and services by using Node.js. ES6 BText Editor
2.10 ES6 Iterator.. ******* 2-22
2
************************************************************************ allows you to make the code more modem and readable.
Text Editor is a computer program that edits plain text. It is
2.11 ES6 Generators.. *************an***.
.2-23 By using ES6 features, we write less and do more, so the
***************************************************************************************** ** used to Write the source code. Some of the text editors
2.12 ES6 Promises. ********************************** °**************"******************** **************************** Z24 term Write less, do more' suits ES6. ES6 introduces many great include Notepad or Notepad++ for Microsoft Windows.
2.12.1 Need of Promises. features such as scope variable, arrow functions, template strings, UNIX or Uiz-like operating systems uses the Pico editor but
******"*************"************************************.a 2-24
2
******n *** class destructions, modules, etc. ES6 was created to standardize also use the VI and Emacs editor.
2.12.2 Making Promises..** ***********u

****************************"**************************"************ .. 2-24
2.12.3 Callbacks to Promises
****************
** ***** JavaScript to help several independent implementati ons. Since the The editors may vary with the operating system. The source
******************************************************"**********************************"*******************"*******-***.
2-25 standard was first published, JavaScript has remained the well-
files should be named with the .js extension.
2.13 Client Server Communication.. known implementation of ECMAScript, comparison to other most
2.14 Fetch ********************************************************************"************************************************************************************************»ET 2-28
famous implementations such as Jscript and ActionScript.
EInstalling the Node.js
*******************************************""****************"***************************************°"********************.2-29
The Node.js is an open-source server-side environment that
Chapter Ends.. 2.1.2 History
Is ree and can nun on ultiple platforms such as Windows, UNLX
The ECMAScript specification is the standardized Linux, etc. It uses the JavaScript on the server. It uses the Google

specification ofscripting language, which is developed by Brendan v8 JavaScript engine for executing the code. It uses the

American technologist and the of Javascript


Eich is an creator
asynchronous programming
named
programming language. Initially, the ECMAScript was

In December
Installation on Windows
Mocha, later LiveScript, and finally, JavaScipt.
American company that sold the 1. You can download the Node.js from its official website. For
1995, Sun Microsystems (an
and services. It created downloading the Node.js, you can click on the following link
computers and its components, software, IT'
Java, NFS, ZFS, SPARC, etc.) and Netscape announced the https://nodejs.org/en/.
November Cick the current version and install the Node.js on your
Javaacript during a press elease. During 1996, 2. on

announced a meeting of the ECMA International system.


Netscape
the Next button and accept the License
organization to enhance the standardization of Javascnpt.
standard 3. Then, click on

agreement, and after setting up the path, you can successfully


ECMA General Assembly adopted the first edition of ECMA-262
in June 1997. Since then, there are several editions of the language install Node.js on your system.
was successful, you could check it by
standard have published. The Name ECMASCript was
a4. If the installation

which included the entering the following command in your terminal


settlement between the organizations
window:node -v
Microsoft,
Standardizing of the language, especially Netscape and
the standard sessions. Brendan
whose disputes dominated primary

lew Syllabus w.e.f academic year 21-22) (M5-78) (New Syllabus w.e.f academic year 21-22) (M5-78) Tech-Neo Publications..ASACHIN SHAH Venture
JTech-Neo Publications..A SACHIN SHAH Ventu
(JavaScript)...Page no.
These
comments a re used to comment Internet Programming (MU -Sem 5-IT Java Script).Page no. (2-5]
Sem 5-
comments:

nemet Programming (MU -


Single-line

line. arameter
2.1.4 ES6 Syntax on the single
comment
ES6
the arrangemenis / t is a
single-line Definition ESS is the fifth edition of the
ECMAScript (a | ES6 is the sixth edition of the ECMAScript (a
which defines e.g:
ven to
given to elements
is the set of rules are the
names
h e syntax
languages in wniCn une Identifiers trademarked scripting language specification | trademarked scripting language specification defined
to programming
variables, etc."
Identifiers

Syntax applies variables, etc. There defined by ECMA


0 Symbols.
applies to markup such as
functions,
are International) by ECMA International).
P n t s
the source code and also within a program, that are as follows:
document describes
the data. The program
rules for
the
identifiers Release It was introduced in 2009. I t was introduced in 2015.
languages, in which the some

Identifiers do not include any special symbol excen the


ofF Data-typeS
within the JavaScript consists ESSsupports primitive data types that are string, In ES6, there are some additions to Javascript data
1or
a notation
Literals : A literal can be defined as dollarsign (S)orunderscore).
number, boolean, null, and undefined. types. It introduced new primitive data type
value within the
fixed
source
code.
be a keyword. 'symbol' for supporting unique values. ,
Module
representingthe name
must not
In The identifier
for initializing the variables. o
used
Generally, literals are digits. R Defining Variables In ESS, could only define the variables by In ES6, there define
c a n see the use of literals in
Identifiers include
the characters as well as we are two new ways to variables
tne following example, you o using the var keyword.
literal, and the string
"hello" is
start the name or the
1dentifier with a digi that is by using let and const.
which 1 represents theinteger you cannot
Performance As ES5 is prior to ES6, there is a non-presence of features and the shorthand
a string literal. Identifiers are case-sensiive
and do not contain spaces | Because of new
storage
o some features, so it has a lower performance than implementation ES6 has a higher performance than
int x = 1;
Example: userName, user_name, namel4 ES6.
Valid Identifiers ESS
string str= "hello";
Support A wide range of communities supports it. It also has a lot of community support, but it is lesser
the storage location that is name
Variables: A variable is Example: Name @, user name, user-name, than ESS.
variable is the name Invalid identifiers
identified the memory address. The
by
the values for the program. 14name. Object Manipulation ESS is time-consuming than ES6. Due to destructuring and speed operators, object
of a memory block that stores
manipulation can be processed more smoothly in

2.2 DIFFERENCE BETWEEN ES5 AND ES6


of referencing
The name of the variable is the standard way
ES6.
the stored value.
word Arrow Functions InESS, both function and return keywords are An arrow function is a new feature introduceed
Computer programming, a keyword is a Marks
GQ. Differentiatebetween ES5 and ES6
Keywords: In
that has a specíal meaning in a specific context. It cannot be * * * * * * * * **** used to define a function. ES6 by which we don't require
or ECMAScript is a trademarked scripting language the function keyword to define the function."
used as an identifier like the variable name, function name,

label. specification that is defined by ECMA- International. It was Loops In ES5, there is a use of for loop to iterate over ES6 introduced the concept of for..of loop to

Operators: Operators are symbols that define the processing created to standardize JavaScipt.scripting language
The ES elements. perform iteration over the values of the iterable
of operands. Some of the common examples of operators objects.
has many implementations, and the popular one is
include arithmetic (addition with +), logical operators (like
JavaScript
Generally, ECMAScript is used for client-side scripting of Initialization of Varlable
AND or &&), etc.

Comments are the programmer-readable


the World Wide Web. W 2.3 ES6 VARIABLES It is the process to store the value in the variable. A variable
can be initialized at any time before its use
Comments8 ES5 is an abbreviation of ECMAScript 5 and also known as
annotations (extra information) in the source code of a The ES6 syntax used the keyword var to declare a variable,
computer program. Comnments are added to make the source
ECMAScript 2009. The sixth edition of the ECMAScript GQ Howto dedaredvaiablesin ES62 Marks) In ES5, we declare the variable like this:
code easy to understand for humans. Comments increased the standard ES6ECMAScript 6. It is also known a
or GO Define let and constkeywords (5
Marks) -var x I/Declaration of a variable by using the var keyword
readability of code and ignored by the compilers and ECMAScript 2015. ES6 is a major enhancement in tn A variable is a named space in the memory, which stores the Valld type of syntax for variable declaration
interpreters.JavaSeript sSupports the following two types of Javaacript language that allows us to write programs for values. The names of the variable are known as identifiers. There Some variable declarations are consídered to be valid are as
comments: are some nules that you should keep in mind while naming an
complex applications. follows:
identifier. These rules are as follows:
Multi-Jine comments: These comments are used for Although ES5 and ES6 have some similarities in their var Sexamplel=value
commenting on the multiple lines. nature It can contain numbers and alphabets. ,
var examplel=value
there are also so
many differences between them.
You cannot start the name of the variable with a nu var_example$=value
Cxampie of multi-line comment/. Keywords cannot be used ag the name of the variable, In ES6, the variables are declared by:
Identifiers do Using let
not
spaces and special
contain characters
except the dollar (5) symbol andundescore Using const
New SytlabuS wef academic year 21-22) (M5-78) (New Syllabus w.e.facademic year 21-22) (M5-78) Tech-Neo Publications..A SACHIN SHAH Venture
Tech-Neo Publications..A SACHIN SHAH Venture
(Java Scnpi age m2
(2.
IntermetProgramming (MU Sem 5-I
Output
comstant
vanable.
For example
Java Scipt)..Page no. (2-7)
Assignment to
e teywords TypeEo h e constant
=100
d e c i a r e i by ang
te t
eo t throw an
eTor
because
ariables
va
JavaScript Declarations are Hoistedd
consok.log{x+ *+yk
bur a a value.
thng reassigned
the bior* scrze.
Bicck scope and cannot be =10:
**Eed iTTRabk
y-200,
JavaScript Variable Scope consoke.og{x when you execte this code, you will get thbe following
Java>c+ipt that
are global and output in
which the vaBae of y is
There are two scopes
in
local 2a
undefined.L
In the global scope, the variable ca Instead of givinga declaration Output
Gobal Scope: eror, de above code will
code.
accessed from any part of the JavaScript successfully execute and show the desired output t
happens 100 undefned
the vanable can be because of the boisting concept. Le us see what happens when the This bappes because hoisting does not allow as to move the
Scope: In the ocal scope,
Local
where it is declared.
code is in the compiling phase. initialization of variables oa the top if you insialize them after Module
within a function
When the above code is in the compile phase, then using
it wil be
treated as
The foliowing example
descibes the Global and Lo
In compiling phase
2.4 ES6 DECISION-MAKING
SCope var x; // declaration of the variable will
Output move on top. ES6 conditional statemeats are used to perform different
In this example, theTe are two vanabies one is outside the
20 x=10; actions based on vaious conditions. The conditional statement
and the other is in the function (lo
function (global scope),
console.log(x); evaluates a condition before the execution of instructions.
scope) When you write the code, you require to pestom diterent
Output
varSvar12= 200; different decisions.
By ing et
function examplej i
10 actions for You can easily perform it by using
conditional statements.
k = 100 JavaScript Initializations are not Hoisted
var varl2= 300;
1. When you initialize the variable before using FTypes of Conditional Statements
console.log(Inside exanplef) funetíon
omne.kg1 var x=100; The conditional statements in JavaScript are isted below
Output
+Svar12); var y=200; if stateme

SymasEraoe dentifier'* has aready been declared console.logx+" "+9)% if..else statement
wen the c e zets ccessfulily ezecued, you will get an consoe.logutside examplet function In compiling phase
i..cse if...statemes
em tht the identifus han already been declared. So, any +var12); var x Dested if staiement
variahle which in declared by using the ka keyword is assigned the
examplel)s var y
blck wasp switch statement
Output
2.
100;
Outside example) funetion 200 y=200;
2.4.1 The if Statement
ES6 gives a new way 0 deckare á COnstant using the comst
Inside enamplel) function300 It is one of the simplest decision-making statement which is
keywnd. The keyword const creaes a read-only reserence to the console.log(x+" "+y);
vawe. There are woe properics of the const that are as follows: JavaScript Dynamic Typing used to decide whether a block of JavaScript code will execute if a
Output
JavaSceript supports the concept of Dynamic Typing as certain condition is trae.
Properties
similar to Pyhon, PERL, Ruby, etc. It is a feature where you 100200
I cannon be reassigreda value
do 2. When you initialize the variable after using it
Syntax
not need to tell
Javascript about what type of value the variable if(condition)
it in biosck suped. will bold. If the type of value of the variable var x=100;
gets changed during block of code wil execute if the condition is true
the execution of the console.logx+" "+y);
Anstant canngt be re-declared. program, then it gets triggered, and JavasCnpP
Cmstants
automatically takes care of it. var y=200;
Must be initialized at the time of declaration. If the condition evaluates to true, the code within if statement.
ES6 and Varlable Hoisting When this code is in compiling..then it wil be treated
Por exanpe will execute, but
follows: if the condition evauates to false, then the code
Hoisting is the default behavior ater the end of if statement (after the closing of curly braces) will
const y 1K
declaralions the top
to
of JavaScript to move au In Compiling phase
y«200) 1/ Jt will result in an error of the current script, current functon, execute.
Current var x;
scope. It allows you to use the variable The if statement must be written in the lowercase letters. The
declaration.
before
JavaScript only hoists the variable declaration, not vary use of Uppercase letters (f or IF) wil cause aJavascript emor
variable initialization.
(New Syllabus w.e.f academic year 21-22) (M5-78) (New Syllabus w.e.f.academic year 21-22) (M5-78) Tech-Neo Publications.A SACHIN SHAH Venture
Tech-Neo Publications..A SACHIN SHAH nture
Ven
(JavaScriptPago no.(2-01
Internet Programming (MU. Sem 5-IT
Internet Programming(MU-Sem5 Output
Java Scrip)...Page no. (2-9)
x is greater default : It specifies some code to run when there is no case
For example
if....else Statement Statement 2, /t will execute when condition2 is true
var x= 78
2.4.3 The f..else match. There can be only a single default keyword in a
The if switch. It is also optional, but it is recommended to use it as
if (x>70) {
test muliple
conditions.
atement can
states
else
used to it takes care of unexpected cases.
console.log(x is greater") It is and they must be
used
statements

zero
else ii
or
have multiple
statement.
You should always be ken Statement 3://t wilexecute when condition2 is false If the condition passed to switch doesn't match with any
else
before using the the else if statements.
nents.
value in cases, then the statement under the default will get
after
Output must come

that the
else statement executed.
xisgreater
Symtax Example Syntax
a 2.4.2 The if.else Statement if(conditionl)s switch(espsessionH Modnle-
var num 20 2
An if....else statement includes tvo blocks
that are
it block cade valuel1
control statement,
which
block of code will execute
if condition is true if(num10)
and else block. It is the next form of the Hcode to be executed
t 1s
controlled way.
allows the execution of JavaScript in a more
break: loptional
used when you require to check two different
conditions and
elee if (condition2) if(num%20) case value2
used for
execute a different set of codes. The else statement is
console.lo8( num1s greater than 10 and even number Jcode to be execute
specifying the execution of a block of code if the condition is false.
block of code will executeit the conditionl rs false and else
break /optional
Syntax
condition? is true Console.log(num t than 10 and odd number
f (condition)
default
biock ol code will execute if the condition is tre
code to be exeeited i al caes are not matche
block of code will execute if the conditionl is false andi
condition2 isfalse console log num15 smalerthan 10 )
else

block ofoode willexeeute if the condition is false Example console.logCAfter nested if statement) Example
var a 10,b 20,c30: Output

If the condition is true, the code within the if statement will


20is reater than 10 and even numb Sitchnum
be executed; if the condition is false, the code after the end of the if console.loga is greater After nested if staterment case0
statement (after the closing of curiy braces) will be executed else if(ba&&b o) console.log( Sun
console.log("bisgreater" 2.4.5 The Switch Statement break
Example
else lt is a multi-way
Let us try to understand if....else statement by the following branch statement that is also used for
example: console.logcis greater decision-making purposes. In some cases, the switch statement is case
varx40, y=20; more convenient than if-else statements. It is mainly used when all console.ogtMonc
Output branches depend upon the value of a single variable. It executes a break
cis greater block of code depending upon the different cases
console.iog y is greater");
2.4.4
The switch statement uses the break or default
keywords, but case 2
The Nested if Statement both of them are optional. Let us define these two keywords: consolelogttuesday
else It is an if statement inside if statement. break: It is used within the switch statement break
an
for terminating
{ Syntax the sequence of a It is optional to use. If it gcts
statoment.

console,log(x is greater ; if (conditionl) omited, then the execution will continue on each statement, case 3
When it is used, then it will stop the execution within the eonsole.log Wednesday
)
Statement 1; i/t will block. hreak
execute when.conditionl is true
(New Syllabus w.e.f academic year
if(condítion2)
21-22) (M5-78)
ech-Neo (New Syllabus w.e.f academic year 21-22) (M5-78) lTech-Neo Publications.A SACHIN SHAH Vénture
Publications..ASSACHIN SHAH enture
(JavaScript)age no.(2-10
InternetProgrammin9 (MU- Sem 5-IT)
2.5.1 Definite Loops
nternet Programming(MU -Sem 5
11)
properties or keys of the object, then you can use for..in Java Script).Page no. (2-11)
number of iterati loop. It is for(var props in
Case4: A definite loop has a
dehnite/tixed

loops that listed helow:


are
a better choice when you are working with
objects or dictionaries Samsung)
three types of definite
where the order of index is not essential.
console.log(Thursday ): ES6, there are
code for
the block of
block of code for a
break; fort:) Loop:
executes
definite Syntax eonsole.log{prope 4Samsung[props
number of times.

iterates througn
tne properties of the objee
for (variable name in object name) /Here in is the keyword
Output
case5: for..in Loop: It
for...of loop: Unlike object literals, it iterates the iterables
console.log(Friday"); / statemet or block to execute Model :Calax
break; (aTays, stning. etc.). Color: White
In every iteration, RAM:4GB
The for (G:)Loop Modale
one
property from the object is assigned to
a 2.5.1.1 Price: function price)
case6: the name of the variable,
and this loop continues till all
of the 2
is to iterate a part of the progr
console.log Saturday"): The for (::) loop
used
object properties get covered.
number or iterations, then it
break; multiple times. If you have a fixed
Example Console.log(this.modelPrice Rs.3300
recommended to use for loop.
always function Mobile(model no
default: {
Syntax this.Modelmodel no a 2.5.1.3 The for..ot Loop
console.log(lnvadid choice"); forfinitialization;conditionginer/decr)
this.Color White Unike the object literals, this loop is used to iterate the
break; Mstatemenl er code to be
executed this.RAM 4GB terables (arays, string, etc.). **

Syntax
The for' loop includes some parts
that follows
are defined as
ar Samsungnew MobileCalaxy
Output Initialization : It is the initial condition that is executed onc for var props in Samsung
forfvariable name of objeet namel Hereofis akerword
Friday at the starting of the loop. In this part, we initialize the variable, or /statement or block toexecute
already initialized variable. It is an consolelogprops t Samsiunglprops)
2.5 ES6 LOOPS * * * **
it can also be used for the

optional statement. la every iteration, one property rom the iterables gets

Explain different types of loops in ES6.


GO * * * * * * * *******-***+*°--
(L0 Marks) Condition : It is executed each time for testing the condition Ouput assigned to the variable_name, and the loop continues till the end

Looping statements in the programming languages help


to
of the loop. It continues the execution of the loop until the Model Galay of the iteration.

execute the set of instrucions/functions repeatedly while a condition is false. It returns only Boolean values that are eithertrue Color White Example
condition evaluates to true. Loops are an ideal way to perform tne orfalse. It is also an optional statement, RAM 4CB var fraitsTAprle Banana, Mango Orangel
execution of certain conditions repeatedly. In a loop. the repetition
increment
If you pass the function in the properties of the object then forlet value of fruits
is termed as iteration.
Increment/Decrement: It can or
decrement the this loop will give you the complete function in the output. You
value of the variable, and it is also an optional statement. can it's illustration in the following code:
Classification of loops
Statement : It represents the body of the loop, which is
fuactionMobilemodel no
Definite For(:) executed every time until the conditional expression is false.
this.Model model no,
Example: The table of 2 by using for loop.
ais ColorWhte
For...in var i this RAM 4GB: You can also wite the above code ike
forfi-l;i=10;it +) this.Price function price() # The. loop will give you thisforflet value of Fapple Banana, Mango Orange
LoopsH For..of function as it is written here.

console.log("2x"i+,21, console.og(valiios
console.log(this.model "Price Rs. 3300 )
For:)
Indefinite 2.5.1.2 The for..in Loop
For.in The for..in
loop is similar to for Ioop, which iteratesthroug
var Samsung new Mobiler'Galaxy
the visitt
(181)Fig.2.5.1 :Clasification of Loops properties of an object,
i.e., when you require ltech-Neo Publications.A SACHIN SHAH Venture
(New Syllabus w.ef academic year 21-22) (MS-78)
(New Syllabus wef academic year 21-22) (M5-78)
Tech-Neo Publications...A SACHIN SHAH Venu
(Java Script..Page no.(2-12

5-) The
do...whille
Loop Internet Programming (MU Sem 5-IT)
internet Programming(MU-Sem 2.5.2.2

To force the cxccution (Java Script)....Page no. (2-13)


that executes aa
executes block
of codeat of the function, we
must have to 2.6.2
Output
It is a
control
flow
statcment

invoke (or call) the function. It is known as function invocation. Anomymous Function
upon the condition
condition whether or
will depend pon The syntax for invoking a function is as follows:
Apple lcast once,
and then it
An anonymous function can be defined
repeatedly.
as a function without
Banana executes the block
function_name() a name. The
noi the loop anonymous function does not bind with an identifier.
Mango after the
dition after
execution
condition

loop
checks the
Example It can be declared
dynamically at runtime.
The do...while
Orange is also known
function hello) 7/defining a function
the
structure
control
why this An anonymous function
that's can be assigned within variable.
2.5.2 Indefinite Loops ofthe block. that the condition
a

post-test loop. It is also a posSIbIlity


ways Such expression is referred to as function expression. The syntax
infinite iterations. It is used
when the
which will c r e a t e an infinite loop. console.log (hello function called") for the anonymous function is as follows.
ndetinite
loophas unknown.
evaluates to true,
intermediate or
number of iterations within the loop is Syntax Modul-
listed below: Syntax hello0: //ealling of function 2
There are two types of indefinite loops
that are
vary function( [arguments]
In the above code, we have defined a
the instructions each
time ill thedo function hello). The
while Loop: It executes
{ pair of parentheses {) define the body of the function, which is
defined condition evaluates to true.
be executeds called a scope of function. lcode to be executed
do...while It is similar to the while loop. but the key /block ofstatements to
Loop:
difference is that the do...while loop executes the loop at
oncE} 2.6.1 Parameterized Functions Example
irrespective of the terminator condition. while (expression)s
Parameters are the names that are listed in the definition of var hello function0
Example
a2.5.2.1 The while Loop
fact=1;
the function. They are the mechanism
of passing the values to console.log(Heltg World)
var count 6 , functions.
console.logtTaí an anonymous function)
the
A while loop is a control flow statement that allowS
The values of the
execution of code based on the given Boolean condition.
fact factcount-
parameters are passed to the function
repeated
during invocation. Unless it is specified explicitly, the number ofhello0:
It consists of a block of code and an expression/condition.
}while (count0); values passed to a function must match with the defined number of
The while loop checks the expression/condition before the Parametenized Anonymous function
parameters.
execution of block; that's why this control structure is often known console.log(fact); Example
Syntax
as a pre-test loop.
The syntax for defining a parameterized function is:
var anonfuncttonfab
Syntax
M 2.6 ES6 FUNCTIONS
functonfunction name parameterl,parameter2 refum a b
while (condition) {
GQ Explain functions in ES6. 5Mark ParameterN
statements ***********
body ofthe funete function sum)
A function is the set of input statements, which performs
Example specific computations and produces output. It is a block of code Example
that is designed for performing a particular task. In this example of parameterized function, we define a
resanon(l00,200};
var yU; console.log Sum:tre
In
function mul0, which accepts two and y, and it
parameters x
while (y< 4{ JavaScript, functions are defined by usingg
fünciou returns their multiplication in the result. The parameter values are
consoBe.log(y keyword followed by a name and
parentheses 0. The function passed to the function during invocation.
name may include digits, letters, dollar sign, and underscore.
y+t Tne function mul xy
brackets in the function name may consist of the nameo
2.7 ES6 ARROW FUNCTION
parameters separated by commas. The body of the function should Yar
The condition is always required in the while loop DEcause 1
is necessary to the
be placed ithin curly braces {}. Consolelog( GQ Give an example of an Arrow function in ES6? List
run
loop. If the condition retuns true, then the
down its advantages a0Marks
loop will start over again, but if it returns false, the loop will The syntax for
defining a standard function is as follows
console.log ty
stop.
If the condition will always true, then the
loop will never functionfunction_name(0 console.log(x to Arrow functions are anonymous functions (the functions
without a name and not bound with an identifier). They
end.
I/body of the function don't retum
any value and can dectare without the function keyword. Arow
mul(20,30) functions cannot be used as the constructors. The context within
the arow functions is lexically or statically defined. They are also
(New Syllabus w.e.f academic year 21-22)
(M5-78) (New Syllabus w.e.f academic year 21-22) (M5-78)
Tech-Neo Publications...A SACHIN SHAH Ventur Tech-Neo Publications.A SACHIN SHAH Venture
(Java Seript).Page no.(2-14
for the single
parameter
InternetProgramming (MU -Sem 5-IT)
IntemetProgramming
(MU-Sem 5-).
Arrow
Optional
parentheses

Output
Java Scriot.Page no. (2-15)
languages. var num=X=>{
different in
in arrow functions compared
called as
Lambda
Functions
and they
cannot
100 500
as to regular functions. In the
property,
functions do not
include any
prototype
console.log(x): arrow function, there is not
any binding of this. In regular
be used with
the new keyword.
22.7.2 Advantages of Arrow Functions functions, this keyword is used to represent the objects that
function
the arrow called the function, which could either be a window, a button,
Syntax for defining num(140)
1. Tt reduces the code size
?.) =>{ stateent and the : When the syntax of arow
we use
(argl, arg2, braces for single empty or a document or anything.
constfunctionName Optional
not any parameter
required. function, the size of the code gets reduced. We can write less
I/body of the
function
braces if there is But with arrow functions, tiís keyword always represents thbe
amount of code by using the arrOw function.
console.log("Hello World");
Lambda arshow
=
(0=> object that defines the arrow function.
Arrow
Funchon or
2. Return statement and
Functional braces are optional for
parts to
an
here are
three
show(; single line functions: In ESS, we need to define the return Example Modnle
Function have the
Function with Parameters statement in the functions, but in ES6, do not Consider a class having an aray of numbers, and if the
ParameterS: Any
function may
optonally
a 2.7.1 Arrow we
require to

define the return statement for


single-line functions. number is less than 30, then we will push them into the child
paramete for the to pass more than one parameter by usin an Functional
it is the
notation
If you require braces are also optional for the single-line
notation/lambda
notation:
them within the parenthesie queuc
Fat arow
arow function, then you
have to pass
esis functions.
arrow (
function.
instruction set of the
Example For example
Statements: It represents
the
In ES5, it can be done as follows
=> {
Example varshow= (a,b,c) In ES5
this.num.forEachfinctiontnium)
console.logla +" " ++b+ ""-+c)
/ fanction expression fünction show(value) 30
return value/2;
show(100,200,300); thia.childpushma)
function show) {
var myfunl
=

Arow function with default parameters Hbindthis),


console.log("t is a Function Expression); In ES6, the function allows the initialization of parameters In ES6, it can be done by usingthearroFunetion
with default values, if there is no value passed to it, or it is Mar showvaue value 2, this.numforkach(um)
Anonymous function undefined. consolelog(show100)5- ifmm 30
Example f you are not applying curly braces on the single statement,
thischild.pushénum
varmyfun2=function 0{ var show= (a, b200) 1 then you.do not require to use return, but if you are using curly

braces even on the single statement, then you must have to use the
console.log(A is an Anonymous Function ) console.log(at b); By i Sing anrow funchon, we do noE TEqure to bind it
return keyword."
implticitly because it performs automaticaly by the arrow function

show(100); Without Retum Keywor The arow function makes the writig of function less complicated,
#Arrow funetion
In the above function, the value of b is set to 200 by default var show value and it also reduces the number of ines
The function will always consider 200 as the value ofb if no value
var mytun30> value/2, 2.8 ES6 HTML DOM
of b is explicitly passed.
console.log(t is an Arrow Function");
Output Every web page resides inside a browser window, which can
Console.logshow(50)) be considered as an object
100200
The default valueof the parameter 'b' will get overwiten
With Réum Keyword A document object represents the HTML document that is

myfuni0; the function passes its value explicitly. You can see it in
yarshow value displayed in that window. The document object has various
the properties that refer to other objects which allow access to and
myfun20; following example: return
value/2:
modiñcation of the docameat content. The way. a docament
ayfun30; Example contentis accessed and modified is called the Document Object
Syntactic Variations var show (4,b=200) console.log(ehow(50)% Model, or DOM: The objects are organized in a hierarchy. This
There are some syntactic variations for the arow functions console.log(a +"+b); 3. Lexically bind the content Arow function binds the hierarchical structure
applies to the organizaton of objects in a
that are as follows: web document .
context lexically or statically. Thehandling of this is diferent

show(100,500);
(New Syllabus w.e.f academic year 21-22) (MS-78) (New Syllabus w.e.f academic year 21-22) (M5-78) El Tech-Neo Publications..A SACHIN SHAH Venture
TecTech-Neo Publications...A SACHIN SHAH Venture
(JavaScript)..Page no. (2-16
can be used set and
get
InternetProgramming (MU -Sem 5-IT)
internetProgramming (MU-Sem 5-1
model
which
the
provided by this

Sr. No. Java Script...Page no. (2:1)


Hierarchy of a few important objects
document property valucs.
Property &Descriptionm Sr: No.
Vindow the
document
perties
properties which
whic
can be 8. fgColor Property &Description
Following is
a list oft was linked.
frame parent self Dp A string that specifies the default text
accessed using Legacy
DOM.

document. color for the Example : document.referrer


Property & Description
1.7 Title
nisiory document locabon Sr. No
|Example: document.fgColor
The text contents of the <title>
anchor
alinkColor
string that specifies the
color of
9.
forms[ tag.
link fom
Deprecated
-A An of
array form objects, one for each ETML form Example: document.title
activated links. that appears in the
document. 18. URL
checkbox
radio textarea Duun ext
Example document.aunkolor Example: document.forms[0], document.forms[1] and A read-only string that specifies the URL of the Module
password reset select
anchors[ ]
so on
document 2
10. images[ ]
An aray of anchor objects,
one ror each anchor that Example: document. URL
An aray of form
opton document. objects, one for each HTML form
appears in the that appears in the document with the
vinkColor
HTML <imgp
(1832Fig.2.8.1: HTML DOOM Example: document.anchors|j, document.anchors[1] Deprecated - A string that specifies the color of the

and so on
tag visited links.
2.8.1 Types of DOM Example: document.forms[0], document.forms[1] and
3.
applets[1
so on Example: document. vlinkColor
GQ List outdifferent types of DOM.
*************
(5Marks) An array of applet objects, one for each applet that 1.
lastModified Document Methods in Legacy DOM
appears in he document Following is a list of methods supported by Legacy DOM.
The following sections explain each of these DOMs in detail A read-only string that specifies the date of the most
Exanmple: document.applets[O]. document.applets[1] recent change to the document
and describe how you can use them to access and modity the
Sr.No Property &Dscription
document content. and so on |Example: document. lastModified clear()
The Legacy DOM: This is the model which was introduced bgColor 12. linkColor Deprecated- Erases the contents ofthe document
in early versions of JavaScript language. It is well supported Deprecated-A string that specifies the background and returns nothing-
Deprecated - A string that specifies the color of
by all browsers, but allows access only to certain key
color of the document. unvisited links. Example: document.clear()
portions of documents, such as forms, form elements, and
Example: document.bgColor
images.
Example: document.linkColor close( )

The W3C DOM This document object model allows


5. Cookie 3.
links[
Closes a document stream opened with the open()
access and modification of all document conteat and is |A string valued property with special behavior that It is a document link array.
method and remrns nothing-
| allows the cookies associated with this document to be
standardized by the World Wide Web Consortium (W3C). open()
queried and set. Example: document.links[0], document.links[1] and
'This model is supported by almost all the moden
browsers Example: document.cookie so on
Deletes the existing document content and opens a
The IE4 DOM This document object model was stream to which the new document contents may be
14. Location written. Returns nothing.
introduced Version 4 of Microsofe's Intermet Explorer
in 6.
Domain
browser. IE 5 and later versions include support for most The URL of the document. Deprecated in favor of the Example: document.open( )
A string that specifies the Internet domain the
basic W3C DOM features. document is from. Used for security purposes. URL property. write( valoe,)
The Legacy DOM Example: document.location Inserts the specified string or strings into the
Example: document.domain
This is the model which 15. document currently being parsed or appends to the
was introcduced in the early versions embeds[ ] plugins[ documentopened with open( ). Returns nothing.
of JavaScript language. It is well
supported by all browsers, but An of
|A synonym for the èmbeds[]
arrayobjects that represent data embedded in, Example: document.write( value, ..)
allows access only to certain key portions of the
as forms, form elements, and images.
documents, such the document with the <embed> tag. A synonym ror Example: document.plugins[0). document.plugias[1] . writen( value, )
and so on
This model provides
plugins . Some plugins and ActiveX controls can be Identical to write(), except that it appends a newline
several read-only
properties, such as controlled with JavaScript code. 16. Referrer
character to the output. Retums nothing
title, URL, and lastModified provide information
about the Example: document.embeds[0], document.embeosl A read-only string that contains the URL of the Example: document.writeln( value, ..)
document as a whole. Apart from that, there are and so on
various methods |document,ifany,from which thecurrent document
(New Syllabus w.e.f academic year 21-22) (New Syllabus w.e.f academic year 21-22) (M5-78) Tech-Neo Publications..A SACHIN SHAH Venture
(M5-78)
ech-Neo
Publications..A SACHIN SHAH Ventu
(Java Script).Fage no. 18)
InternetProgramming (MU Sem 5-I)
internet Programming (MU-Sem5
dava Scie).. Pageno.(2-199
HIML
within any "SecondForm">
Example
HTML element name
=
locate any Kform
we can
a web
document
= "Don't ClickMe"/> class.
For instance, if "button"
value
Class Expression We can also say thatabove constructor initializes two
the
HTML DOM.
dOcument using
we can
reter to l
as input type
using JavaScript, var Student class variables'n and 'a' along with the parameter values passed to the
cOntains a form element, then two form </form>
includes
Web document COnstructor.
document.forms[0].
If your
document. forms[Uj
and tne
</body> constructor(name, age)
first form is referred to as
The function stu() in the class will print the values of name
elements, the this.name name;
second as document.forms[l. </html> and age.
given above, we can
INHERITANCE this.age age
Using the hierarchy and properties
document.forms[0].elements|0
2.9 CLASSES AND 2.9.2 Class inberttance
access the first form element using
and so on.
2.9.1 ES6 Classes Inheritance is the ability to create new enuties trom a"
Modale
Instantiating an Object from clas8
Example existing one. The class that is extended for creating newer classes
using
document properties class in ES6? Like other object-oriented
Following is an example
to accesSs
GQ. How to
create a
programming languages, we cans referred to as superclass/parent class, while the newly created
instantiate an object trom class by using the new
- - - - * * * * * * *

Legacy DOM method. keyword.classes are called subclass/child class.


Classes are an essential part of object-onented programmine
<html> Classes are used to define the blueprint for real-world Syntax A class can be inherited from another class by using the
(OOP).
reusable and logical
<head>
object modeling and organize the code
into var obj_name= new class_name([arguements]) 'extends keyword Except for 1 constructors from the parent

Stitde> Document Title </title>


parts. Befoe ES6,
it was hard to create
a class in JavaScript. But in Example class, child class inherits all properties and methods.
the class keyword. We can
ES6, we can create the class by using var stu = new Student("Sai', 22) Sytax
include classes in our code either by class expression or by using a
s o r i p t type = "text/javascript">
Accessing functions class childclass_name extends
class declaration. parent classDame{
A class definition can only include constrictors and The object can access the attributes and functions of a class.
function myFunc) { We use the ' dot notation (or period) for accessing the data
functions. These components are together called as the data A class inberits from the other class by using the extends
var ret document.title; members of the class.
members of a class. The classes contain constructors that allocates keyword.
alert("Document Title: "+ ret }; the memory to the objects of a class. Classes contain functions that
var ret = document. UR;
Syntax
Example
are responsible for performing the actions to the objects. obj.function_name(O: h strict
se
aler(Document URL: "+ ret } Syntax Example elass Student
var ret = document.forms{0};
Class Expression usestrict constructofa) {
alert("Document First Fom:"+ ret }
var var namenew classname
ar ret document.forms[0].elements[l]; classStudent this.name a
alert("Second element: "+ ret }; constructorename age)
Syntax
this.nnam
Class Declaration
class User extends Student
/script> elass Class namet
show)
head Console.logthe name df the Student is:+this.natme
Example
Console.log he Name of the studentis:this.n
body Class Declaration
hlidtitle"> This is rmain title</h1> Console.log(The Age of the student is: this. a)
class Student var ob new UsertSahil
p>Click the following to see the result: </p>
constructor{name, age obsbow0
this.name = name;
In the above example, we bave declared a class student. By
tom name irstform this.age ages Var studbnew Student(Peter,20),
that
input type button" value = "Click Me" onclick using the extends keyword, we can create a new class User
stObj.atu( shares the same characteristics' as its parent class Student. So, we
royFune0:"/ n the above example, we have declared a class
Student. The
can see that here is an inherntance relationship between these
input type"button value= "Cancel"> contains two arguments name and age
COnstructor of the class classes.
form respectively. The keyword 'this'
refers to the curment instance ofthe

(New Syllabus w.e.f academic year 21-22) (M5-78)


(New Syllabus we.f academic year 21-22) (M5-78)
Tech-Neo PublicationsA SACHIN SHAH Venture
Tech-Neo Publications...A SACHIN SHAH Venture
(JavaScrip).Pageno.(2-201 InternetProgramming (MU- Bem 5-
intsrnetPrograrnming (MU-8em5 xnmpe feheck iterable using for,
T y p e s of Inherltance class Animal{ fordlet m of marka){ Java Scágt)...Page no. (2-21)
Jnheritaice can be alegoried as Snple level nlierlance,

ea() eomole.log(m) coratruetorfeniome)t


Mulupic inheritancc,
and Multi level
inheritance. Muluple
consoe.log("rating...")
adding esatomer objects to an aray
inheritance is not supported in ES6 his cualomers.comcatlcustomers
Single-level Inheritance
</script
The output ol the adove code
i s defined us the inheritsnce itn which a
derived
class Can
claws Dog extends Animal{
ill be as
gjven below: implement fterator funetion
6niy be interited from only o n e base class. It alBows a den ved clasw

hark (
10
Symbol.itertorj0f
1g inherit the behaviour and properties of a base class, which

new fealures comsole.log("barking...");


20 letonant-0
adding he 30
enAblCs the reusability of code as well as
let customersthís.eustonners
lo the existing code. It makes the codc less rcpetitve
Example retum f Module
Class A
The following cxample declares an next:funetionot
class BabyDog extends Dog{ iterator object. array, marks and
rctrieves an Ihe
Iretrievinga eustomer object from the array
retrieve an 1teratorobjeeL. 1he
symbol.iterator|0 can be used
next) method
to
weep() with 'value and
of the iterator r lef eostomerValeustonersfcount
console.log( weeping..)
an object 'done'
properties. 'done' is Boc
Class B returns true after reading all items in the collection. count1
fcount eustomers.lengih}1
Single Inheritance
script Tettun
(18)Fig. 2.9.1: Single inheritance
var d=new BabyDog();
letmarke (10,20,30] yalte.customerVal,
Multiple Inheritance letitermarke[Symbol.iterator)0 done:false
In multiple inheritance, a class can be inherited from several
d.eat0 console.log(iter.next0)
classes. It is not supported in ES6.
d.bark0 console.logiter.next)
d.weep console.logliter.next0) Teturn true if all ustonmer obiects are iterated
Class A ClassB console.log(iter.nexto)
2.10.ES6 ITERATOR retum tdone:true
S/script
- The output of the above code will be as shown below-
Class C
GQ. Explain ES6Iterator.
********
vaue: 10,done: false
Introduction to Iterator value: 20, done false
Mutiple Inheritance
Tterator is an object which allows us to access a collection of value: 30, done: false icreatecustomerobjects
aB4Fig. 2.92 : Multiple inberitance objects one at a time.
ivaluet undefined,done:uruel letelt
Multi-level Inheritance Thefollowing built-in types are by default iterable Custom Iterable firsiNameSachins
In Muli-level inheritance, a derived class is created from astNameTeuduikar
String Certain types in JavaScript are iterable (Eg. Aay. Map etc)
another derived class. hus, a muiti-level inheritance has more than
Aray while others are not (E.g. Class). JavaScript types which are not
one parent class.

Map
iterable by default can be iterated by using the iterable proiocol. let c2
ClassA The following example defines a class named CustomerList istName: Rahul
Set

An
which stores multiple customer objects as an aay. EachcustomerlastName Dravid
object
is considered iterable, if the
object implements object has firstName and lastName properties.
function whose key is [Symbol.iterator] and returms an iterator. A
Class B To make this class iterable, the class must implement
for..of loop can be used to iterate a collection. ldefine a eustomer arrayand inihalize
(Symbol.iteator10 function. This function returms an iterator
ODject. "The iterator object has a function next which returns an
customers ct,ca
ample
object {value:customer,done:true/false). pass customers tothe dass constructor
Class C The
following example declares an array, marks, and iterau let customersObinew Customerlistfcustomers
through it by using a for.of loop. seript
Multiple Inheritance teraling using for. af
script userdefinediterable forflet c of customersObj)
(185) Fig. 2.93: Moltilevel inheritance
classCustomerlist
let marks [10,20,30]
(New Syllabus w.e.f academic year 21-22) (New Syllabus w.e.f academic year 21-22) (M5-78) al Tech-Neo Publications.ASACHIN SHAH Veniture
(M5-78)
Tech-Neo Publications..A SACHIN SHAH
V jre
Java Scnpt)Page no (2 Internet Programming(MU Sem 5
We are ou some of
showing you
syntRx. the The yield statement
suspends the function (Java Scrip)....Page no. (2-23))
intemet Programming (MU -Sem 5-I
following
In the
defining
the
generator
function:

cends a value back to the caller. It retains


enough state to enable
execution and tample
console.los(c) vaid ways of Valid function to resume where 1t is left off. When it
mygenfun) / gets resume the UBe sic
hunction function continues the execution
immediately after the last
Iiterating using the next() rnethod run. It can produce a sequence of values. yield netionowels0
let iter = customers0bjiSymbol.iteralorj0: yield 1: next) method here 1he asterisk marks this s aenerator
console.log(iter.next() yield 2 yield A
In the above example, we have used the next)
console.log(iter.next0) shich is the main method of the
yield E
method,
generator. When you call the
console.logfiter.next()
next) method along ith argument, it will resume the execution
an
vield T
</script>
of the generator function, replacing the yielded yieldC Module
The
of the above code
oatput
will be as follows
/ Valid expression whereyield U:
function mygenfun) the execution was paused with the argument from the next)
{firstName: "Sachin", lastName: "Tendulkar method.
{firstName: "Rahul", lastName: "Dravid"} forlet alpha of vowel-0)
yield 1; The result of the next) method is
always an
object having console.logfalpha
yield 2; two properties:
done: false
value: It is the yielded value.
value: Output
***
done: It is a Boolean value which gives true
firstName: "Sachin", if the function
code has finished. Otherwise, it gives false.
lastName: "Tendulkar"
functionmygenfun) // Valid Example
functionshow0
yield 1; yield 100,
done: false
yield 2;
value: ** var gen show)here gen is a generator object 2.12ES6PROMISES
firstName: "Rahul", console.logteen.next0%:A value;100,done:falsel
lastName: "Dravid" GQ Explain Promises in Esa
Output *********
0 Mars)
Example valuer 100,done:false Promises are a way to mplemet. asyme programming m
function gen) Generator object
JavaScriptqES6). A Promise wil become a container for future
done: true
The generator functions return geneator objects. A generator value. Like if you order any food on any site to deliver it to your
yield 100;
object is an instance of the generator function, and it conforms to place that order record will be the promise and the food wil be the
2.11 ES6 GENERATORS yield;
both the iterable and iterator interfaces. value of that promise. So the order details are the container of the
: | yield 200;
understand by ES6 Generator function? used either by caling the next0ood you ortered
Ler's explain it with another example. You order
GQWhat do you The generator objects can be
an awesome camera online. Afer your order is placed you receive
(10Marks)| / Calling the Generator Function method or by using the generator object within a loop. The
********~*** ~~~~*~~~- var receipt ot the order. eceipt is a Promise that your order will
That
ES6 generator 15 a different kind of function that may be mygen gen =
Eenerator object is an iterator; that's why you can use it in for...ofa
be delivered to you. The receipt is a placehokder for the future
paused in the middle either onc or many times and can be resumed
later. When the standard function is called, the control rests with
console.log(mygen.next.value);
console.log(mygen.nexn).value);
loops or in other functions accepting an iterable.
value namely the camera
In the above next) method example, the variable gen is the
thecalled function until it returns, but the generator in ES6 allows console.logímygen.next(),value); Promises used in JavaScript for asynchronous programming
the caller function to control the exceution of a called function. generator object.
Output For asynchronoas programming. JavaScript used callbacks but
Syntax Generator function with for...of looP
100 there is a problem using the callback, which is callback hell or
The syntax of the generalor Juncuon
s alnOst J0cnua undefined
Using for.of loop with generator function reduces the line Pyramid of Doom. Using the ES6 Promise willsimply avoid all the
regular funetion. The only real difference is that the generator
in the Iolowing
function is denoted by sufiixing the functión
keyword with an 200 of code. You can see the illustration for the same
problems associated withthecallback
Asernsk (*). The yield statement example.

(New Syllabus w.ef academic year 21-22) (M5-78) (New Syllabus w.e.facademic year 21-22) (M5-78) lTech-Neo Publications.A SACHIN SHAHVenture
Tech-Neo Publications.A SACHIN
SHA
(JavaScnp).Page no. (2-2a
some
tinmes )); Internet Programming (MU- Sem 5-IT
failed

internet Programming (MU -Sem 5 - . reject(new


Errorf'l eonat Fulfilecd m (fulfilledValue)
(Java Script)..Page no. (2-25)
2.12.1 Need of Promises eoneole.log(ulfilled'Value)j leoript
Promises
Callbacks to econet Rejected (error)
Bur
Callbacks are great when dcalingbasic cases.
with
2.12.3 console.log(error) head
lot of
ne

web
application whee you
have a

cases. cvery two types


of
calthacks
which are used for I
handling myPromise.then(Fulfilled, Rejected) body
In conplex 7here ar
handling pom
code. Callbacks can

adds a level of
be great
nesting
trouble.

which can make your code


naly
promises
then() and .catch().
It can be used
for

(promise
pHeppy codinglp
llback
callbacksP 1s KCpo)
or ejcetion i
/body
CSSy
and had
to understand. This excessive nesting of in case of fulfilent (pomise
myPromiae.then((fulhilledValue)= html
is often termed as Callback Hell.
bmken).
a promise
1s kept or broken. It can.h conaole.log(ulfitledValue) Requests and Responses
Example : Invokod when h.eatch(er m> console,log(em)
.then():
rejection of a promise. It talbe.
takes When you
Callback Hell handle the
fulfilment or ype a URL into the address bar of your web uoanle
chained to
1s invoked if the DTOWSeT, your web browser sends a
functions as parameters.
Ine st one

2.13 CLIENT SERVER COMMUNICATION request to that URL, and the 2


f function(x) in fwo
the second onc(opnonal)
is invoked if the SeTVer sends back a
response that contains the content at that URRL.
fulfilled and
2(x, function(y}{ promise is
Servers
B(y, function(z}{ pomise is rejected. Cllents
A server is a that
A client is whatever
computer responds to reqests by serving
***
Exampe you' Te using to interact with the internet. ouses.
using .then)
Handling Promise rejection It's the web browser you're using to read this page. The web At a high level, there are two
Promise(function(resolve, reject) types of content:
='new browser on your computer is one
client, the web br
varpromise Static comtent that doesn't change much. The tutorials at
resolve(Hello, I am a Promise!'); your phone is another client.
HappyCoding.io are an example of this type of content.
Promises instcad or
1o deal With ths probiem, we use
One major job of to
when yoa view them, you see the same thing as everybody
callbacks.
clents, is
parse HTML content and
else, and they don't change much over time. Other types of
display it to the user. files ike mages are ofkn stauC as e l .
2.12.2 Making Promises promise.thenffunction(prómise kept_message)
For example, let's say we have this HTML:
yuamic content that changes over time, or basedi on who's
console.log{promise _kept message)
GQWhat are the states of promises in ES6? (5 Mars),| <IDOCTYRE html iewing the page. For example, the content of
- -- -*-***-* }, funetionferor) <htm> stackovertlow.com changes eveTy ime somebody posts a
A Promise is basically created when we are unsure o

head question. Your Twitter feed is anique to you, based on who


whether or not the assigned task will be completed. The Promise /This function is invoked this time you follow and what they ve posted.
Object represents the eventual compleion (or failure) of an
H as the Promise is rejected
<itle My First Webpage /itle
Server-Slde Rendering
async(asynchronous) operation and its resulting value. As the name /head
console.log(error); }) Server-side rendering means that the HlMML is generated on
suggests a Promise is either kept or broken.
.catch) can be used for handling the errors(if any). It takes
<body tbe server. f's still displayed by the browser on the cient
A Promise is always in one ofthe following states
only one function as a parameter which is used to handle the errors shl>Happy Coding hl> Let's say we want to build a webpage that show the current
fulfilled: Action related to the promise succceded.
f any). pHello worldi /p Unix time (the nunber of
seconds since midnight on January
rejected: Action reiatedtothe promise failed
Example
/body 1, 1970). When the chieat requests the URL of our page, we
pending: Promise is still pending ie not fulfiled or rejected </hlm wk can use the
System.curentTime Milis0
function to calculate
yet. Hangling Promise rejection(or ermors) using catcho Web browsers can also run JavaScript code. This is cient the carrent Unix ime, which we can format into HTML and
settled: Promise has fulfilled or rejected. coRstmyPromise new Promise(resolve,reject side code that runs on your computer
send as a response

Syntax if (Math.random) > 0) { For example, let's say. we have this HTML which inchudes ampon javaiolOBxception
some JavaScript code:
const promise = new Promise((resolve,reject) =>{...});
console.logtresolving the promise ; mport javaxservlet.annotation. WebServlet
Example
resolve(Hello, Positive :)) <IDOCTYPE htmla lmportjavas.eerelet.htp.HtupServlet
const myPromisenew Promise(resolve, reject) =>{ Shtml impert java.aervlet.htp.HltpservletRed
Math.random0>0) rejectinew Eror(No plsce for Negative here 0) shead mport javak.serlet.hrp Hlupservletkes
resolve(Hello, I am positive number!); title Happy Coding/itle
script @wabServlet timel
alert(hellol" extends HtpSer
(New Syllabus w.e.f academic year 21-22) (M5-78)
Tech-Neo Publications...A SACHIN SHAH enture (New syllabus wef academic year21-22)(M5-78) Tech-Neo Publications.ASACHINSHAH Venture
(Java Scrip)..age no. (2-26)
uscrs probably
intemetProgramming W- Sem 5-T
won't
mos1 .
Ad
siower,

eret Programming (tKU . Sem 5


page
couid make
our
@Override
of the
twects anyway. Java ScrePege no.(2-27)
publie void dolGet(HtpaervletReque reue
most
even sce
calied AAX comes in he.
nandy. eond esuontain
verride Tis
ishere a technology

saying
that we can use JavaScript. HupServietResponse responee) throwm 10Excepio tElenentByld rest
poblic void
doetsHnpServienResgoes

Htpaerviethesponse respomse)
regquest

thws 1OExoeption
AJAX

request
is a

content
fancy way of

from a
server.
With AJAX,
With AJAx, the rrequest
e q u e s fow

1000;
aixTimeSecondsSystem.eumenlimeMlie taiter.innerTetT
SystemcurTenfIime Milis(f looks iike this
sehkime# eguest deta fron the serve
sixlimeSecnis=

Smg URL into the


address bar
oftheir web nresponse ponsetea)cevet tbe
JO00;
The user types a

response.setontentlypeftex/html ponse to raw tet


browser.
to a server.
response-getWiter)-printlnfuni TimeSecoods denlfniTime f
web browser
sends a request
The
respense.setContentTypel"text/hnl;";

# boild the HTMLof the


Unix Time </h1>: iniual content. page Module
<h]> The server responds wth some
responsegeWriter),printhnf
Unix time: resultCotainer.imnerlext aniline
<p>Current is sually mostly
static, 1or example the This is pretty mcn exacuy the same
Tepone-ge Wriier).prittnf This content code as we saw
unixTimeSecmds+ </p>"*
navigation bar at the top. It also includes some JavaScript server-side rendernng 1he only difiference is dhat insteadwih
of
response-gaWriteri)-prinilof' <p>(<a
for building the dynamic parts
of the page. outputting HTML Content, this code responds with
code responsible
value: the current Unix time.
a single |scrpt
href=">Refresh <ja>)</p>% makes another request for more
code
That JavaScript
We can even visit t in
<Ahead
a web browser, exactly like any other
content

URL <body onloed-"requestUniTimel"


hke any other request
whe the client requests the time.htmi URL
That request goes to the serve EXacTIy
<hi>Unis Time<hl>
In above code, responds with the requested content. This lecalhosteDe0/ tine
would. The server
responds w+th HTML contem
that
in many
PCrent Unis time Cspan id"resni <lspan <p
from cur server, the
*Tve
content, and can come
is usually the dynamic C O locahostetn/time
11 generated using Java code, rather than HTML tha
came

different formats: HTML, XML, JSON, plain text, etc. Sp>(Shref=>Refreabcla>)<lp


from a html f+e. The chent doesD t care
(or even know) how

That response comes back to the JavaScript code, and the 1557025630 Cbody
the HTML was generated. It renders the
HTML no matter
build out the rest of the
<html
JavaScript code parses the content to
where it came from. This file cotains static HIML and JavaScript. When a user
UI using JavaScript functions. (196Fig. 2.131 navigates to the aserbbml URE, the cient sends a requests
Unix Time The user sees the initial content first, maybe a loading bar This isn't a veryinteresting webpage, but that's because it's and the server sends this content back as the esponse. he
while the dynamic content is requested, and then the dynamic not meant for humans to see. It exists so JavaScript can chicnt then displays the page and cals the
request it and then use the response to build the HTML of the requesziinis Time
Cumet Cnix time: 1557014658 content is populated. function

Let's look at our Unix time example again, this time using page The requestUnixtime0 function uses the Fetch APt to send a
Now we know how to create a server-side endpoint that
The @WebServlet annotation tells our server which URL the client-side rendering approach. request to the time URL. Like we saw above, the server
handles a request for a URL, runs some Java code, and
this code should run for. In this example we used /time.html, Server Endpoints handies this BRL by retrning a response that contains the
returns some data in the response.
but we could have chosen anything. URLs like time without arent Unix time. The JavaScript code uses this response to
First, we have to create an
endpoint (which is a fancy wod The other half of this is the JavaScript code that requests the
file extension URLS ike baikd the UL, in this cae by showing the curent Unix time in
a or even
fume/ witn wiuOcaras
for a URL that responds with data) on our server. In our example, data from the server and uses it to build the HTML of the
work fine! page
this endpoint needs to retun the curent Unix time.
page The fetchO method in JavaSeripe is used to request to the
Client-Side Rendering
import java.io.1OException cent.html andi load the information
Server-side rendering allows build
server in the webpages. The request
dynammc webpages,
us to

but it also requires that we output the whole page at one time.
inuport javax.aervlet.annotation WebServlets <IDOCTYPE html an be of any APls that retums the data of the format ISON

import javax.serviet.hitp.HtupServlet, shtml> or XML. This method reums a promise


For our small example this might not be a big deal, but think
about complicated page
import javax.servlet.http.HttpservletRequest <head
wanted
a more

to load more tweets when


ike Twitter.
the user
what if
scTolled to the
we
mT
import javax.servlet.http.HttpServletResponse Smetacharset"UTF-8" Unix Time
bottom of their feed?
Stitle>Unix Time /title
Cument Unix time: 15S7014658
If we relied on server-side rendering, we'd have to include a
@WebServlet(time") Sscript
ton of tweets in the HTML public class Unix limeServlet
we send back to the client. This extends Httpservlet lunction requestUnixTime)
(New Syllabus w.ef academic year 21-22) (M5-78)
Tech-Neo Publications...A SACHIN SHAH enture (New Syllabus w.ef academic year 21-22) (MS-78) Tech-Neo PublicationsA SACHIN SHAHVenture
V
(Java Seript).Page no. (2-28) nternet Programming (MU Sem 6-IT
method

Internet Programming (MU -Sem 5- Wi byusing


then) method: "POST
Java Scrip)...Page no.(2-29)
2.14 FETCH
fetchRes.then(res
esjson0).thend -> {
headers fetehRes.then(res
Content-Type' resjeon().thernd=
GQ Explain fetch method with help ofexampie
the
5 Mariks)
console.log(d)
'applieationjaon;ehareet utf-8 cosole.log(d)

JavaScript is used to request to the


/script body: JSON.stringify(user script
fetch) method in
server
The

and load the information in the webpages. The request can


</body> <bodys
be of any APls that returns the data of the format
JSON or XML.

</html Fake api for making post requests S/htmls


Fetch
Request using
This method returns a promise.
Bxample 2
* * * *
: Making Post
letfetchRes Mod
Syntax make Post Request using
fetch method fetch "http://dummy.restapiexámple.com/api/vl/create
GQ How to
fetch( url, options) 6 Marks) options);

Parameters Chapter Ends..


above and can be made using
fetch by giving optionsas
This method accept two parameters as mentioned Post requests
described belowr given below:

is to be made. i
URL: It is the URL to which the request let options ={
Opttons : It is an aray of fProperties. lt is an optional method: POST,
parameter. headers: {
Returm Value: It returns a promises whether it is resolved or Content-Type': 'application/json;charsetutf-8
be of the forrmat JSON or XML.
not. The retun data can

I t can be the array of objects or simply a single object.


body: JSON.stringify(data)
Fetch
Example 1: Making Get Request using
r*- -****** ******
method.
GO How to make Get Request using fetch Example
5 Marks) i| <DOCTYPE html>
Without options Fetch will always act as a get requesL
html lang="en">

<IDOCTYPE html> <head


meta charset="UTF-8">
html lang="en">
meta name="viewport content
<head>
meta charset="UTF-8">
"width-device-width, initial-soale 1.0"
meta name"viewport" content=
"width=device-width, initial-scale=1.0"> <title> JavaScript fetch0 Method /uitle:
<title> JavaScript | fetch0 Method </titde > /head
</head> cbody>
<body> script
Script> user
name: "Geeks for Geeks,

API for get reguests "age": "23"


let fetchRes = fetch(

"https://jsonplaceholder.typicode.com/todos/1"}; Options to be given asparameter infetch for makins


requests other then CET
/ fetchRes is the promise to resolve let options{
(New Syllabus w.e.f academic year 21-22) (M5-78)
Tech-Neo Publications...A SACHIN SHAH ture

You might also like