0% found this document useful (0 votes)
14 views

Java Scripttoday

Java screen guard

Uploaded by

josephzekeri407
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Scripttoday

Java screen guard

Uploaded by

josephzekeri407
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

1.

I
ntr
oduct
iont
oJav
aScr
ipt

Jav
aScr
ipti
soneoft
hemostpopul
arpr
ogr
ammi
ngl
anguagesi
nthewor
ld.

Ibel
iev
eit
’sagr
eatl
anguaget
obey
ourf
ir
stpr
ogr
ammi
ngl
anguageev
er.

Wemai
nlyuseJav
aScr
iptt
ocr
eat
e

websi
tes

webappl
icat
ions

server-
sideappl
icat
ionsusi
ngNode.jsbutJavaScr
ipti
snotli
mit
edtothesethi
ngs,anditcanal
sobeusedto
createmobileappli
cati
onsusi
ngtoolsl
ikeReactNativ
ecreat
eprogr
amsf ormicr
ocontr
oller
sandt
heint
ernetof
thingscreat
esmar t
watchappl
icat
ions

Itcanbasical
lydoanyt
hing.I
t’
ssopopul
art
hatev
ery
thi
ngnewt
hatshowsupi
sgoi
ngt
ohav
esomeki
ndof
JavaScri
ptint
egrat
ionatsomepoint
.

Jav
aScr
ipti
sapr
ogr
ammi
ngl
anguaget
hati
s:

hi
ghlevel
:itpr
ov i
desabstractionst
hatal
lowy outoignorethedetai
lsoft
hemachinewher eit’
srunni
ngon.I
t
managesmemor yautomat i
callywi
thagarbagecoll
ector,soyoucanfocusonthecodeinsteadofmanaging
memoryli
keot herlanguagesl i
keCwouldneed,andpr ov
idesmanyconst r
uct
swhichall
owy outodealwi
thhighl
y
powerf
ulvari
ablesandobj ects.

dynamic:asopposedt ostati
cprogramminglanguages, ady
nami clanguageexecutesatrunti
memanyoft he
thi
ngsthatastaticlanguagedoesatcompiletime.Thishaspr osandcons, andi
tgivesuspower fulf
eat
uresli
ke
dynamictypi
ng,latebindi
ng,ref
lect
ion,
functi
onalprogramming, obj
ectrunti
mealterati
on,cl
osuresandmuchmor e.
Don’tworryi
fthoset hi
ngsareunknownt oyou-you’llknowallofthoseattheendoft hecourse.

dynami
cal
lyt
yped:avar
iabl
edoesnotenfor
ceatype.Youcanr
eassi
gnanyt
ypet
oav
ari
abl
e,f
orexampl
e,
assi
gni
nganint
egert
oav ari
abl
ethathol
dsastr
ing.

l
ooselyty
ped:asopposedtostrongty
ping,l
oosely(
orweakly
)typedl
anguagesdonotenf
orcet
hetypeofan
obj
ect,al
lowingmoref
lexi
bil
it
ybutdenyingustypesaf
etyandty
pechecking(somet
hingt
hatTy
peScri
pt-whi
ch
bui
ldsont opofJav
aScri
pt-provi
des)

i
nt erpret
ed:i
t’
scommonl yknownasani nt
erpr
etedlanguage,
whichmeanst hatitdoesnotneedacompilat
ion
stagebef or
eapr ogr
am canrun,asopposedtoC,JavaorGof orexample.I
npr act
ice,
browsersdocompil
e
Jav aScri
ptbefor
eexecuti
ngit,
forperf
ormancereasons,butt
hisistr
ansparenttoyou:ther
eisnoaddi
ti
onalstep
i
nv olved.

multi
-par
adigm:t
helanguagedoesnotenf or
ceanyparti
cularprogrammi ngpar adi
gm, unl
ikeJavaf orexample,
whichforcest
heuseofobject-
ori
entedprogramming,orCwhi chforcesimper ati
veprogrammi ng.Youcanwr it
e
JavaScri
ptusi
nganobject-
ori
entedparadi
gm, usi
ngprototypesandt henew( asofES6)cl assessyntax.Youcan
writ
eJavaScri
pti
naf unct
ionalpr
ogrammi ngstyl
e,wi
thitsfir
st-
classfuncti
ons, orev
eni nanimper ati
vesty
le(C-
l
ike).

I
ncasey
ou’
rewonder
ing,
Jav
aScr
ipthasnot
hingt
odowi
thJav
a,i
t’
sapoornamechoi
cebutwehav
etol
iv
ewi
thi
t.
2.Al
it
tl
ebi
tofhi
stor
y

Cr
eat
edi
n1995,
Jav
aScr
ipthasgoneav
eryl
ongwaysi
ncei
tshumbl
ebegi
nni
ngs.

Itwast
hefir
stscri
ptingl
anguagethatwassupport
ednativ
elybywebbr owser
s,andthankst
ot hi
sitgai
neda
compet
iti
veadvantageoveranyot
herlanguageandtodayit
’sst
il
ltheonlyscr
ipt
ingl
anguagethatwecanuseto
buil
dWebApplicat
ions.

Otherl
anguagesexi
st,
butal
lmustcompi
let
oJav
aScr
ipt-ormor
erecent
lyt
oWebAssembl
y,butt
hisi
sanot
her
st
ory.

I
nthebegi
nning,
JavaScr
iptwasnotnearl
ypower
fulasi
tist
oday
,andi
twasmai
nlyusedf
orf
ancyani
mat
ionsand
t
hemarvelknownatthet
imeasDy namicHTML.

Wit
hthegrowingneedst
hatt
hewebpl at
for
m demanded(andcont
inuest
odemand),
JavaScr
ipthadthe
r
esponsi
bil
it
ytogrowaswell
,toaccommodatetheneedsofoneofthemostwi
del
yusedecosystemsofthewor
ld.

JavaScr
ipti
snowwidel
yusedal
soout
sideoft
hebrowser
.Theri
seofNode.
jsi
nthelastfewyearsunl
ocked
backenddevel
opment
,oncet
hedomai
nofJava,Ruby
,Pyt
hon,PHPandmoretr
adit
ionalser
ver-
sidel
anguages.

JavaScri
pti
snowal
sothelanguagepoweri
ngdatabasesandmanymor
eappli
cat
ions,andi
t’
sevenpossibl
eto
devel
opembeddedappl
icat
ions,
mobileapps,TVset
sappsandmuchmore.Whatstar
tedasati
nylanguageinsi
de
thebrowseri
snowthemostpopularl
anguageint
hewor l
d.

3.JustJav
aScr
ipt

Somet
imesi
t’
shar
dtosepar
ateJav
aScr
iptf
rom t
hef
eat
uresoft
heenv
ironmenti
tisusedi
n.

Forexample,
theconsole.l
og()l
ineyoucanfindinmanycodeexampl esi
snotJavaScr
ipt
.Inst
ead,i
t’
spar
toft
he
vastl
ibr
aryofAPIsprovi
dedt ousinthebrowser.Inthesameway ,
ontheserv
er,
itcanbesometimeshar
dto
separat
etheJavaScr
iptlanguagefeatur
esfrom theAPIsprov
idedbyNode.
js.

I
sapar
ti
cul
arf
eat
urepr
ovi
dedbyReactorVue?Ori
sit“
plai
nJav
aScr
ipt
”,or“
vani
ll
aJav
aScr
ipt
”asof
tencal
led?

I
nthisbookItal
kaboutJavaScr
ipt
,thelanguage,
withoutcompl
icat
ingy
ourl
ear
ningpr
ocesswi
tht
hingst
hatar
e
out
sideofi
t,andpr
ovidedbyexter
nalecosystems.

4.Abr
iefi
ntr
otot
hesy
ntaxofJav
aScr
ipt

I
nthi
sli
tt
lei
ntr
oduct
ionIwantt
otel
lyouabout5concept
s:

whi
tespace

casesensi
ti
vi
ty

l
it
eral
s

i
dent
if
ier
s

comment
s
4.
1.Whi
tespace

JavaScri
ptdoesnotconsi
derwhi
tespacemeani
ngf
ul.Spacesandl
inebr
eakscanbeaddedi
nanyf
ashi
ony
ou
mightli
ke,event
houghthi
sisint
heory.

I
npract
ice,youwi
llmostli
kel
ykeepawell-
defi
nedst
yleandadher
etowhatpeopl
ecommonl
yuse,
andenf
orcet
his
usi
ngalint
erorastyl
etoolsuchasPr
ett
ier.

Forexampl
e,Il
iket
oal
way
suse2char
act
erst
oindent
.

4.
2.Casesensi
ti
ve

Jav
aScr
ipti
scasesensi
ti
ve.Av
ari
abl
enamedsomet
hingi
sdi
ff
erentf
rom Somet
hing.

Thesamegoesf
oranyi
dent
if
ier
.

4.
3.Li
ter
als

Wedef
ineasli
ter
alavaluethati
swrit
teninthesour
cecode,f
orexampl
e,anumber
,ast
ri
ng,
abool
eanoral
so
mor
eadvancedconst
ructs,
likeObj
ectLi
teral
sorArr
ayLit
eral
s:

'
Test
'

t
rue

[
'
a',
'b'
]

