INP MOD2 JavaScript
INP MOD2 JavaScript
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-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-15 *****
2.7.1 Arrow Function
*******
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
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
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:
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
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.
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
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
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
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
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
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
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
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( )
hark (
10
Symbol.itertorj0f
1g inherit the behaviour and properties of a base class, which
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:
(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
web
application whee you
have a
adds a level of
be great
nesting
trouble.
(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
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,
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=
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
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