{
col
or:'
red'
,shape:'
Rect
angl
e'
}

4.
4.I
dent
if
ier
s

Anidenti
fi
erisasequenceofcharact
ersthatcanbeusedtoident
if
yav ari
abl
e,af
unction,oranobject
.Itcanst
art
wi
t halet
ter
,thedollarsi
gn$oranunderscore_,andi
tcancontai
ndigi
ts.Usi
ngUnicode,alett
ercanbeany
al
lowedchar,forexample,anemoji .

Test

t
est

TEST

_
test

Test
1

$t
est

Thedol
larsi
gni
scommonl
yusedt
oref
erenceDOM el
ement
s.
Somenamesar
ereser
vedf
orJav
aScr
ipti
nter
naluse,
andwecan’
tuset
hem asi
dent
if
ier
s.

4.
5.Comment
s

Comment sareoneofthemosti mport


antpar
tsofanypr
ogram.I
nanyprogr
ammingl
anguage.Theyar
ei mpor
tant
becausetheyl
etusannotatethecodeandaddimport
anti
nfor
mationt
hatot
her
wisewoul
dnotbeav ai
labl
eto
otherpeopl
e(orour
sel
v es)r
eadingthecode.

I
nJavaScri
pt,
wecanwr i
teacommentonasi
ngl
eli
neusi
ng/
/.Ev
ery
thi
ngaf
ter/
/isnotconsi
der
edascodebyt
he
Jav
aScri
ptint
erpr
eter
.

Li
ket
his:

/
/acomment

t
rue/
/anot
hercomment

Anot
hert
ypeofcommenti
samul
ti
-l
inecomment
.Itst
art
swi
th/
*andendswi
th*
/.

Ev
ery
thi
ngi
nbet
weeni
snotconsi
der
edascode:

/
*someki
nd

of

comment

*
/

5.Semi
col
ons

Ev
eryl
inei
naJav
aScr
iptpr
ogr
am i
sopt
ional
lyt
ermi
nat
edusi
ngsemi
col
ons.

Isai
dopt
ional
l
y,becauset
heJav
aScr
ipti
nter
pret
eri
ssmar
tenought
oint
roducesemi
col
onsf
ory
ou.

I
nmostcases,
youcanomi
tsemi
col
onsal
toget
herf
rom y
ourpr
ogr
ams.

Thi
sfacti
sver
ycont
rov
ersi
al,
andy
ou’
l
lal
way
sfi
ndcodet
hatusessemi
col
onsandcodet
hatdoesnot
.

Myper
sonal
pref
erencei
stoal
way
sav
oidsemi
col
onsunl
essst
ri
ctl
ynecessar
y.
6.Val
ues

Ahel
lost
ri
ngi
sav
alue.Anumberl
ike12i
sav
alue.

hel
loand12ar
eval
ues.st
ri
ngandnumberar
ethet
ypesoft
hosev
alues.

Thetypeisthekindofval
ue,i
tscat
egor
y.Wehav emanydi
ff
erentt
ypesi
nJav
aScr
ipt
,andwe’
l
ltal
kaboutt
hem i
n
det
aill
ateron.Eachtypehasi
tsowncharact
eri
sti
cs.

Whenweneedtohavearef
erencetoav
alue,
weassignitt
oav ari
abl
e.Thevari
abl
ecanhaveaname,
andt
he
val
uei
swhat’
sstor
edinavari
able,
sowecanlat
eraccessthatval
uethr
oughthevari
abl
ename.

7.Var
iabl
es

Av
ari
abl
eisav
alueassi
gnedt
oani
dent
if
ier
,soy
oucanr
efer
enceandusei
tlat
eri
nthepr
ogr
am.

Thi
sisbecauseJav
aScr
ipti
sloosel
yty
ped,
aconcepty
ou’
l
lfr
equent
lyhearabout
.

Av
ari
abl
emustbedecl
aredbef
orey
oucanusei
t.

Wehav
e2mai
nway
stodecl
arev
ari
abl
es.Thef
ir
sti
stouseconst
:

consta=0

Thesecondwayi
stousel
et:

l
eta=0

What
’st
hedi
ff
erence?

constdefi
nesaconst
antr
efer
encet
oav
alue.Thi
smeanst
her
efer
encecannotbechanged.Youcannotr
eassi
gna
newv al
uetoit
.

Usi
ngl
ety
oucanassi
gnanewv
aluet
oit
.

Forexampl
e,y
oucannotdot
his:

consta=0

a=1

Becausey
ou’
l
lgetaner
ror
:Ty
peEr
ror
:Assi
gnmentt
oconst
antv
ari
abl
e..

Ont
heot
herhand,
youcandoi
tusi
ngl
et:
l
eta=0

a=1

constdoesnotmean“constant
”inthewaysomeot herlanguagesli
keCmean.Inpart
icular
,itdoesnotmeanthe
val
uecannotchange-i
tmeansi tcannotber
eassigned.Ift
hev ar
iabl
epoint
stoanobjectoranar r
ay(we’
l
lsee
moreaboutobject
sandarrayslat
er)t
hecontentoftheobjectorthearr
aycanfr
eel
ychange.

Constv
ari
abl
esmustbei
nit
ial
izedatt
hedecl
arat
iont
ime:

consta=0

butl
etv
aluescanbei
nit
ial
izedl
ater
:

l
eta

a=0

Youcandecl
aremul
ti
plev
ari
abl
esatoncei
nthesamest
atement
:

consta=1,

b=2

l
etc=1,

d=2

Buty
oucannotr
edecl
aret
hesamev
ari
abl
emor
ethanonet
ime:

l
eta=1

l
eta=2

ory
ou’
dgeta“
dupl
icat
edecl
arat
ion”er
ror
.

Myadvi
ceistoalwaysuseconstandonl
yuseletwheny ouknowy
ou’
llneedtoreassi
gnav al
uetothatv
ariabl
e.
Why?Becausethel
esspowerourcodehas,t
hebetter
.Ifweknowavaluecannotbereassi
gned,
it’
soneless
sour
ceforbugs.

Nowt
hatwesawhowt
owor
kwi
thconstandl
et,
Iwantt
oment
ionv
ar.

Unti
l2015,varwastheonlywaywecoulddeclar
eav ar
iabl
einJavaScri
pt.Today
, amoderncodebasewil
lmost
l
ikel
yjustuseconstandlet
.Ther
earesomef undamentaldi
ff
erenceswhichIdetai
lint
hispostbuti
fyou’
rej
ust
star
ti
ngout,youmightnotcar
eaboutthem.Justuseconstandlet.

8.Ty
pes

Var
iabl
esi
nJav
aScr
iptdonothav
eanyt
ypeat
tached.
Theyar
eunt
yped.

Oncey
ouassi
gnav al
uewi t
hsomet
ypet
oav
ari
abl
e,y
oucanl
aterr
eassi
gnt
hev
ari
abl
etohostav
alueofany
ot
hert
ype,
wit
houtanyissue.

I
nJav
aScr
iptwehav
e2mai
nki
ndsoft
ypes:
pri
mit
ivet
ypesandobj
ectt
ypes.

8.
1.Pr
imi
ti
vet
ypes

Pr
imi
ti
vet
ypesar
e

number
s

st
ri
ngs

bool
eans

sy
mbol
s

Andt
wospeci
alt
ypes:nul
landundef
ined.

8.
2.Obj
ectt
ypes

Anyval
uethat’
snotofaprimit
ivet
ype(astri
ng,anumber,aboolean,nul
lorundefi
ned)i
sanobject.Obj
ectt
ypes
havepr
opert
iesandalsohavemethodsthatcanactonthosepropert
ies.We’
llt
alkmoreaboutobject
slat
eron.

9.Expr
essi
ons

Anexpr
essi
oni
sasi
ngl
euni
tofJav
aScr
iptcodet
hatt
heJav
aScr
iptengi
necanev
aluat
e,andr
etur
nav
alue.

Expr
essi
onscanv
aryi
ncompl
exi
ty.

West
artf
rom t
hev
erysi
mpl
eones,
cal
ledpr
imar
yexpr
essi
ons:

0.
02

;
('
somet
hing'
)

t
rue

f
alse

t
his/
/thecur
rentscope

undef
ined

i/
/wher
eii
sav
ari
abl
eoraconst
ant

Ari
thmet
icexpr
essi
onsar
eexpr
essi
onst
hatt
akeav
ari
abl
eandanoper
ator(
mor
eonoper
ator
ssoon)
,andr
esul
t
i
ntoanumber:
1/2

i
++

i-
=2

i*2

St
ri
ngexpr
essi
onsar
eexpr
essi
onst
hatr
esul
tint
oast
ri
ng:

'
A'+'
str
ing'

Logi
calexpr
essi
onsmakeuseofl
ogi
caloper
ator
sandr
esol
vet
oabool
eanv
alue:

a&&b

a|
|b

!
a

Mor
eadv
ancedexpr
essi
onsi
nvol
veobj
ect
s,f
unct
ions,
andar
ray
s,andI

lli
ntr
oducet
hem l
ater
.

10.Oper
ator
s

Oper
ator
sal
lowy
out
ogett
wosi
mpl
eexpr
essi
onsandcombi
net
hem t
ofor
m amor
ecompl
exexpr
essi
on.

Wecanclassi
fyoper
ator
sbasedontheoper
andstheywor
kwi
th.Someoper
ator
swor
kwi
th1oper
and.Mostwi
th
2oper
ands.Justoneoper
atorwor
kswit
h3operands.

I
nt hi
sfir
stint
roducti
ontooperat
ors,
we’l
lintr
oducetheoperatorsyouaremostl
ikel
yf amil
iarwi
th:bi
nar
y
operat
ors.Ial
readyint
roducedonewhentalki
ngaboutvari
ables:theassi
gnmentoperator=.Youuse=toassi
gna
val
uetoav ari
able:

l
etb=2

Let
’snowi
ntr
oduceanot
hersetofbi
nar
yoper
ator
sthaty
ouar
eal
readyf
ami
li
arwi
th,
from basi
cmat
h.

10.
1.Theaddi
ti
onoper
ator(
+)

constt
hree=1+2

constf
our=t
hree+1

The+oper
atoral
soser
vesasst
ri
ngconcat
enat
ioni
fyouusest
ri
ngs,
sopayat
tent
ion:
constt
hree=1+2

t
hree+1/
/4

'
thr
ee'
+1/
/thr
ee1

10.
2.Thesubt
ract
ionoper
ator(
-)

constt
wo=4-2

10.
3.Thedi
vi
sionoper
ator(
/)

Ret
urnst
hequot
ientoft
hef
ir
stoper
atorandt
hesecond:

constr
esul
t=20/5/
/resul
t===4

constr
esul
t=20/7/
/resul
t===2.
857142857142857

Ify
oudi v
idebyzer
o,Jav
aScr
iptdoesnotr
aiseanyer
rorbutr
etur
nst
heI
nfi
nit
yval
ue(
or-
Inf
ini
tyi
fthev
aluei
s
negat
ive).

1/0-/
/Inf
ini
ty

1/0/
/-I
nfi
nit
y

10.
4.Ther
emai
nderoper
ator(
%)

Ther
emai
nderi
sav
eryusef
ulcal
cul
ati
oni
nmanyusecases:

constr
esul
t=20%5/
/resul
t===0

constr
esul
t=20%7/
/resul
t===6

Ar
emai
nderbyzer
oisal
way
sNaN,
aspeci
alv
aluet
hatmeans“
NotaNumber
”:

1%0/
/NaN

10.
5.Themul
ti
pli
cat
ionoper
ator(
*)

Mul
ti
plyt
wonumber
s

1*2/
/2

1*-
2//
-2

10.
6.Theexponent
iat
ionoper
ator(
**)
Rai
set
hef
ir
stoper
andt
othepoweroft
hesecondoper
and

1*
*2/
/1

2*
*1/
/2

2*
*2/
/4

2*
*8/
/256

8*
*2/
/64

11.Pr
ecedencer
ules

Ev
erycompl
exst
atementwi
thmul
ti
pleoper
ator
sint
hesamel
inewi
lli
ntr
oducepr
ecedencepr
obl
ems.

Taket
hisexampl
e:

l
eta=1*2+(
(5/2)%2)

Ther
esul
tis2.
5,butwhy
?

Whatoper
ati
onsar
eexecut
edf
ir
st,
andwhi
chneedt
owai
t?

Someoper
ati
onshav
emor
epr
ecedencet
hant
heot
her
s.Thepr
ecedencer
ulesar
eli
stedi
nthi
stabl
e:

Oper
ator
Descr
ipt
ion

*/% mul
ti
pli
cat
ion/
div
isi
on

+- addi
ti
on/
subt
ract
ion

= assi
gnment

Oper
ati
onsont
hesamel
evel(
li
ke+and-
)ar
eexecut
edi
ntheor
dert
heyar
efound,
from l
eftt
ori
ght
.

Fol
lowi
ngt
heser
ules,
theoper
ati
onabov
ecanbesol
vedi
nthi
sway
:

l
eta=1*2+(
(5/2)%2)

l
eta=2+(
(5/2)%2)
l
eta=2+(
2.5%2)

l
eta=2+0.
5

l
eta=2.
5

12.Compar
isonoper
ator
s

Af
terassi
gnmentandmat
hoper
ator
s,t
het
hir
dsetofoper
ator
sIwantt
oint
roducei
scompar
isonoper
ator
s.

Youcanuset
hef
oll
owi
ngoper
ator
stocompar
etwonumber
s,ort
wost
ri
ngs.

Compar
isonoper
ator
sal
way
sret
urnabool
ean,
aval
uet
hat
’st
rueorf
alse)
.

Thosear
edi
sequal
it
ycompar
isonoper
ator
s:

<means“
lesst
han”

<=means“
minust
han,
orequalt
o”

>means“
great
ert
han”

>=means“
great
ert
han,
orequalt
o”

Exampl
e:

l
eta=2

a>=1/
/tr
ue

I
naddi
ti
ont
othose,
wehav
e4equal
it
yoper
ator
s.Theyacceptt
wov
alues,
andr
etur
nabool
ean:

===checksf
orequal
it
y

!
==checksf
ori
nequal
it
y

Notethatweal
sohave==and!
=inJav
aScr
ipt
,butIhi
ghl
ysuggestt
oonl
yuse===and!
==becauset
heycan
pr
eventsomesubt
leprobl
ems.

13.Condi
ti
onal
s

Wi
tht
hecompar
isonoper
ator
sinpl
ace,
wecant
alkaboutcondi
ti
onal
s.
Anifst
atementi
susedt
omaket
hepr
ogr
am t
akear
out
e,oranot
her
,dependi
ngont
her
esul
tofanexpr
essi
on
ev
aluat
ion.

Thi
sist
hesi
mpl
estexampl
e,whi
chal
way
sexecut
es:

i
f(t
rue){

/
/dosomet
hing

ont
hecont
rar
y,t
hisi
snev
erexecut
ed:

i
f(f
alse){

/
/dosomet
hing(
?nev
er?
)

Thecondit
ionalcheckstheexpressi
onyoupasstoitf
oratr
ueorfalseval
ue.I
fyoupassanumber,
thatalways
eval
uatest
ot rueunlessi
t’
s0.Ifyoupassastri
ng,i
tal
wayseval
uatestotr
ueunlessi
t’
sanemptystr
ing.Thosear
e
gener
alrul
esofcast ingt
ypestoaboolean.

Di
dyounot
icet
hecur
lybr
aces?Thati
scal
ledabl
ock,
andi
tisusedt
ogr
oupal
istofdi
ff
erentst
atement
s.

Abl
ockcanbeputwher
every
oucanhaveasi
nglest
atement.Andi
fyouhav
easi
ngl
est
atementt
oexecut
eaf
ter
t
hecondi
ti
onal
s,y
oucanomitthebl
ock,
andj
ustwri
tethest
atement
:

i
f(t
rue)doSomet
hing(
)

ButIal
way
sli
ket
ousecur
lybr
acest
obemor
ecl
ear
.

13.
1.El
se

Youcanpr
ovi
deasecondpar
ttot
hei
fst
atement
:el
se.

Youat
tachast
atementt
hati
sgoi
ngt
obeexecut
edi
fthei
fcondi
ti
oni
sfal
se:
i
f(t
rue){

/
/dosomet
hing

}el
se{

/
/dosomet
hingel
se

Si
nceel
seaccept
sast
atement
,youcannestanot
heri
f/el
sest
atementi
nsi
dei
t:

i
f(a===t
rue){

/
/dosomet
hing

}el
sei
f(b===t
rue){

/
/dosomet
hingel
se

}el
se{

/
/fal
lback

14.Ar
ray
s

Anar
rayi
sacol
lect
ionofel
ement
s.

Ar
ray
sinJav
aScr
iptar
enotat
ypeont
hei
rown.

Ar
ray
sar
eobj
ect
s.

Wecani
nit
ial
izeanempt
yar
rayi
nthese2di
ff
erentway
s:

consta=[
]

consta=Ar
ray
()

Thef
ir
sti
susi
ngt
hear
rayl
it
eralsy
ntax.Thesecondusest
heAr
raybui
lt
-i
nfunct
ion.

Youcanpr
e-f
il
lthear
rayusi
ngt
hissy
ntax:
consta=[
1,2,
3]

consta=Ar
ray
.of
(1,
2,3)

Anar
raycanhol
danyv
alue,
evenv
alueofdi
ff
erentt
ypes:

consta=[
1,'
Fl
avi
o',
['
a'
,'
b'
]]

Sincewecanaddanarr
ayintoanar
ray
,wecancr
eat
emul
ti
-di
mensi
onalar
ray
s,whi
chhav
ever
yusef
ul
appli
cat
ions(
e.g.amat
ri
x):

constmat
ri
x=[

[
1,2,
3],

[
4,5,
6],

[
7,8,
9],

mat
ri
x[0]
[0]/
/1

mat
ri
x[2]
[0]/
/7

Youcanaccessanyel
ementoft
hear
raybyr
efer
enci
ngi
tsi
ndex,
whi
chst
art
sfr
om zer
o:

a[
0]/
/1

a[
1]/
/2

a[
2]/
/3

Youcanini
ti
ali
zeanewarraywi
thasetofval
uesusi
ngt
hissy
ntax,
whi
chf
ir
sti
nit
ial
izesanar
rayof12el
ement
s,
andfi
ll
seachelementwi
ththe0number:

Ar
ray
(12)
.f
il
l(
0)

Youcangett
henumberofel
ement
sint
hear
raybychecki
ngi
tsl
engt
hpr
oper
ty:

consta=[
1,2,
3]

a.
lengt
h//
3
Notethaty
oucansetthelengthoft
hearray
.Ify
ouassi
gnabiggernumberthant
hear
ray
’scur
rentcapaci
ty,
not
hinghappens.I
fyouassignasmall
ernumber,t
hear
rayi
scutatthatposi
ti
on:

consta=[
1,2,
3]

a/
/[1,
2,3]

a.
lengt
h=2

a/
/[1,
2]

14.
1.Howt
oaddani
tem t
oanar
ray

Wecanaddanel
ementatt
heendofanar
rayusi
ngt
hepush(
)met
hod:

a.
push(
4)

Wecanaddanel
ementatt
hebegi
nni
ngofanar
rayusi
ngt
heunshi
ft
()met
hod:

a.
unshi
ft
(0)

a.
unshi
ft
(-
2,-
1)

14.
2.Howt
oremov
eani
tem f
rom anar
ray

Wecanr
emov
eani
tem f
rom t
heendofanar
rayusi
ngt
hepop(
)met
hod:

a.
pop(
)

Wecanr
emov
eani
tem f
rom t
hebegi
nni
ngofanar
rayusi
ngt
heshi
ft
()met
hod:

a.
shi
ft
()

14.
3.Howt
ojoi
ntwoormor
ear
ray
s

Youcanj
oinmul
ti
plear
ray
sbyusi
ngconcat
():

consta=[
1,2]

constb=[
3,4]

constc=a.
concat
(b)/
/[1,
2,
3,
4]

a/
/[1,
2]
b/
/[3,
4]

Youcanal
souset
hespr
eadoper
ator(
..
.)i
nthi
sway
:

consta=[
1,2]

constb=[
3,4]

constc=[
..
.a,
...
b]

c/
/[1,
2,
3,
4]

14.
4.Howt
ofi
ndaspeci
fi
cit
em i
nthear
ray

Youcanuset
hef
ind(
)met
hodofanar
ray
:

a.
fi
nd(
(el
ement
,index,
arr
ay)=>{

/
/ret
urnt
rueorf
alse

}
)

Thismet
hodr et
urnst
hef
ir
sti
tem t
hatr
etur
nst
ruei
nthecal
lbackf
unct
ionpr
ovi
ded.I
tret
urnsundef
inedi
fnot
hing
ret
urns“
true”
.

I
t’
syourr
esponsi
bil
it
ytodef
inet
hebodyoft
hecal
lbackf
unct
ion,
soy
oucant
ellf
ind(
)whaty
ou’
rel
ooki
ngf
or.

Acommonl
yusedsy
ntaxi
s:

constmy
_id=3

a.
fi
nd(
(x)=>x.
id===my
_id)

Theabov
eli
newi
llr
etur
nthef
ir
stel
ementi
nthear
rayt
hathasi
dequalt
o3,
thev
alueofmy
_id.

f
indI
ndex(
)isanotherar
raymethodthatworkssi
mil
arl
ytof
ind(
),butr
etur
nst
hei
ndexoft
hef
ir
sti
tem t
hatr
etur
ns
t
rue,andi
fnotfound,i
tret
urnsundef
ined:

a.
fi
ndI
ndex(
(el
ement
,index,
arr
ay)=>{

/
/ret
urnt
rueorf
alse
}
)

Anot
herusef
ulmet
hodi
sincl
udes(
):

a.
incl
udes(
val
ue)

Ret
urnst
ruei
facont
ainsv
alue.

a.
incl
udes(
val
ue,
i)

Ret
urnst
ruei
facont
ainsv
alueaf
tert
heposi
ti
oni
.

15.St
ri
ngs

Ast
ri
ngi
sasequenceofchar
act
ers.

I
tcanbeal
sodef
inedasast
ri
ngl
it
eral
,whi
chi
sencl
osedi
nquot
esordoubl
equot
es:

'
Ast
ri
ng'

'
Anot
herst
ri
ng'

Iper
sonal
lypr
efersi
ngl
equot
esal
lthet
ime,
andusedoubl
equot
esonl
yinHTMLt
odef
ineat
tri
but
es.

Youassi
gnast
ri
ngv
aluet
oav
ari
abl
eli
ket
his:

constname='
Fl
avi
o'

Youcandet
ermi
net
hel
engt
hofast
ri
ngusi
ngt
hel
engt
hpr
oper
tyofi
t:

'
Fl
avi
o'.
lengt
h//
6

constname='
Fl
avi
o'

name.
lengt
h//
6

Thi
sisanempt
yst
ri
ng:'
'
.It
slengt
hpr
oper
tyi
s0:

'
'
.l
engt
h//
0
Twost
ri
ngscanbej
oinedusi
ngt
he+oper
ator
:

'
A'+'
str
ing'

Youcanuset
he+oper
atort
oint
erpol
atev
ari
abl
es:

constname='
Fl
avi
o'

'
Mynamei
s'+name/
/Mynamei
sFl
avi
o

Anotherwaytodefi
nestr
ingsi
st ouseaspecialsy
ntaxcall
edtempl
atel
it
eral
s,def
inedi
nsi
debackt
icks.Theyare
especi
all
yusefult
omakemul t
il
inestr
ingsmuchsimpler.Withsi
ngl
eordoubl
equotesyoucan’
tdef
ineamul t
il
ine
str
ingeasi
ly
:you’dneedt
ouseescapingcharacter
s.

Onceatemplat
eli
ter
alisopenedwitht
hebackt
ick,
youj
ustpr
essent
ert
ocr
eat
eanewl
ine,
wit
hnospeci
al
char
act
ers,
andit’
srender
edas-is:

constst
ri
ng=`
Hey

t
his

st
ri
ng

i
sawesome!
`

Templ
atel
it
eral
sar
eal
sogr
eatbecauset
heypr
ovi
deaneasywayt
oint
erpol
atev
ari
abl
esandexpr
essi
onsi
nto
st
ri
ngs.

Youdosobyusi
ngt
he${
..
.}sy
ntax:

constv
ar='
test
'

constst
ri
ng=`
somet
hing${
var
}`

/
/somet
hingt
est

i
nsi
det
he${
}youcanaddany
thi
ng,
evenexpr
essi
ons:

constst
ri
ng=`
somet
hing${
1+2+3}
`

constst
ri
ng2=`
somet
hing

${
a>b?'
a':'
b'
}`
16.Loops

Loopsar
eoneoft
hemai
ncont
rolst
ruct
uresofJav
aScr
ipt
.

Wi
thal
oopwecanaut
omat
eandr
epeati
ndef
ini
tel
yabl
ockofcode,
forhowmanyt
imeswewanti
ttor
un.

Jav
aScr
iptpr
ovi
desmanyway
stoi
ter
atet
hroughl
oops.

Iwantt
ofocuson3way
s:

whi
lel
oops

f
orl
oops

f
or.
.ofl
oops

16.
1.whi
le

Thewhi
lel
oopi
sthesi
mpl
estl
oopi
ngst
ruct
uret
hatJav
aScr
iptpr
ovi
desus.

Weaddacondi
ti
onaf
tert
hewhi
lekey
wor
d,andwepr
ovi
deabl
ockt
hati
srununt
ilt
hecondi
ti
onev
aluat
est
otr
ue.

Exampl
e:

constl
ist=[
'
a',
'b'
,'
c'
]

l
eti=0

whi
le(
i<l
ist
.l
engt
h){

consol
e.l
og(
li
st[
i]
)//
val
ue

consol
e.l
og(
i)/
/index

i=i+1

Youcani
nter
ruptawhi
lel
oopusi
ngt
hebr
eakkey
wor
d,l
iket
his:

whi
le(
true){
i
f(somet
hingI
sTr
ue)br
eak

andifyoudeci
dethati
nthemi
ddl
eofal
oopy
ouwantt
oski
pthecur
renti
ter
ati
on,
youcanj
umpt
othenext
i
ter
ationusi
ngconti
nue:

whi
le(
true){

i
f(somet
hingI
sTr
ue)cont
inue

/
/dosomet
hingel
se

Verysimi
lart
owhil
e,wehav edo..
whi
lel
oops.I
t’
sbasi
cal
lyt
hesameaswhi
le,
exceptt
hecondi
ti
oni
sev
aluat
ed
af
terthecodebl
ockisexecuted.

Thi
smeanst
hebl
ocki
sal
way
sexecut
edatl
eastonce.

Exampl
e:

constl
ist=[
'
a',
'b'
,'
c'
]

l
eti=0

do{

consol
e.l
og(
li
st[
i]
)//
val
ue

consol
e.l
og(
i)/
/index

i=i+1

}whi
le(
i<l
ist
.l
engt
h)

16.
2.f
or

Thesecondv
eryi
mpor
tantl
oopi
ngst
ruct
urei
nJav
aScr
ipti
sthef
orl
oop.

Weuset
hef
orkey
wor
dandwepassasetof3i
nst
ruct
ions:t
hei
nit
ial
izat
ion,
thecondi
ti
on,
andt
hei
ncr
ementpar
t.

Exampl
e:
constl
ist=[
'
a',
'b'
,'
c'
]

f
or(
leti=0;
i<l
ist
.l
engt
h;i
++){

consol
e.l
og(
li
st[
i]
)//
val
ue

consol
e.l
og(
i)/
/index

Justl
ikewi
thwhil
eloops,youcani
nter
ruptaf
orl
oopusi
ngbr
eakandy
oucanf
astf
orwar
dtot
henexti
ter
ati
onof
aforl
oopusingcont
inue.

16.
3.f
or.
..
of

Thi
sloopi
srel
ati
vel
yrecent(
int
roducedi
n2015)andi
t’
sasi
mpl
if
iedv
ersi
onoft
hef
orl
oop:

constl
ist=[
'
a',
'b'
,'
c'
]

f
or(
constv
alueofl
ist
){

consol
e.l
og(
val
ue)/
/val
ue

17.Funct
ions

I
nanymoder
atel
ycompl
exJav
aScr
iptpr
ogr
am,
ever
ythi
nghappensi
nsi
def
unct
ions.

Funct
ionsar
eacor
e,essent
ialpar
tofJav
aScr
ipt
.

Whati
saf
unct
ion?

Af
unct
ioni
sabl
ockofcode,
sel
f-
cont
ained.

Her
e’saf
unct
iondecl
arat
ion:
f
unct
ionget
Dat
a(){

/
/dosomet
hing

Af
unct
ioncanber
unanyt
imey
ouwantbyi
nvoki
ngi
t,l
iket
his:

get
Dat
a()

Af
unct
ioncanhav
eoneormor
ear
gument
:

f
unct
ionget
Dat
a(){

/
/dosomet
hing

f
unct
ionget
Dat
a(col
or){

/
/dosomet
hing

f
unct
ionget
Dat
a(col
or,
age){

/
/dosomet
hing

Whenwecanpassanar
gument
,wei
nvoket
hef
unct
ionpassi
ngpar
amet
ers:

f
unct
ionget
Dat
a(col
or,
age){

/
/dosomet
hing

get
Dat
a('
green'
,24)

get
Dat
a('
black'
)

Notethati
nthesecondinvocat
ionIpassedt
hebl
ackst
ri
ngpar
amet
erast
hecol
orar
gument
,butnoage.I
nthi
s
case,
ageinsi
dethefuncti
onisundefi
ned.
Wecanchecki
fav
aluei
snotundef
inedusi
ngt
hiscondi
ti
onal
:

f
unct
ionget
Dat
a(col
or,
age){

/
/dosomet
hing

i
f(t
ypeofage!
=='
undef
ined'
){

/
/..
.

t
ypeofi
saunar
yoper
atort
hatal
lowsust
ocheckt
het
ypeofav
ari
abl
e.

Youcanal
sochecki
nthi
sway
:

f
unct
ionget
Dat
a(col
or,
age){

/
/dosomet
hing

i
f(age){

/
/..
.

al
thoughi
nthi
scaset
hecondi
ti
onalwi
llbef
alsei
fagei
snul
l,
0oranempt
yst
ri
ng.

Youcanhav
edef
aul
tval
uesf
orpar
amet
ers,
incaset
heyar
enotpassed:

f
unct
ionget
Dat
a(col
or='
black'
,age=25){

/
/dosomet
hing

Youcanpassanyv
alueasapar
amet
er:number
s,st
ri
ngs,
bool
eans,
arr
ays,
obj
ect
s,andal
sof
unct
ions.

Af
unct
ionhasar
etur
nval
ue.Bydef
aul
taf
unct
ionr
etur
nsundef
ined,
unl
essy
ouaddar
etur
nkey
wor
dwi
thav
alue:
f
unct
ionget
Dat
a(){

/
/dosomet
hing

r
etur
n'hi
!'

Wecanassi
gnt
hisr
etur
nval
uet
oav
ari
abl
ewhenwei
nvoket
hef
unct
ion:

f
unct
ionget
Dat
a(){

/
/dosomet
hing

r
etur
n'hi
!'

l
etr
esul
t=get
Dat
a()

r
esul
tnowhol
dsast
ri
ngwi
tht
hehi
!val
ue.

Youcanonl
yret
urnonev
alue.

Tor
etur
nmul
ti
plev
alues,
youcanr
etur
nanobj
ect
,oranar
ray
,li
ket
his:

f
unct
ionget
Dat
a(){

r
etur
n['
Fl
avi
o',
37]

l
et[
name,
age]=get
Dat
a()

Funct
ionscanbedef
inedi
nsi
deot
herf
unct
ions:

constget
Dat
a=(
)=>{

constdosomet
hing=(
)=>{
}

dosomet
hing(
)
r
etur
n't
est
'

Thenest
edf
unct
ioncannotbecal
ledf
rom t
heout
sideoft
heencl
osi
ngf
unct
ion.

Youcanr
etur
naf
unct
ionf
rom af
unct
ion,
too.

18.Ar
rowf
unct
ions

Ar
rowf
unct
ionsar
ear
ecenti
ntr
oduct
iont
oJav
aScr
ipt
.

Theyar
ever
yoftenusedinst
eadof“
regul
ar”f
unct
ions,
theoneIdescr
ibedi
nthepr
evi
ouschapt
er.You’
l
lfi
ndbot
h
for
msusedever
y wher
e.

Vi
sual
ly
,theyal
lowy
out
owr
it
efunct
ionswi
thashor
tersy
ntax,
from:

f
unct
ionget
Dat
a(){

/
/..
.

t
o

;
()=>{

/
/..
.

But
..not
icet
hatwedon’
thav
eanameher
e.

Ar
rowf
unct
ionsar
eanony
mous.Wemustassi
gnt
hem t
oav
ari
abl
e.

Wecanassi
gnar
egul
arf
unct
iont
oav
ari
abl
e,l
iket
his:

l
etget
Dat
a=f
unct
ionget
Dat
a(){
/
/..
.

Whenwedoso,
wecanr
emov
ethenamef
rom t
hef
unct
ion:

l
etget
Dat
a=f
unct
ion(
){

/
/..
.

andi
nvoket
hef
unct
ionusi
ngt
hev
ari
abl
ename:

l
etget
Dat
a=f
unct
ion(
){

/
/..
.

get
Dat
a()

That
’st
hesamet
hingwedowi
thar
rowf
unct
ions:

l
etget
Dat
a=(
)=>{

/
/..
.

get
Dat
a()

I
fthef
unct
ionbodycont
ainsj
ustasi
ngl
est
atement
,youcanomi
tthepar
ent
hesesandwr
it
eital
lonasi
ngl
eli
ne:

constget
Dat
a=(
)=>consol
e.l
og(
'hi
!'
)

Par
amet
ersar
epassedi
nthepar
ent
heses:

constget
Dat
a=(
par
am1,
par
am2)=>consol
e.l
og(
par
am1,
par
am2)

I
fyouhav
eone(
andj
ustone)par
amet
er,
youcoul
domi
tthepar
ent
hesescompl
etel
y:

constget
Dat
a=(
par
am)=>consol
e.l
og(
par
am)

Ar
rowf
unct
ionsal
lowy
out
ohav
eani
mpl
ici
tret
urn:v
aluesar
eret
urnedwi
thouthav
ingt
ouset
her
etur
nkey
wor
d.
I
twor
kswhent
her
eisaon-
li
nest
atementi
nthef
unct
ionbody
:

constget
Dat
a=(
)=>'
test
'

get
Dat
a()/
/'t
est
'

Li
kewi
thr
egul
arf
unct
ions,
wecanhav
edef
aul
tpar
amet
ers:

Youcanhav
edef
aul
tval
uesf
orpar
amet
ers,
incaset
heyar
enotpassed:

constget
Dat
a=(
col
or='
black'
,age=2)=>{

/
/dosomet
hing

andwecanonl
yret
urnonev
alue.

Ar
rowf
unct
ionscancont
ainot
herar
rowf
unct
ion,
oral
sor
egul
arf
unct
ions.

Theyarev
erysi
mil
ar,
soyoumightaskwhytheywer
eint
roduced?Thebigdi
ff
erencewi
thr
egul
arf
unct
ionsi
swhen
theyar
eusedasobj
ectmet
hods.Thi
sissomethi
ngwe’l
lsoonlooki
nto.

19.Obj
ect
s

Anyv
aluet
hat
’snotofapr
imi
ti
vet
ype(
ast
ri
ng,
anumber
,abool
ean,
asy
mbol
,nul
l,
orundef
ined)i
sanobj
ect
.

Her
e’showwedef
ineanobj
ect
:

constcar={
}

Thi
sist
heobj
ectl
it
eralsy
ntax,
whi
chi
soneoft
heni
cestt
hingsi
nJav
aScr
ipt
.

Youcanal
souset
henewObj
ectsy
ntax:
constcar=newObj
ect
()

Anot
hersy
ntaxi
stouseObj
ect
.cr
eat
e()
:

constcar=Obj
ect
.cr
eat
e()

Youcanalsoinit
iali
zeanobjectusi
ngt
henewkeywordbefor
eaf unct
ionwi
thacapi
tall
ett
er.Thi
sfuncti
onserv
es
asaconstruct
orf orthatobj
ect
.Int
her
e,wecani
nit
ial
izet
heargumentswerecei
veasparameter
s,tosetupthe
i
nit
ialst
ateoftheobj ect:

f
unct
ionCar
(br
and,
model
){

t
his.
brand=br
and

t
his.
model=model

Wei
nit
ial
izeanewobj
ectusi
ng

constmy
Car=newCar
('
For
d',
'Fi
est
a')

my
Car
.br
and/
/'For
d'

my
Car
.model/
/'Fi
est
a'

Obj
ect
sar
eal
way
spassedbyr
efer
ence.

I
fyouassi
gnav
ari
abl
ethesamev
alueofanot
her
,ifi
t’
sapr
imi
ti
vet
ypel
ikeanumberorast
ri
ng,
theyar
epassed
byval
ue:

Taket
hisexampl
e:

l
etage=36

l
etmy
Age=age

my
Age=37

age/
/36

constcar={

col
or:'
blue'
,
}

constanot
her
Car=car

anot
her
Car
.col
or='
yel
low'

car
.col
or/
/'y
ell
ow'

Ev
enar
ray
sorf
unct
ionsar
e,undert
hehood,
obj
ect
s,soi
t’
sver
yimpor
tantt
ounder
standhowt
heywor
k.

19.
1.Obj
ectPr
oper
ti
es

Obj
ect
shav
epr
oper
ti
es,
whi
char
ecomposedbyal
abelassoci
atedwi
thav
alue.

Theval
ueofapr
oper
tycanbeofanyty
pe,whi
chmeanst
hati
tcanbeanar
ray
,af
unct
ion,
andi
tcanev
enbean
obj
ect,
asobj
ect
scannestot
herobj
ect
s.

Thi
sist
heobj
ectl
it
eralsy
ntaxwesawi
nthepr
evi
ouschapt
er:

constcar={
}

Wecandef
ineacol
orpr
oper
tyi
nthi
sway
:

constcar={

col
or:'
blue'
,

herewehaveacarobjectwithapropert
ynamedcolor
,wi
ththev
alueblue.Label
scanbeanyst
ri
ng,butbeware
speci
alchar
act
ers:i
fIwantedtoincludeachar
act
ernotv
ali
dasav ar
iablenameinthepr
oper
tyname,Iwould
havehadtousequotesaroundit
:

constcar={

col
or:'
blue'
,

'
thecol
or'
:'
blue'
,

I
nval
idv
ari
abl
enamechar
act
ersi
ncl
udespaces,
hyphens,
andot
herspeci
alchar
act
ers.
Asy
ousee,
whenwehav
emul
ti
plepr
oper
ti
es,
wesepar
ateeachpr
oper
tywi
thacomma.

Wecanr
etr
iev
ethev
alueofapr
oper
tyusi
ng2di
ff
erentsy
ntaxes.

Thef
ir
sti
sdotnot
ati
on:

car
.col
or/
/'bl
ue'

Thesecond(
whi
chi
stheonl
yonewecanusef
orpr
oper
ti
eswi
thi
nval
idnames)
,ist
ousesquar
ebr
acket
s:

car
['
thecol
or'
]//
'bl
ue'

I
fyouaccessanunexi
sti
ngpr
oper
ty,
you’
l
lgett
heundef
inedv
alue:

car
.br
and/
/undef
ined

Assai
d,obj
ect
scanhav
enest
edobj
ect
saspr
oper
ti
es:

constcar={

br
and:{

name:'
For
d',

}
,

col
or:'
blue'
,

I
nthi
sexampl
e,y
oucanaccesst
hebr
andnameusi
ng

car
.br
and.
name

or

car
['
brand'
]
['
name'
]

Youcansett
hev
alueofapr
oper
tywheny
oudef
inet
heobj
ect
.
Buty
oucanal
way
supdat
eitl
ateron:

constcar={

col
or:'
blue'
,

car
.col
or='
yel
low'

car
['
col
or'
]='
red'

Andy
oucanal
soaddnewpr
oper
ti
est
oanobj
ect
:

car
.model='
Fi
est
a'

car
.model/
/'Fi
est
a'

Gi
vent
heobj
ect

constcar={

col
or:'
blue'
,

br
and:'
For
d',

y
oucandel
eteapr
oper
tyf
rom t
hisobj
ectusi
ng

del
etecar
.br
and

19.
2.Obj
ectMet
hods

It
alkedaboutf
unct
ionsi
napr
evi
ouschapt
er.

Funct
ionscanbeassi
gnedt
oaf
unct
ionpr
oper
ty,
andi
nthi
scaset
heyar
ecal
ledmet
hods.

I
nthi
sexample,t
hestar
tpropert
yhasafunct
ionassi
gned,
andwecani
nvokei
tbyusi
ngt
hedotsy
ntaxweused
f
orpr
opert
ies,wi
tht
heparenthesesatt
heend:

constcar={
br
and:'
For
d',

model
:'
Fi
est
a',

st
art
:funct
ion(
){

consol
e.l
og(
'St
art
ed'
)

}
,

car
.st
art
()

I
nsi
deamet
hoddef
inedusi
ngaf
unct
ion(
){}sy
ntaxwehav
eaccesst
otheobj
ecti
nst
ancebyr
efer
enci
ngt
his.

I
nthef
oll
owi
ngexampl
e,wehav
eaccesst
othebr
andandmodelpr
oper
ti
esv
aluesusi
ngt
his.
brandandt
his.
model
:

constcar={

br
and:'
For
d',

model
:'
Fi
est
a',

st
art
:funct
ion(
){

consol
e.l
og(
`St
art
ed

${
thi
s.br
and}${
thi
s.model
}`
)

}
,

car
.st
art
()

I
t’
simpor
tanttonotet
hisdist
inct
ionbet
weenr
egul
arf
unct
ionsandar
rowf
unct
ions:wedon’
thav
eaccesst
othi
sif
weuseanarrowfunct
ion:

constcar={

br
and:'
For
d',

model
:'
Fi
est
a',

st
art
:()=>{
consol
e.l
og(
`St
art
ed

${
thi
s.br
and}${
thi
s.model
}`
)//
notgoi
ngt
owor
k

}
,

car
.st
art
()

Thi
sisbecausear
rowf
unct
ionsar
enotboundt
otheobj
ect
.

Thi
sist
her
easonwhyr
egul
arf
unct
ionsar
eof
tenusedasobj
ectmet
hods.

Met
hodscanacceptpar
amet
ers,
li
ker
egul
arf
unct
ions:

constcar={

br
and:'
For
d',

model
:'
Fi
est
a',

goTo:f
unct
ion(
dest
inat
ion){

consol
e.l
og(
`Goi
ngt
o${
dest
inat
ion}
`)

}
,

car
.goTo(
'Rome'
)

20.Cl
asses

Wet
alkedaboutobj
ect
s,whi
char
eoneoft
hemosti
nter
est
ingpar
tsofJav
aScr
ipt
.

I
nthi
schapt
erwe’
l
lgouponel
evel
,i
ntr
oduci
ngcl
asses.

Whatar
ecl
asses?Theyar
eawayt
odef
ineacommonpat
ter
nformul
ti
pleobj
ect
s.

Let
’st
akeaper
sonobj
ect
:
constper
son={

name:'
Fl
avi
o',

Wecancreat
eacl
assnamedPer
son(
not
ethecapi
talP,
aconv
ent
ionwhenusi
ngcl
asses)
,thathasaname
pr
oper
ty:

cl
assPer
son{

name

Nowf
rom t
hiscl
ass,
wei
nit
ial
izeaf
lav
ioobj
ectl
iket
his:

constf
lav
io=newPer
son(
)

f
lav
ioi
scal
ledani
nst
anceoft
hePer
soncl
ass.

Wecansett
hev
alueoft
henamepr
oper
ty:

f
lav
io.
name='
Fl
avi
o'

andwecanaccessi
tusi
ng

f
lav
io.
name

l
ikewedof
orobj
ectpr
oper
ti
es.

Cl
assescanhol
dpr
oper
ti
es,
li
kename,
andmet
hods.

Met
hodsar
edef
inedi
nthi
sway
:

cl
assPer
son{

hel
lo(
){

r
etur
n'Hel
lo,
Iam Fl
avi
o'

andwecani
nvokemet
hodsonani
nst
anceoft
hecl
ass:

cl
assPer
son{
hel
lo(
){

r
etur
n'Hel
lo,
Iam Fl
avi
o'

constf
lav
io=newPer
son(
)

f
lav
io.
hel
lo(
)

Ther
eisaspecialmet
hodcal
ledconst
ruct
or(
)thatwecanuset
oini
ti
ali
zet
hecl
asspr
oper
ti
eswhenwecr
eat
ea
newobjecti
nst
ance.

I
twor
ksl
iket
his:

cl
assPer
son{

const
ruct
or(
name){

t
his.
name=name

hel
lo(
){

r
etur
n'Hel
lo,
Iam '
+thi
s.name+'
.
'

Not
ehowweuset
hist
oaccesst
heobj
ecti
nst
ance.

Nowwecani nst
anti
ateanewobj
ectf
rom t
hecl
ass,
passi
ngast
ri
ng,
andwhenwecal
lhel
lo,
we’
l
lgeta
per
sonal
izedmessage:

constf
lav
io=newPer
son(
'f
lav
io'
)

f
lav
io.
hel
lo(
)//
'Hel
lo,
Iam f
lav
io.
'

Whent
heobj
ecti
sini
ti
ali
zed,
theconst
ruct
ormet
hodi
scal
led,
wit
hanypar
amet
erspassed.

Nor
mal
lymet
hodsar
edef
inedont
heobj
ecti
nst
ance,
notont
hecl
ass.
Youcandef
ineamet
hodasst
ati
ctoal
lowi
ttobeexecut
edont
hecl
assi
nst
ead:

cl
assPer
son{

st
ati
cgener
icHel
lo(
){

r
etur
n'Hel
lo'

Per
son.
gener
icHel
lo(
)//
Hel
lo

Thi
sisv
eryusef
ul,
att
imes.

21.I
nher
it
ance

Acl
asscanext
endanot
hercl
ass,
andobj
ect
sini
ti
ali
zedusi
ngt
hatcl
assi
nher
ital
lthemet
hodsofbot
hcl
asses.

Supposewehav
eacl
assPer
son:

cl
assPer
son{

hel
lo(
){

r
etur
n'Hel
lo,
Iam aPer
son'

Wecandef
ineanewcl
assPr
ogr
ammert
hatext
endsPer
son:

cl
assPr
ogr
ammerext
endsPer
son{
}

Nowi
fwei
nst
ant
iat
eanewobj
ectwi
thcl
assPr
ogr
ammer
,ithasaccesst
othehel
lo(
)met
hod:

constf
lav
io=newPr
ogr
ammer
()

f
lav
io.
hel
lo(
)//
'Hel
lo,
Iam aPer
son'
I
nsi
deachi
ldcl
ass,
youcanr
efer
encet
hepar
entcl
asscal
li
ngsuper
():

cl
assPr
ogr
ammerext
endsPer
son{

hel
lo(
){

r
etur
nsuper
.hel
lo(
)+'
.Iam al
soapr
ogr
ammer
.'

constf
lav
io=newPr
ogr
ammer
()

f
lav
io.
hel
lo(
)

Theabov
epr
ogr
am pr
int
sHel
lo,
Iam aPer
son.Iam al
soapr
ogr
ammer
..

22.Asy
nchr
onousPr
ogr
ammi
ngandCal
lbacks

Mostoft
het
ime,
Jav
aScr
iptcodei
sransy
nchr
onousl
y.

Thi
smeanst
hatal
ineofcodei
sexecut
ed,
thent
henextonei
sexecut
ed,
andsoon.

Ev
ery
thi
ngi
sasy
ouexpect
,andhowi
twor
ksi
nmostpr
ogr
ammi
ngl
anguages.

Howev
er,
ther
ear
eti
meswheny
oucannotj
ustwai
tforal
ineofcodet
oexecut
e.

Youcan’
tjustwai
t2secondsf
orabi
gfi
let
oload,
andhal
tthepr
ogr
am compl
etel
y.

Youcan’
tjustwai
tforanet
wor
kresour
cet
obedownl
oaded,
bef
oredoi
ngsomet
hingel
se.

Jav
aScr
iptsol
vest
hispr
obl
em usi
ngcal
lbacks.

Oneoft
hesi
mpl
estexamplesofhowtousecall
backsi
stimer
s.Timersar
enotpartofJavaScr
ipt,butt
heyar
e
pr
ovi
dedbyt
hebr
owser,andNode.j
s.Letmetal
kaboutoneoftheti
merswehave:setTi
meout().
Theset
Timeout(
)funct
ionaccept
s2argument
s:af
unct
ion,
andanumber
.Thenumberi
sthemi
ll
isecondst
hat
mustpassbef
orethefunct
ionisr
an.

Exampl
e:

set
Timeout
(()=>{

/
/runsaf
ter2seconds

consol
e.l
og(
'i
nsi
det
hef
unct
ion'
)

}
,2000)

Thef
unct
ioncont
aini
ngt
heconsol
e.l
og(
'i
nsi
det
hef
unct
ion'
)li
newi
llbeexecut
edaf
ter2seconds.

I
fyouaddaconsol
e.l
og(
'bef
ore'
)pr
iort
othef
unct
ion,
andconsol
e.l
og(
'af
ter
')af
teri
t:

consol
e.l
og(
'bef
ore'
)

set
Timeout
(()=>{

/
/runsaf
ter2seconds

consol
e.l
og(
'i
nsi
det
hef
unct
ion'
)

}
,2000)

consol
e.l
og(
'af
ter
')

Youwi
llseet
hishappeni
ngi
nyourconsol
e:

bef
ore

af
ter

i
nsi
det
hef
unct
ion

Thecal
lbackf
unct
ioni
sexecut
edasy
nchr
onousl
y.

Thi
sisav
erycommonpat
ter
nwhenwor
kingwi
tht
hef
il
esy
stem,
thenet
wor
k,ev
ent
s,ort
heDOM i
nthebr
owser
.
Al
lofthethi
ngsIment
ionedarenot“core”JavaScr
ipt
,sotheyarenotexpl
ainedi
nthi
shandbook,
buty
ou’
l
lfi
nd
l
otsofexamplesi
nmyot herhandbooksavai
labl
eatflav
iocopes.
com.

Her
e’showwecani
mpl
ementcal
lbacksi
nourcode.

Wedef
ineaf
unct
iont
hataccept
sacal
lbackpar
amet
er,
whi
chi
saf
unct
ion.

Whent
hecodei
sreadyt
oinv
oket
hecal
lback,
wei
nvokei
tpassi
ngt
her
esul
t:

constdoSomet
hing=(
cal
lback)=>{

/
/dot
hings

/
/dot
hings

constr
esul
t=/
*..*
/cal
lback(
resul
t)

Codeusi
ngt
hisf
unct
ionwoul
dusei
tli
ket
his:

doSomet
hing(
(resul
t)=>{

consol
e.l
og(
resul
t)

}
)

23.Pr
omi
ses

Pr
omi
sesar
eanal
ter
nat
ivewayt
odealwi
thasy
nchr
onouscode.

Aswesawi ntheprev
iouschapt
er,wit
hcallbackswe’
dbepassi
ngaf
unct
iont
oanot
herf
unct
ioncal
l,
thatwoul
dbe
cal
ledwhenthefunct
ionhasfi
nishedprocessi
ng.

Li
ket
his:

doSomet
hing(
(resul
t)=>{

consol
e.l
og(
resul
t)

}
)
Whent
hedoSomet
hing(
)codeends,
itcal
lst
hef
unct
ionr
ecei
vedasaapar
amet
er:

constdoSomet
hing=(
cal
lback)=>{

/
/dot
hings

/
/dot
hings

constr
esul
t=/
*..*
/cal
lback(
resul
t)

Themai nproblem wi
tht
hisapproachi sthati
fweneedt ousetheresul
tofthisf
unct
ioninther
estofourcode,al
l
ourcodemustbenest edinsidethecall
back,andifwehavet odo2-3cal
lbacksweenteri
nwhatisusual
lydefi
ned
“cal
lbackhell
”withmanylevelsoffuncti
onsindentedi
ntootherf
uncti
ons:

doSomet
hing(
(resul
t)=>{

doSomet
hingEl
se(
(anot
her
Resul
t)=>{

doSomet
hingEl
seAgai
n((
yet
Anot
her
Resul
t)=>{

consol
e.l
og(
resul
t)

}
)

}
)

}
)

Pr
omi
sesar
eonewayt
odealwi
tht
his.

I
nst
eadofdoi
ng:

doSomet
hing(
(resul
t)=>{

consol
e.l
og(
resul
t)

}
)

Wecal
lapr
omi
se-
basedf
unct
ioni
nthi
sway
:

doSomet
hing(
).
then(
(resul
t)=>{

consol
e.l
og(
resul
t)

}
)
Wef
ir
stcal
lthef
unct
ion,
thenwehav
eat
hen(
)met
hodt
hati
scal
ledwhent
hef
unct
ionends.

Thei
ndent
ati
ondoesnotmat
ter
,buty
ou’
l
lof
tenuset
hisst
ylef
orcl
ari
ty.

I
t’
scommont
odet
ecter
ror
susi
ngacat
ch(
)met
hod:

doSomet
hing(
)

.
then(
(resul
t)=>{

consol
e.l
og(
resul
t)

}
)

.
cat
ch(
(er
ror
)=>{

consol
e.l
og(
err
or)

}
)

Now,t
obeabl
etousethi
ssy
ntax,
thedoSomet
hing(
)funct
ioni
mpl
ement
ati
onmustbeal
it
tl
ebi
tspeci
al.I
tmust
uset
hePr
omisesAPI
.

I
nst
eadofdecl
ari
ngi
tasanor
malf
unct
ion:

constdoSomet
hing=(
)=>{
}

Wedecl
arei
tasapr
omi
seobj
ect
:

constdoSomet
hing=newPr
omi
se(
)

andwepassaf
unct
ioni
nthePr
omi
seconst
ruct
or:

constdoSomet
hing=newPr
omi
se(
()=>{
})

Thi
sfuncti
onr ecei
ves2paramet
ers.Thef
ir
sti
saf
unct
ionwecal
ltor
esol
vet
hepr
omi
se,
thesecondi
saf
unct
ion
wecallt
orejectthepromi
se.

constdoSomet
hing=newPr
omi
se(
(resol
ve,
rej
ect
)=>{
})

Resol
vi
ngapr
omi
semeanscompl
eti
ngi
tsuccessf
ull
y(whi
chr
esul
tsi
ncal
li
ngt
het
hen(
)met
hodi
nwhousesi
t)
.
Rej
ect
ingapr
omi
semeansendi
ngi
twi
thaner
ror(
whi
chr
esul
tsi
ncal
li
ngt
hecat
ch(
)met
hodi
nwhousesi
t)
.

Her
e’show:

constdoSomet
hing=newPr
omi
se(

(
resol
ve,
rej
ect
)=>{

/
/somecode

constsuccess=/
*..
.*/

i
f(success){

r
esol
ve(
'ok'
)

}el
se{

r
eject
('
thi
ser
roroccur
red'
)

Wecanpassapar
amet
ert
other
esol
veandr
ejectf
unct
ions,
ofanyt
ypewewant
.

24.Asy
ncandAwai
t

Asy
ncf
unct
ionsar
eahi
gherl
evelabst
ract
ionov
erpr
omi
ses.

Anasy
ncf
unct
ionr
etur
nsapr
omi
se,
li
kei
nthi
sexampl
e:

constget
Dat
a=(
)=>{

r
etur
nnewPr
omi
se(
(resol
ve,
rej
ect
)=>{

set
Timeout
(()=>r
esol
ve(
'somedat
a')
,2000)

}
)

Anycodet
hatwant
stouset
hisf
unct
ionwi
lluset
heawai
tkey
wor
dri
ghtbef
oret
hef
unct
ion:
constdat
a=awai
tget
Dat
a()

anddoi
ngso,
anydat
aret
urnedbyt
hepr
omi
sei
sgoi
ngt
obeassi
gnedt
othedat
avar
iabl
e.

I
nourcase,
thedat
aist
he“
somedat
a”st
ri
ng.

Wi
thonepar
ti
cul
arcav
eat
:whenev
erweuset
heawai
tkey
wor
d,wemustdosoi
nsi
deaf
unct
iondef
inedasasy
nc.

Li
ket
his:

constdoSomet
hing=asy
nc(
)=>{

constdat
a=awai
tget
Dat
a()

consol
e.l
og(
dat
a)

TheAsy
nc/
awai
tduoal
lowsust
ohav
eacl
eanercodeandasi
mpl
ement
almodelt
owor
kwi
thasy
nchr
onouscode.

Asy oucanseei
ntheexampl
eabov
e,ourcodel
ooksv
erysi
mpl
e.Compar
eitt
ocodeusi
ngpr
omi
ses,
orcal
lback
functi
ons.

Andt
hisi
sav
erysi
mpl
eexampl
e,t
hemaj
orbenef
it
swi
llar
isewhent
hecodei
smuchmor
ecompl
ex.

Asanexampl
e,her
e’showy
ouwoul
dgetaJSONr
esour
ceusi
ngt
heFet
chAPI
,andpar
sei
t,usi
ngpr
omi
ses:

constget
Fir
stUser
Dat
a=(
)=>{

/
/getuser
sli
st

r
etur
n(

f
etch(
'/
user
s.j
son'
)

/
/par
seJSON

.
then(
(response)=>r
esponse.
json(
))

/
/pi
ckf
ir
stuser
.
then(
(user
s)=>user
s[0]
)

/
/getuserdat
a

.
then(
(user
)=>f
etch(
`/user
s/${
user
.name}
`))

/
/par
seJSON

.
then(
(user
Response)=>user
Response.
json(
))

get
Fir
stUser
Dat
a()

Andher
eist
hesamef
unct
ional
i
typr
ovi
dedusi
ngawai
t/asy
nc:

constget
Fir
stUser
Dat
a=asy
nc(
)=>{

/
/getuser
sli
st

constr
esponse=awai
tfet
ch(
'/
user
s.j
son'
)

/
/par
seJSON

constuser
s=awai
tresponse.
json(
)

/
/pi
ckf
ir
stuser

constuser=user
s[0]

/
/getuserdat
a

constuser
Response=awai
tfet
ch(
`/user
s/${
user
.name}
`)

/
/par
seJSON

constuser
Dat
a=awai
tuser
Response.
json(
)

r
etur
nuser
Dat
a

get
Fir
stUser
Dat
a()

25.Var
iabl
esscope

WhenIi
ntr
oducedv
ari
abl
es,
Ital
kedaboutusi
ngconst
,let
,andv
ar.
Scopei
sthesetofv
ari
abl
est
hat
’sv
isi
blet
oapar
toft
hepr
ogr
am.

I
nJav
aScr
iptwehav
eagl
obalscope,
blockscopeandf
unct
ionscope.

I
favar
iabl
eisdefi
nedoutsi
deofafuncti
onorblock,
it’
sat
tachedt
othegl
obalobj
ectandi
thasagl
obalscope,
whi
chmeansit’
savai
labl
einever
ypartofaprogram.

Ther
eisav
eryi
mpor
tantdi
ff
erencebet
weenv
ar,
letandconstdecl
arat
ions.

Av
ari
abl
edef
inedasv
ari
nsi
deaf
unct
ioni
sonl
yvi
sibl
einsi
det
hatf
unct
ion.Si
mil
arl
ytoaf
unct
ionar
gument
s:

Av
ari
abl
edef
inedasconstorl
etont
heot
herhandi
sonl
yvi
sibl
einsi
det
hebl
ockwher
eiti
sdef
ined.

Ablocki
sasetofinst
ructi
onsgr
oupedi
ntoapai
rofcur
lybr
aces,
li
ket
heoneswecanf
indi
nsi
deani
fst
atement
oraforl
oop.Andafuncti
on,t
oo.

I
t’
simpor
tantt
ounder
standt
hatabl
ockdoesnotdef
ineanewscopef
orv
ar,
buti
tdoesf
orl
etandconst
.

Thi
shasv
erypr
act
icali
mpl
icat
ions.

Supposey
oudef
ineav
arv
ari
abl
einsi
deani
fcondi
ti
onali
naf
unct
ion

f
unct
ionget
Dat
a(){

i
f(t
rue){

v
ardat
a='
somedat
a'

consol
e.l
og(
dat
a)

I
fyoucal
lthi
sfunct
ion,
you’
l
lgetsomedat
apr
int
edt
otheconsol
e.
I
fyout
ryt
omov
econsol
e.l
og(
dat
a)af
tert
hei
f,i
tst
il
lwor
ks:

f
unct
ionget
Dat
a(){

i
f(t
rue){

v
ardat
a='
somedat
a'

consol
e.l
og(
dat
a)

Buti
fyouswi
tchv
ardat
atol
etdat
a:

f
unct
ionget
Dat
a(){

i
f(t
rue){

l
etdat
a='
somedat
a'

consol
e.l
og(
dat
a)

You’
l
lgetaner
ror
:Ref
erenceEr
ror
:dat
aisnotdef
ined.

Thisisbecausevari
sfuncti
onscoped,andthere’
saspeci
althi
nghappeninghere,cal
ledhoi
sti
ng.I
nshor
t,thevar
declar
ati
onismov edtothetopoft
heclosestfuncti
onbyJav
aScri
pt,bef
oreitrunsthecode.Moreorl
essthisi
s
whatthefuncti
onlooksl
iketoJS,i
nter
nall
y:

f
unct
ionget
Dat
a(){

v
ardat
a

i
f(t
rue){

dat
a='
somedat
a'

consol
e.l
og(
dat
a)

Thi
siswhyy
oucanal
soconsol
e.l
og(
dat
a)att
het
opofaf
unct
ion,
evenbef
orei
t’
sdecl
ared,
andy
ou’
l
lget
undef
inedasav
aluef
ort
hatv
ari
abl
e:

f
unct
ionget
Dat
a(){

consol
e.l
og(
dat
a)

i
f(t
rue){

v
ardat
a='
somedat
a'

buti
fyouswitchtol
et,
you’
l
lgetaner
rorRef
erenceEr
ror
:dat
aisnotdef
ined,
becausehoi
sti
ngdoesnothappent
o
l
etdecl
arat
ions.

constf
oll
owst
hesamer
ulesasl
et:i
t’
sbl
ockscoped.

I
tcanbet r
ickyatfir
st,
butoncey oureali
zethisdif
ference,
t henyou’l
lseewhyv arisconsi
deredabadpract
ice
nowadayscompar edtolet
:theydohav efewermov ingparts,andtheirscopeisli
mitedtotheblock,
whi
chalso
makesthem verygoodasloopv ari
ables,becausetheyceaset oexistafteral
oophasended:

f
unct
iondoLoop(
){

f
or(
vari=0;
i<10;
i++){

consol
e.l
og(
i)

consol
e.l
og(
i)

doLoop(
)

Wheny
ouexi
tthel
oop,
iwi
llbeav
ali
dvar
iabl
ewi
thv
alue10.

I
fyouswi
tcht
olet
,ify
out
ryt
oconsol
e.l
og(
i)wi
llr
esul
tinaner
rorRef
erenceEr
ror
:ii
snotdef
ined.

You might also like