Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 77

Jnun SOn|t

!avaScrlpL ls @ scrlpLlng language of Lhe Web


!avaScrlpL ls used ln bllllons of Web pages Lo add funcLlonallLy valldaLe forms communlcaLe wlLh Lhe server and much more
!avaScrlpL ls easy Lo learn ?ou wlll en[oy lL

!avaScrlpL lnLroducLlon
!avaScrlpL ls Lhe mosL popular scrlpLlng language on Lhe lnLerneL and works ln all ma[or browsers such as lnLerneL Lxplorer llrefox
Chrome Cpera and Safarl
WhaL ?ou Should Already know
8efore you conLlnue you should have a baslc undersLandlng of Lhe followlng
O @, and CSS
WhaL ls !avaScrlpL?
O !avaScrlpL was deslgned Lo add lnLeracLlvlLy Lo @, pages
O !avaScrlpL ls a scrlpLlng language
O A scrlpLlng language ls a llghLwelghL programmlng language
O !avaScrlpL ls usually embedded dlrecLly lnLo @, pages
O !avaScrlpL ls an lnLerpreLed language (means LhaL scrlpLs execuLe wlLhouL prellmlnary compllaLlon)
O Lveryone can use !avaScrlpL wlLhouL purchaslng a llcense
Are !ava and !avaScrlpL Lhe same?
nC!
!ava and !avaScrlpL are Lwo compleLely dlfferenL languages ln boLh concepL and deslgn!
!ava (developed by Sun ,lcrosysLems) ls a powerful and much more complex programmlng language ln Lhe same caLegory as C and C++
WhaL Can !avaScrlpL do?
O IavaScr|pt g|ves n1ML des|gners a programm|ng too| @, auLhors are normally noL programmers buL !avaScrlpL ls a scrlpLlng
language wlLh a very slmple synLax! AlmosL anyone can puL small snlppeLs of code lnLo Lhelr @, pages
O IavaScr|pt can react to events A !avaScrlpL can be seL Lo execuLe when someLhlng happens llke when a page has flnlshed loadlng or
when a user cllcks on an @, elemenL
O IavaScr|pt can read and wr|te n1ML e|ements A !avaScrlpL can read and change Lhe conLenL of an @, elemenL
O IavaScr|pt can be used to va||date data A !avaScrlpL can be used Lo valldaLe form daLa before lL ls submlLLed Lo a server @hls saves Lhe
server from exLra processlng
O IavaScr|pt can be used to detect the v|s|tors browser A !avaScrlpL can be used Lo deLecL Lhe vlslLors browser and dependlng on Lhe
browser load anoLher page speclflcally deslgned for LhaL browser
O IavaScr|pt can be used to create cook|es A !avaScrlpL can be used Lo sLore and reLrleve lnformaLlon on Lhe vlslLors compuLer

!avaScrlpL LC,AScrlpL
!avaScrlpL ls an lmplemenLaLlon of Lhe LC,AScrlpL language sLandard LC,A262 ls Lhe offlclal !avaScrlpL sLandard
!avaScrlpL was lnvenLed by 8rendan Llch aL neLscape (wlLh navlgaLor 20) and has appeared ln all browsers slnce 1996
@he offlclal sLandardlzaLlon was adopLed by Lhe LC,A organlzaLlon (an lndusLry sLandardlzaLlon assoclaLlon) ln 1997
@he LC,A sLandard (called LC,AScrlpL262) was approved as an lnLernaLlonal lSC (lSC/lLC 16262) sLandard ln 1998
@he developmenL ls sLlll ln progress

!avaScrlpL ow @o
@he @, scrlpL Lag ls used Lo lnserL a !avaScrlpL lnLo an @, page
WrlLlng Lo @he @, uocumenL
@he example below wrlLes a p elemenL wlLh currenL daLe lnformaLlon Lo Lhe @, documenL
Lxample
hLml
body

h1,y llrsL Web age/h1

scrlpL LypeLexL/[avascrlpL
documenLwrlLe(p + uaLe() + /p)
/scrlpL

/body
/hLml

1ry |t yourse|f
Note @ry Lo avold uslng documenLwrlLe() ln real llfe !avaScrlpL code @he enLlre @, page wlll be overwrlLLen lf documenLwrlLe() ls used lnslde a
funcLlon or afLer Lhe page ls loaded owever documenLwrlLe() ls an easy way Lo demonsLraLe !avaScrlpL ouLpuL ln a LuLorlal
Changlng @, LlemenLs
@he example below wrlLes Lhe currenL daLe lnLo an exlsLlng p elemenL
Lxample
hLml
body

h1,y llrsL Web age/h1

p lddemo/p

scrlpL LypeLexL/[avascrlpL
documenLgeLLlemenL8yld(demo)lnner@,uaLe()
/scrlpL

/body
/hLml

1ry |t yourse|f
Note @o manlpulaLe @, elemenLs !avaScrlpL uses Lhe uC, meLhod getL|ement8yId() @hls meLhod accesses Lhe elemenL wlLh Lhe speclfled ld
Lxamples Lxplalned
@o lnserL a !avaScrlpL lnLo an @, page use Lhe scrlpL Lag
lnslde Lhe scrlpL Lag use Lhe Lype aLLrlbuLe Lo deflne Lhe scrlpLlng language
@he scrlpL and /scrlpL Lells where Lhe !avaScrlpL sLarLs and ends
hLml
body
h1,y llrsL Web age/h1

p lddemo@hls ls a paragraph/p

scrlpL LypeLexL/[avascrlpL
some !avaScrlpL code
/scrlpL

/body
/hLml
@he llnes beLween Lhe scrlpL and /scrlpL conLaln Lhe !avaScrlpL and are execuLed by Lhe browser
ln Lhls case Lhe browser wlll replace Lhe conLenL of Lhe @, elemenL wlLh lddemo wlLh Lhe currenL daLe
hLml
body
h1,y llrsL Web age/h1

p lddemo@hls ls a paragraph/p

scrlpL LypeLexL/[avascrlpL
documenLgeLLlemenL8yld(demo)lnner@,uaLe()
/scrlpL

/body
/hLml
WlLhouL Lhe scrlpL Lag(s) Lhe browser wlll LreaL documenLgeLLlemenL8yld(demo)lnner@,uaLe() as pure LexL and [usL wrlLe lL Lo Lhe
page@ry lL yourself
Some 8rowsers do noL SupporL !avaScrlpL
8rowsers LhaL do noL supporL !avaScrlpL wlll dlsplay !avaScrlpL as page conLenL
@o prevenL Lhem from dolng Lhls and as a parL of Lhe !avaScrlpL sLandard Lhe @, commenL Lag should be used Lo hlde Lhe !avaScrlpL
!usL add an @, commenL Lag ! before Lhe flrsL !avaScrlpL sLaLemenL and a (end of commenL) afLer Lhe lasL !avaScrlpL sLaLemenL llke Lhls
hLml
body
scrlpL LypeLexL/[avascrlpL
!
documenLgeLLlemenL8yld(demo)lnner@,uaLe()
//
/scrlpL
/body
/hLml
@he Lwo forward slashes aL Lhe end of commenL llne (//) ls Lhe !avaScrlpL commenL symbol @hls prevenLs !avaScrlpL from execuLlng Lhe Lag

!avaScrlpL Where @o
!avaScrlpLs can be puL ln Lhe body and ln Lhe head secLlons of an @, page
!avaScrlpL ln body
@he example below wrlLes Lhe currenL daLe lnLo an exlsLlng p elemenL when Lhe page loads
Lxample
hLml
body
h1,y llrsL Web age/h1
p lddemo/p
scrlpL LypeLexL/[avascrlpL
documenLgeLLlemenL8yld(demo)lnner@,uaLe()
/scrlpL
/body
/hLml

1ry |t yourse|f
noLe LhaL Lhe !avaScrlpL ls placed aL Lhe boLLom of Lhe page Lo make sure lL ls noL execuLed before Lhe p elemenL ls creaLed
!avaScrlpL luncLlons and LvenLs
!avaScrlpLs ln an @, page wlll be execuLed when Lhe page loads @hls ls noL always whaL we wanL
SomeLlmes we wanL Lo execuLe a !avaScrlpL when an event occurs such as when a user cllcks a buLLon When Lhls ls Lhe case we can puL Lhe scrlpL
lnslde a funct|on
LvenLs are normally used ln comblnaLlon wlLh funcLlons (llke calllng a funcLlon when an evenL occurs)
?ou wlll learn more abouL !avaScrlpL funcLlons and evenLs ln laLer chapLers
!avaScrlpL ln head
@he example below calls a funcLlon when a buLLon ls cllcked
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon dlsplayuaLe()

documenLgeLLlemenL8yld(demo)lnner@,uaLe()

/scrlpL
/head
body
h1,y llrsL Web age/h1
p lddemo/p
buLLon LypebuLLon oncllckdlsplayuaLe()ulsplay uaLe/buLLon
/body
/hLml

1ry |t yourse|f

ScrlpLs ln head and body
?ou can place an unllmlLed number of scrlpLs ln your documenL and you can have scrlpLs ln boLh Lhe body and Lhe head secLlon aL Lhe same Llme
lL ls a common pracLlce Lo puL all funcLlons ln Lhe head secLlon or aL Lhe boLLom of Lhe page @hls way Lhey are all ln one place and do noL lnLerfere
wlLh page conLenL
uslng an LxLernal !avaScrlpL
!avaScrlpL can also be placed ln exLernal flles
LxLernal !avaScrlpL flles ofLen conLaln code Lo be used on several dlfferenL web pages
LxLernal !avaScrlpL flles have Lhe flle exLenslon [s
Note LxLernal scrlpL cannoL conLaln Lhe scrlpL/scrlpL Lags!
@o use an exLernal scrlpL polnL Lo Lhe [s flle ln Lhe src aLLrlbuLe of Lhe scrlpL Lag
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL srcxxx[s/scrlpL
/head
body
/body
/hLml

1ry |t yourse|f
Note 8emember Lo place Lhe scrlpL exacLly where you normally would wrlLe Lhe scrlpL!

!avaScrlpL SLaLemenLs
!avaScrlpL ls a sequence of sLaLemenLs Lo be execuLed by Lhe browser
!avaScrlpL ls Case SenslLlve
unllke @, !avaScrlpL ls case senslLlve Lherefore waLch your caplLallzaLlon closely when you wrlLe !avaScrlpL sLaLemenLs creaLe or call varlables
ob[ecLs and funcLlons
!avaScrlpL SLaLemenLs
A !avaScrlpL sLaLemenL ls a command Lo a browser @he purpose of Lhe command ls Lo Lell Lhe browser whaL Lo do
@hls !avaScrlpL sLaLemenL Lells Lhe browser Lo wrlLe ello uolly Lo Lhe web page
documenLwrlLe(ello uolly)
lL ls normal Lo add a semlcolon aL Lhe end of each execuLable sLaLemenL ,osL people Lhlnk Lhls ls a good programmlng pracLlce and mosL ofLen
you wlll see Lhls ln !avaScrlpL examples on Lhe web
@he semlcolon ls opLlonal (accordlng Lo Lhe !avaScrlpL sLandard) and Lhe browser ls supposed Lo lnLerpreL Lhe end of Lhe llne as Lhe end of Lhe
sLaLemenL 8ecause of Lhls you wlll ofLen see examples wlLhouL Lhe semlcolon aL Lhe end
Note uslng semlcolons makes lL posslble Lo wrlLe mulLlple sLaLemenLs on one llne
!avaScrlpL Code
!avaScrlpL code (or [usL !avaScrlpL) ls a sequence of !avaScrlpL sLaLemenLs
Lach sLaLemenL ls execuLed by Lhe browser ln Lhe sequence Lhey are wrlLLen
@hls example wlll wrlLe a headlng and Lwo paragraphs Lo a web page
Lxample
scrlpL LypeLexL/[avascrlpL
documenLwrlLe(h1@hls ls a headlng/h1)
documenLwrlLe(p@hls ls a paragraph/p)
documenLwrlLe(p@hls ls anoLher paragraph/p)
/scrlpL

1ry |t yourse|f

!avaScrlpL 8locks
!avaScrlpL sLaLemenLs can be grouped LogeLher ln blocks
8locks sLarL wlLh a lefL curly brackeL and end wlLh a rlghL curly brackeL
@he purpose of a block ls Lo make Lhe sequence of sLaLemenLs execuLe LogeLher
@hls example wlll wrlLe a headlng and Lwo paragraphs Lo a web page
Lxample
scrlpL LypeLexL/[avascrlpL

documenLwrlLe(h1@hls ls a headlng/h1)
documenLwrlLe(p@hls ls a paragraph/p)
documenLwrlLe(p@hls ls anoLher paragraph/p)

/scrlpL

1ry |t yourse|f
@he example above ls noL very useful lL [usL demonsLraLes Lhe use of a block normally a block ls used Lo group sLaLemenLs LogeLher ln a funcLlon
or ln a condlLlon (where a group of sLaLemenLs should be execuLed lf a condlLlon ls meL)
?ou wlll learn more abouL funcLlons and condlLlons ln laLer chapLers

!avaScrlpL CommenLs
!avaScrlpL commenLs can be used Lo make Lhe code more readable
!avaScrlpL CommenLs
CommenLs can be added Lo explaln Lhe !avaScrlpL or Lo make Lhe code more readable
Slngle llne commenLs sLarL wlLh //
@he followlng example uses slngle llne commenLs Lo explaln Lhe code
Lxample
scrlpL LypeLexL/[avascrlpL
// WrlLe a headlng
documenLwrlLe(h1@hls ls a headlng/h1)
// WrlLe Lwo paragraphs
documenLwrlLe(p@hls ls a paragraph/p)
documenLwrlLe(p@hls ls anoLher paragraph/p)
/scrlpL

1ry |t yourse|f

!avaScrlpL ,ulLllne CommenLs
,ulLl llne commenLs sLarL wlLh /* and end wlLh */
@he followlng example uses a mulLl llne commenL Lo explaln Lhe code
Lxample
scrlpL LypeLexL/[avascrlpL
/*
@he code below wlll wrlLe
one headlng and Lwo paragraphs
*/
documenLwrlLe(h1@hls ls a headlng/h1)
documenLwrlLe(p@hls ls a paragraph/p)
documenLwrlLe(p@hls ls anoLher paragraph/p)
/scrlpL

1ry |t yourse|f

uslng CommenLs Lo revenL LxecuLlon
ln Lhe followlng example Lhe commenL ls used Lo prevenL Lhe execuLlon of a slngle code llne (can be sulLable for debugglng)
Lxample
scrlpL LypeLexL/[avascrlpL
//documenLwrlLe(h1@hls ls a headlng/h1)
documenLwrlLe(p@hls ls a paragraph/p)
documenLwrlLe(p@hls ls anoLher paragraph/p)
/scrlpL

1ry |t yourse|f
ln Lhe followlng example Lhe commenL ls used Lo prevenL Lhe execuLlon of a code block (can be sulLable for debugglng)
Lxample
scrlpL LypeLexL/[avascrlpL
/*
documenLwrlLe(h1@hls ls a headlng/h1)
documenLwrlLe(p@hls ls a paragraph/p)
documenLwrlLe(p@hls ls anoLher paragraph/p)
*/
/scrlpL

1ry |t yourse|f

uslng CommenLs aL Lhe Lnd of a lne
ln Lhe followlng example Lhe commenL ls placed aL Lhe end of a code llne
Lxample
scrlpL LypeLexL/[avascrlpL
documenLwrlLe(ello) // WrlLe ello
documenLwrlLe( uolly!) // WrlLe uolly!
/scrlpL


!avaScrlpL varlables
varlables are conLalners for sLorlng lnformaLlon
uo ?ou 8emember Algebra lrom School?
uo you remember algebra from school? x3 y6 zx+y
uo you remember LhaL a leLLer (llke x) could be used Lo hold a value (llke 3) and LhaL you could use Lhe lnformaLlon above Lo calculaLe Lhe value of
z Lo be 11?
@hese leLLers are called var|ab|es and varlables can be used Lo hold values (x3) or expresslons (zx+y)
!avaScrlpL varlables
As wlLh algebra !avaScrlpL varlables are used Lo hold values or expresslons
A varlable can have a shorL name llke x or a more descrlpLlve name llke carname
8ules for !avaScrlpL varlable names
O varlable names are case senslLlve (y and ? are Lwo dlfferenL varlables)
O varlable names musL begln wlLh a leLLer or Lhe underscore characLer
Note 8ecause !avaScrlpL ls casesenslLlve varlable names are casesenslLlve
Lxample
A varlables value can change durlng Lhe execuLlon of a scrlpL ?ou can refer Lo a varlable by lLs name Lo dlsplay or change lLs value
ueclarlng (CreaLlng) !avaScrlpL varlables
CreaLlng varlables ln !avaScrlpL ls mosL ofLen referred Lo as declarlng varlables
?ou declare !avaScrlpL varlables wlLh Lhe var keyword
var x
var carname
AfLer Lhe declaraLlon shown above Lhe varlables are empLy (Lhey have no values yeL)
owever you can also asslgn values Lo Lhe varlables when you declare Lhem
var x3
var carnamevolvo
AfLer Lhe execuLlon of Lhe sLaLemenLs above Lhe varlable x wlll hold Lhe value S and carname wlll hold Lhe value Vo|vo
Note When you asslgn a LexL value Lo a varlable use quoLes around Lhe value
Note lf you redeclare a !avaScrlpL varlable lL wlll noL lose lLs value
ocal !avaScrlpL varlables
A varlable declared wlLhln a !avaScrlpL funcLlon becomes LCCAL and can only be accessed wlLhln LhaL funcLlon (Lhe varlable has local scope)
?ou can have local varlables wlLh Lhe same name ln dlfferenL funcLlons because local varlables are only recognlzed by Lhe funcLlon ln whlch Lhey
are declared
ocal varlables are desLroyed when you exlL Lhe funcLlon
?ou wlll learn more abouL funcLlons ln a laLer chapLer of Lhls LuLorlal
Clobal !avaScrlpL varlables
varlables declared ouLslde a funcLlon become GLC8AL and all scrlpLs and funcLlons on Lhe web page can access lL
Clobal varlables are desLroyed when you close Lhe page
lf you declare a varlable wlLhouL uslng var Lhe varlable always becomes GLC8AL
Asslgnlng values Lo undeclared !avaScrlpL varlables
lf you asslgn values Lo varlables LhaL have noL yeL been declared Lhe varlables wlll auLomaLlcally be declared as global varlables
@hese sLaLemenLs
x3
carnamevolvo
wlll declare Lhe varlables x and carname as global varlables (lf Lhey donL already exlsL)
!avaScrlpL ArlLhmeLlc
As wlLh algebra you can do arlLhmeLlc operaLlons wlLh !avaScrlpL varlables
yx3
zy+3
?ou wlll learn more abouL Lhe operaLors LhaL can be used ln Lhe nexL chapLer of Lhls LuLorlal

!avaScrlpL CperaLors
ls used Lo asslgn values
+ ls used Lo add values
@he asslgnmenL operaLor ls used Lo asslgn values Lo !avaScrlpL varlables
@he arlLhmeLlc operaLor + ls used Lo add values LogeLher
y3
z2
xy+z
@he value of x afLer Lhe execuLlon of Lhe sLaLemenLs above ls 7
!avaScrlpL ArlLhmeLlc CperaLors
ArlLhmeLlc operaLors are used Lo perform arlLhmeLlc beLween varlables and/or values
Clven LhaL yS Lhe Lable below explalns Lhe arlLhmeLlc operaLors
Cperator Descr|pt|on Lxamp|e kesu|t
+ AddlLlon xy+2 x7 y3
SubLracLlon xy2 x3 y3
* ,ulLlpllcaLlon xy*2 x10 y3
/ ulvlslon xy/2 x23 y3
,odulus (dlvlslon remalnder) xy2 x1 y3
++ lncremenL x++y x6 y6
xy++ x3 y6
uecremenL xy x4 y4
xy x3 y4

!avaScrlpL AsslgnmenL CperaLors
AsslgnmenL operaLors are used Lo asslgn values Lo !avaScrlpL varlables
Clven LhaL x and yS Lhe Lable below explalns Lhe asslgnmenL operaLors
Cperator Lxamp|e Same As kesu|t
xy x3
+ x+y xx+y x13
xy xxy x3
* x*y xx*y x30
/ x/y xx/y x2
xy xxy x0

@he + CperaLor used on SLrlngs
@he + operaLor can also be used Lo add sLrlng varlables or LexL values LogeLher
@o add Lwo or more sLrlng varlables LogeLher use Lhe + operaLor
LxL1WhaL a very
LxL2nlce day
LxL3LxL1+LxL2
AfLer Lhe execuLlon of Lhe sLaLemenLs above Lhe varlable LxL3 conLalns WhaL a verynlce day
@o add a space beLween Lhe Lwo sLrlngs lnserL a space lnLo one of Lhe sLrlngs
LxL1WhaL a very
LxL2nlce day
LxL3LxL1+LxL2
or lnserL a space lnLo Lhe expresslon
LxL1WhaL a very
LxL2nlce day
LxL3LxL1+ +LxL2
AfLer Lhe execuLlon of Lhe sLaLemenLs above Lhe varlable LxL3 conLalns
WhaL a very nlce day
Addlng SLrlngs and numbers
@he rule ls If you add a number and a str|ng the resu|t w||| be a str|ng!
Lxample
x3+3
documenLwrlLe(x)

x3+3
documenLwrlLe(x)

x3+3
documenLwrlLe(x)

x3+3
documenLwrlLe(x)


!avaScrlpL Comparlson and oglcal CperaLors

Comparlson and oglcal operaLors are used Lo LesL for Lrue or false
Comparlson CperaLors
Comparlson operaLors are used ln loglcal sLaLemenLs Lo deLermlne equallLy or dlfference beLween varlables or values
Clven LhaL xS Lhe Lable below explalns Lhe comparlson operaLors
Cperator Descr|pt|on Lxamp|e
ls equal Lo x8 ls false
x3 ls Lrue
ls exacLly equal Lo (value and Lype) x3 ls Lrue
x3 ls false
! ls noL equal x!8 ls Lrue
ls greaLer Lhan x8 ls false
ls less Lhan x8 ls Lrue
ls greaLer Lhan or equal Lo x8 ls false
ls less Lhan or equal Lo x8 ls Lrue

ow Can lL be used
Comparlson operaLors can be used ln condlLlonal sLaLemenLs Lo compare values and Lake acLlon dependlng on Lhe resulL
lf (age18) documenLwrlLe(@oo young)
?ou wlll learn more abouL Lhe use of condlLlonal sLaLemenLs ln Lhe nexL chapLer of Lhls LuLorlal
oglcal CperaLors
oglcal operaLors are used Lo deLermlne Lhe loglc beLween varlables or values
Clven LhaL x and y Lhe Lable below explalns Lhe loglcal operaLors
Cperator Descr|pt|on Lxamp|e
and (x 10 y 1) ls Lrue
|| or (x3 || y3) ls false
! noL !(xy) ls Lrue

CondlLlonal CperaLor
!avaScrlpL also conLalns a condlLlonal operaLor LhaL asslgns a value Lo a varlable based on some condlLlon
SynLax
varlablename(condlLlon)?value1value2
Lxample
greeLlng(vlslLor8LS)?uear resldenL uear
lf Lhe varlable v|s|tor has Lhe value of 8LS Lhen Lhe varlable greet|ng wlll be asslgned Lhe value uear resldenL else lL wlll be asslgned uear

!avaScrlpL lfLlse SLaLemenLs
CondlLlonal sLaLemenLs are used Lo perform dlfferenL acLlons based on dlfferenL condlLlons
CondlLlonal SLaLemenLs
very ofLen when you wrlLe code you wanL Lo perform dlfferenL acLlons for dlfferenL declslons ?ou can use condlLlonal sLaLemenLs ln your code Lo
do Lhls
ln !avaScrlpL we have Lhe followlng condlLlonal sLaLemenLs
O |f statement use Lhls sLaLemenL Lo execuLe some code only lf a speclfled condlLlon ls Lrue
O |fe|se statement use Lhls sLaLemenL Lo execuLe some code lf Lhe condlLlon ls Lrue and anoLher code lf Lhe condlLlon ls false
O |fe|se |fe|se statement use Lhls sLaLemenL Lo selecL one of many blocks of code Lo be execuLed
O sw|tch statement use Lhls sLaLemenL Lo selecL one of many blocks of code Lo be execuLed
lf SLaLemenL
use Lhe lf sLaLemenL Lo execuLe some code only lf a speclfled condlLlon ls Lrue
SynLax
lf (cooJltloo)

coJetoeexecoteJlfcooJltloolsttoe

noLe LhaL lf ls wrlLLen ln lowercase leLLers uslng uppercase leLLers (ll) wlll generaLe a !avaScrlpL error!
Lxample
scrlpL LypeLexL/[avascrlpL
//WrlLe a Cood mornlng greeLlng lf
//Lhe Llme ls less Lhan 10

var dnew uaLe()
var LlmedgeLours()

lf (Llme10)

documenLwrlLe(bCood mornlng/b)

/scrlpL

1ry |t yourse|f
noLlce LhaL Lhere ls no else ln Lhls synLax ?ou Lell Lhe browser Lo execuLe some code on|y |f the spec|f|ed cond|t|on |s true
lfelse SLaLemenL
use Lhe lfelse sLaLemenL Lo execuLe some code lf a condlLlon ls Lrue and anoLher code lf Lhe condlLlon ls noL Lrue
SynLax
lf (cooJltloo)

coJetoeexecoteJlfcooJltloolsttoe

else

coJetoeexecoteJlfcooJltloolsootttoe


Lxample
scrlpL LypeLexL/[avascrlpL
//lf Lhe Llme ls less Lhan 10 you wlll geL a Cood mornlng greeLlng
//CLherwlse you wlll geL a Cood day greeLlng

var d new uaLe()
var Llme dgeLours()

lf (Llme 10)

documenLwrlLe(Cood mornlng!)

else

documenLwrlLe(Cood day!)

/scrlpL

1ry |t yourse|f

lfelse lfelse SLaLemenL
use Lhe lfelse lfelse sLaLemenL Lo selecL one of several blocks of code Lo be execuLed
SynLax
lf (cooJltloo1)

coJetoeexecoteJlfcooJltloo1lsttoe

else lf (cooJltloo2)

coJetoeexecoteJlfcooJltloo2lsttoe

else

coJetoeexecoteJlfoeltbetcooJltloo1ootcooJltloo2lsttoe


Lxample
scrlpL LypeLexL/[avascrlpL
var d new uaLe()
var Llme dgeLours()
lf (Llme10)

documenLwrlLe(bCood mornlng/b)

else lf (Llme10 Llme16)

documenLwrlLe(bCood day/b)

else

documenLwrlLe(bello World!/b)

/scrlpL

1ry |t yourse|f

!avaScrlpL SwlLch SLaLemenL
CondlLlonal sLaLemenLs are used Lo perform dlfferenL acLlons based on dlfferenL condlLlons
@he !avaScrlpL SwlLch SLaLemenL
use Lhe swlLch sLaLemenL Lo selecL one of many blocks of code Lo be execuLed
SynLax
swlLch(n)

case 1
execotecoJeock1
break
case 2
execotecoJeock2
break
defaulL
coJetoeexecoteJlfolsJlffeteotftomcose1ooJ2

@hls ls how lL works llrsL we have a slngle expresslon o (mosL ofLen a varlable) LhaL ls evaluaLed once @he value of Lhe expresslon ls Lhen
compared wlLh Lhe values for each case ln Lhe sLrucLure lf Lhere ls a maLch Lhe block of code assoclaLed wlLh LhaL case ls execuLed use break Lo
prevenL Lhe code from runnlng lnLo Lhe nexL case auLomaLlcally
Lxample
scrlpL LypeLexL/[avascrlpL
//?ou wlll recelve a dlfferenL greeLlng based
//on whaL day lL ls noLe LhaL Sunday0
//,onday1 @uesday2 eLc

var dnew uaLe()
var LheuaydgeLuay()
swlLch (Lheuay)

case 3
documenLwrlLe(llnally lrlday)
break
case 6
documenLwrlLe(Super SaLurday)
break
case 0
documenLwrlLe(Sleepy Sunday)
break
defaulL
documenLwrlLe(lm looklng forward Lo Lhls weekend!)

/scrlpL


!avaScrlpL opup 8oxes
!avaScrlpL has Lhree klnd of popup boxes AlerL box Conflrm box and rompL box
AlerL 8ox
An alerL box ls ofLen used lf you wanL Lo make sure lnformaLlon comes Lhrough Lo Lhe user
When an alerL box pops up Lhe user wlll have Lo cllck Ck Lo proceed
Syntax
alerL(sometext)

Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon show_alerL()

alerL(l am an alerL box!)

/scrlpL
/head
body

lnpuL LypebuLLon oncllckshow_alerL() valueShow alerL box /

/body
/hLml

1ry |t yourse|f

Conflrm 8ox
A conflrm box ls ofLen used lf you wanL Lhe user Lo verlfy or accepL someLhlng
When a conflrm box pops up Lhe user wlll have Lo cllck elLher Ck or Cancel Lo proceed
lf Lhe user cllcks Ck Lhe box reLurns Lrue lf Lhe user cllcks Cancel Lhe box reLurns false
Syntax
conflrm(sometext)

Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon show_conflrm()

var rconflrm(ress a buLLon)
lf (rLrue)

alerL(?ou pressed Ck!)

else

alerL(?ou pressed Cancel!)


/scrlpL
/head
body

lnpuL LypebuLLon oncllckshow_conflrm() valueShow conflrm box /

/body
/hLml

1ry |t yourse|f

rompL 8ox
A prompL box ls ofLen used lf you wanL Lhe user Lo lnpuL a value before enLerlng a page
When a prompL box pops up Lhe user wlll have Lo cllck elLher Ck or Cancel Lo proceed afLer enLerlng an lnpuL value
lf Lhe user cllcks Ck Lhe box reLurns Lhe lnpuL value lf Lhe user cllcks Cancel Lhe box reLurns null
Syntax
prompL(sometextJefootvooe)

Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon show_prompL()

var nameprompL(lease enLer your namearry oLLer)
lf (name!null name!)

documenLwrlLe(ello + name + ! ow are you Loday?)


/scrlpL
/head
body

lnpuL LypebuLLon oncllckshow_prompL() valueShow prompL box /

/body
/hLml


!avaScrlpL luncLlons
A funcLlon wlll be execuLed by an evenL or by a call Lo Lhe funcLlon
!avaScrlpL luncLlons
@o keep Lhe browser from execuLlng a scrlpL when Lhe page loads you can puL your scrlpL lnLo a funcLlon
A funcLlon conLalns code LhaL wlll be execuLed by an evenL or by a call Lo Lhe funcLlon
?ou may call a funcLlon from anywhere wlLhln a page (or even from oLher pages lf Lhe funcLlon ls embedded ln an exLernal [s flle)
luncLlons can be deflned boLh ln Lhe head and ln Lhe body secLlon of a documenL owever Lo assure LhaL a funcLlon ls read/loaded by Lhe
browser before lL ls called lL could be wlse Lo puL funcLlons ln Lhe head secLlon
ow Lo ueflne a luncLlon
SynLax
funcLlon fooctloooome(vot1vot2vot\)

somecoJe

@he parameLers var1 var2 eLc are varlables or values passed lnLo Lhe funcLlon @he and Lhe deflnes Lhe sLarL and end of Lhe funcLlon
Note A funcLlon wlLh no parameLers musL lnclude Lhe parenLheses () afLer Lhe funcLlon name
Note uo noL forgeL abouL Lhe lmporLance of caplLals ln !avaScrlpL! @he word fooctloo musL be wrlLLen ln lowercase leLLers oLherwlse a !avaScrlpL
error occurs! Also noLe LhaL you musL call a funcLlon wlLh Lhe exacL same caplLals as ln Lhe funcLlon name
!avaScrlpL luncLlon Lxample
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon dlsplaymessage()

alerL(ello World!)

/scrlpL
/head

body
form
lnpuL LypebuLLon valueCllck me! oncllckdlsplaymessage() /
/form
/body
/hLml

1ry |t yourse|f
lf Lhe llne alerL(ello world!!) ln Lhe example above had noL been puL wlLhln a funcLlon lL would have been execuLed as soon as Lhe page was
loaded now Lhe scrlpL ls noL execuLed before a user hlLs Lhe lnpuL buLLon @he funcLlon dlsplaymessage() wlll be execuLed lf Lhe lnpuL buLLon ls
cllcked
?ou wlll learn more abouL !avaScrlpL evenLs ln Lhe !S LvenLs chapLer
@he reLurn SLaLemenL
@he reLurn sLaLemenL ls used Lo speclfy Lhe value LhaL ls reLurned from Lhe funcLlon
So funcLlons LhaL are golng Lo reLurn a value musL use Lhe reLurn sLaLemenL
@he example below reLurns Lhe producL of Lwo numbers (a and b)
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon producL(ab)

reLurn a*b

/scrlpL
/head

body
scrlpL LypeLexL/[avascrlpL
documenLwrlLe(producL(43))
/scrlpL

/body
/hLml

1ry |t yourse|f

@he lfeLlme of !avaScrlpL varlables
lf you declare a varlable uslng var wlLhln a funcLlon Lhe varlable can only be accessed wlLhln LhaL funcLlon When you exlL Lhe funcLlon Lhe
varlable ls desLroyed @hese varlables are called local varlables ?ou can have local varlables wlLh Lhe same name ln dlfferenL funcLlons because
each ls recognlzed only by Lhe funcLlon ln whlch lL ls declared
lf you declare a varlable ouLslde a funcLlon all Lhe funcLlons on your page can access lL @he llfeLlme of Lhese varlables sLarLs when Lhey are
declared and ends when Lhe page ls closed

!avaScrlpL lor oop
oops execuLe a block of code a speclfled number of Llmes or whlle a speclfled condlLlon ls Lrue
!avaScrlpL oops
CfLen when you wrlLe code you wanL Lhe same block of code Lo run over and over agaln ln a row lnsLead of addlng several almosL equal llnes ln a
scrlpL we can use loops Lo perform a Lask llke Lhls
ln !avaScrlpL Lhere are Lwo dlfferenL klnd of loops
O for loops Lhrough a block of code a speclfled number of Llmes
O wh||e loops Lhrough a block of code whlle a speclfled condlLlon ls Lrue
@he for oop
@he for loop ls used when you know ln advance how many Llmes Lhe scrlpL should run
Syntax
for (votloestottvooevotloeeoJvooevotloevotloe+loctemeot)

coJetoeexecoteJ

Lxamp|e
@he example below deflnes a loop LhaL sLarLs wlLh l0 @he loop wlll conLlnue Lo run as long as | ls less Lhan or equal Lo 3 | wlll lncrease by 1 each
Llme Lhe loop runs
Note @he lncremenL parameLer could also be negaLlve and Lhe could be any comparlng sLaLemenL
Lxample
hLml
body
scrlpL LypeLexL/[avascrlpL
var l0
for (l0l3l++)

documenLwrlLe(@he number ls + l)
documenLwrlLe(br /)

/scrlpL
/body
/hLml

1ry |t yourse|f

!avaScrlpL Whlle oop
oops execuLe a block of code a speclfled number of Llmes or whlle a speclfled condlLlon ls Lrue
@he whlle oop
@he whlle loop loops Lhrough a block of code whlle a speclfled condlLlon ls Lrue
SynLax
whlle (votloeeoJvooe)

coJetoeexecoteJ

Note @he could be any comparlng operaLor
Lxample
@he example below deflnes a loop LhaL sLarLs wlLh l0 @he loop wlll conLlnue Lo run as long as | ls less Lhan or equal Lo 3 | wlll lncrease by 1 each
Llme Lhe loop runs
Lxample
hLml
body
scrlpL LypeLexL/[avascrlpL
var l0
whlle (l3)

documenLwrlLe(@he number ls + l)
documenLwrlLe(br /)
l++

/scrlpL
/body
/hLml

1ry |t yourse|f

@he dowhlle oop
@he dowhlle loop ls a varlanL of Lhe whlle loop @hls loop wlll execuLe Lhe block of code CnCL and Lhen lL wlll repeaL Lhe loop as long as Lhe
speclfled condlLlon ls Lrue
SynLax
do

coJetoeexecoteJ

whlle (votloeeoJvooe)
Lxample
@he example below uses a dowhlle loop @he dowhlle loop wlll always be execuLed aL leasL once even lf Lhe condlLlon ls false because Lhe
sLaLemenLs are execuLed before Lhe condlLlon ls LesLed
Lxample
hLml
body
scrlpL LypeLexL/[avascrlpL
var l0
do

documenLwrlLe(@he number ls + l)
documenLwrlLe(br /)
l++

whlle (l3)
/scrlpL
/body
/hLml


!avaScrlpL 8reak and ConLlnue SLaLemenLs
@he break SLaLemenL
@he break sLaLemenL wlll break Lhe loop and conLlnue execuLlng Lhe code LhaL follows afLer Lhe loop (lf any)
Lxample
hLml
body
scrlpL LypeLexL/[avascrlpL
var l0
for (l0l10l++)

lf (l3)

break

documenLwrlLe(@he number ls + l)
documenLwrlLe(br /)

/scrlpL
/body
/hLml

1ry |t yourse|f

@he conLlnue SLaLemenL
@he conLlnue sLaLemenL wlll break Lhe currenL loop and conLlnue wlLh Lhe nexL value
Lxample
hLml
body
scrlpL LypeLexL/[avascrlpL
var l0
for (l0l10l++)

lf (l3)

conLlnue

documenLwrlLe(@he number ls + l)
documenLwrlLe(br /)

/scrlpL
/body
/hLml


!avaScrlpL lorln SLaLemenL
!avaScrlpL lorln SLaLemenL
@he forln sLaLemenL loops Lhrough Lhe properLles of an ob[ecL
SynLax
for (votloe ln oect)

coJetoeexecoteJ

Note @he code ln Lhe body of Lhe forln loop ls execuLed once for each properLy
Lxample
ooplng Lhrough Lhe properLles of an ob[ecL
Lxample
var personfname!ohnlnameuoeage23

for (x ln person)

documenLwrlLe(personx + )



!avaScrlpL LvenLs
LvenLs are acLlons LhaL can be deLecLed by !avaScrlpL
AcLlng Lo an LvenL
@he example below dlsplays Lhe daLe when a buLLon ls cllcked
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon dlsplayuaLe()

documenLgeLLlemenL8yld(demo)lnner@,uaLe()

/scrlpL
/head
body
h1,y llrsL Web age/h1
p lddemo/p
buLLon LypebuLLon oncllckdlsplayuaLe()ulsplay uaLe/buLLon
/body
/hLml

1ry |t yourse|f

LvenLs
8y uslng !avaScrlpL we have Lhe ablllLy Lo creaLe dynamlc web pages LvenLs are acLlons LhaL can be deLecLed by !avaScrlpL
Lvery elemenL on a web page has cerLaln evenLs whlch can Lrlgger a !avaScrlpL lor example we can use Lhe onCllck evenL of a buLLon elemenL Lo
lndlcaLe LhaL a funcLlon wlll run when a user cllcks on Lhe buLLon We deflne Lhe evenLs ln Lhe @, Lags
Lxamples of evenLs
O A mouse cllck
O A web page or an lmage loadlng
O ,ouslng over a hoL spoL on Lhe web page
O SelecLlng an lnpuL fleld ln an @, form
O SubmlLLlng an @, form
O A keysLroke
Note LvenLs are normally used ln comblnaLlon wlLh funcLlons and Lhe funcLlon wlll noL be execuLed before Lhe evenL occurs!
lor a compleLe reference of Lhe evenLs recognlzed by !avaScrlpL go Lo our compleLe LvenL reference

onoad and onunload
@he onoad and onunload evenLs are Lrlggered when Lhe user enLers or leaves Lhe page
@he onoad evenL ls ofLen used Lo check Lhe vlslLors browser Lype and browser verslon and load Lhe proper verslon of Lhe web page based on Lhe
lnformaLlon
8oLh Lhe onoad and onunload evenLs are also ofLen used Lo deal wlLh cookles LhaL should be seL when a user enLers or leaves a page lor
example you could have a popup asklng for Lhe users name upon hls flrsL arrlval Lo your page @he name ls Lhen sLored ln a cookle nexL Llme Lhe
vlslLor arrlves aL your page you could have anoLher popup saylng someLhlng llke Welcome !ohn uoe!
onlocus on8lur and onChange
@he onlocus on8lur and onChange evenLs are ofLen used ln comblnaLlon wlLh valldaLlon of form flelds
8elow ls an example of how Lo use Lhe onChange evenL @he checkLmall() funcLlon wlll be called whenever Lhe user changes Lhe conLenL of Lhe
fleld
lnpuL LypeLexL slze30 ldemall onchangecheckLmall()

onSubmlL
@he onSubmlL evenL ls used Lo valldaLe A form flelds before submlLLlng lL
8elow ls an example of how Lo use Lhe onSubmlL evenL @he checklorm() funcLlon wlll be called when Lhe user cllcks Lhe submlL buLLon ln Lhe form
lf Lhe fleld values are noL accepLed Lhe submlL should be cancelled @he funcLlon checklorm() reLurns elLher Lrue or false lf lL reLurns Lrue Lhe form
wlll be submlLLed oLherwlse Lhe submlL wlll be cancelled
form meLhodposL acLlonxxxhLm onsubmlLreLurn checklorm()

on,ouseCver
@he onmouseover evenL can be used Lo Lrlgger a funcLlon when Lhe user mouses over an @, elemenL
Lxample

,ouse over Lhe sun and Lhe planeLs and see Lhe dlfferenL descrlpLlons


avaScrlpL @ryCaLch SLaLemenL
@he LrycaLch sLaLemenL allows you Lo LesL a block of code for errors
!avaScrlpL CaLchlng Lrrors
When browslng Web pages on Lhe lnLerneL we all have seen a !avaScrlpL alerL box Lelllng us Lhere ls a runLlme error and asklng uo you wlsh Lo
debug? Lrror message llke Lhls may be useful for developers buL noL for users When users see errors Lhey ofLen leave Lhe Web page
@hls chapLer wlll Leach you how Lo caLch and handle !avaScrlpL error messages so you donL lose your audlence
@he LrycaLch SLaLemenL
@he LrycaLch sLaLemenL allows you Lo LesL a block of code for errors @he Lry block conLalns Lhe code Lo be run and Lhe caLch block conLalns Lhe
code Lo be execuLed lf an error occurs
SynLax
Lry

//8un some code here

caLch(err)

//andle errors here

noLe LhaL LrycaLch ls wrlLLen ln lowercase leLLers uslng uppercase leLLers wlll generaLe a !avaScrlpL error!
Lxamples
@he example below ls supposed Lo alerL Welcome guesL! when Lhe buLLon ls cllcked owever Lheres a Lypo ln Lhe message() funcLlon alerL() ls
mlsspelled as adddlerL() A !avaScrlpL error occurs @he caLch block caLches Lhe error and execuLes a cusLom code Lo handle lL @he code dlsplays a
cusLom error message lnformlng Lhe user whaL happened
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
var LxL
funcLlon message()

Lry

adddlerL(Welcome guesL!)

caLch(err)

LxL@here was an error on Lhls pagenn
LxL+Lrror descrlpLlon + errdescrlpLlon + nn
LxL+Cllck Ck Lo conLlnuenn
alerL(LxL)


/scrlpL
/head

body
lnpuL LypebuLLon valuevlew message oncllckmessage() /
/body

/hLml

1ry |t yourse|f
@he nexL example uses a conflrm box Lo dlsplay a cusLom message Lelllng users Lhey can cllck Ck Lo conLlnue vlewlng Lhe page or cllck Cancel Lo go
Lo Lhe homepage lf Lhe conflrm meLhod reLurns false Lhe user cllcked Cancel and Lhe code redlrecLs Lhe user lf Lhe conflrm meLhod reLurns Lrue
Lhe code does noLhlng
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
var LxL
funcLlon message()

Lry

adddlerL(Welcome guesL!)

caLch(err)

LxL@here was an error on Lhls pagenn
LxL+Cllck Ck Lo conLlnue vlewlng Lhls pagen
LxL+or Cancel Lo reLurn Lo Lhe home pagenn
lf(!conflrm(LxL))

documenLlocaLlonhrefhLLp//wwww3schoolscom/



/scrlpL
/head

body
lnpuL LypebuLLon valuevlew message oncllckmessage() /
/body

/hLml

1ry |t yourse|f

@he Lhrow SLaLemenL
@he Lhrow sLaLemenL can be used LogeLher wlLh Lhe LrycaLch sLaLemenL Lo creaLe an excepLlon for Lhe error earn abouL Lhe Lhrow sLaLemenL ln
Lhe nexL chapLer

!avaScrlpL @hrow SLaLemenL
@he Lhrow sLaLemenL allows you Lo creaLe an excepLlon
@he @hrow SLaLemenL
@he Lhrow sLaLemenL allows you Lo creaLe an excepLlon lf you use Lhls sLaLemenL LogeLher wlLh Lhe LrycaLch sLaLemenL you can conLrol program
flow and generaLe accuraLe error messages
SynLax
Lhrow exceptloo
@he excepLlon can be a sLrlng lnLeger 8oolean or an ob[ecL
noLe LhaL tbtow ls wrlLLen ln lowercase leLLers uslng uppercase leLLers wlll generaLe a !avaScrlpL error!
Lxample
@he example below deLermlnes Lhe value of a varlable called x lf Lhe value of x ls hlgher Lhan 10 lower Lhan 0 or noL a number we are golng Lo
Lhrow an error @he error ls Lhen caughL by Lhe caLch argumenL and Lhe proper error message ls dlsplayed
Lxample
hLml
body
scrlpL LypeLexL/[avascrlpL
var xprompL(LnLer a number beLween 0 and 10)
Lry

lf(x10)

Lhrow Lrr1

else lf(x0)

Lhrow Lrr2

else lf(lsnan(x))

Lhrow Lrr3


caLch(er)

lf(erLrr1)

alerL(Lrror! @he value ls Loo hlgh)

lf(erLrr2)

alerL(Lrror! @he value ls Loo low)

lf(erLrr3)

alerL(Lrror! @he value ls noL a number)


/scrlpL
/body
/hLml


!avaScrlpL Speclal CharacLers
ln !avaScrlpL you can add speclal characLers Lo a LexL sLrlng by uslng Lhe backslash slgn
lnserL Speclal CharacLers
@he backslash () ls used Lo lnserL aposLrophes new llnes quoLes and oLher speclal characLers lnLo a LexL sLrlng
ook aL Lhe followlng !avaScrlpL code
var LxLWe are Lhe socalled vlklngs from Lhe norLh
documenLwrlLe(LxL)
ln !avaScrlpL a sLrlng ls sLarLed and sLopped wlLh elLher slngle or double quoLes @hls means LhaL Lhe sLrlng above wlll be chopped Lo We are Lhe
socalled
@o solve Lhls problem you musL place a backslash () before each double quoLe ln vlklng @hls Lurns each double quoLe lnLo a sLrlng llLeral
var LxLWe are Lhe socalled vlklngs from Lhe norLh
documenLwrlLe(LxL)
!avaScrlpL wlll now ouLpuL Lhe proper LexL sLrlng We are Lhe socalled vlklngs from Lhe norLh
@he Lable below llsLs oLher speclal characLers LhaL can be added Lo a LexL sLrlng wlLh Lhe backslash slgn
Code Cutputs
slngle quoLe
double quoLe
backslash
n new llne
r carrlage reLurn
L Lab
b backspace
f form feed

!avaScrlpL Culdellnes
Some oLher lmporLanL Lhlngs Lo know when scrlpLlng wlLh !avaScrlpL
!avaScrlpL ls Case SenslLlve
A funcLlon named myfuncLlon ls noL Lhe same as myluncLlon and a varlable named myvar ls noL Lhe same as myvar
!avaScrlpL ls case senslLlve Lherefore waLch your caplLallzaLlon closely when you creaLe or call varlables ob[ecLs and funcLlons
WhlLe Space
!avaScrlpL lgnores exLra spaces ?ou can add whlLe space Lo your scrlpL Lo make lL more readable @he followlng llnes are equlvalenL
var nameege
var name ege


8reak up a Code lne
?ou can break up a code llne w|th|n a text str|ng wlLh a backslash @he example below wlll be dlsplayed properly
documenLwrlLe(ello
World!)
owever you cannoL break up a code llne llke Lhls
documenLwrlLe
(ello World!)

!avaScrlpL Cb[ecLs lnLroducLlon
!avaScrlpL ls an Cb[ecL CrlenLed rogrammlng (CC) language
An CC language allows you Lo deflne your own ob[ecLs and make your own varlable Lypes
Cb[ecL CrlenLed rogrammlng
!avaScrlpL ls an Cb[ecL CrlenLed rogrammlng (CC) language An CC language allows you Lo deflne your own ob[ecLs and make your own
varlable Lypes
owever creaLlng your own ob[ecLs wlll be explalned laLer ln Lhe Advanced !avaScrlpL secLlon We wlll sLarL by looklng aL Lhe bullLln !avaScrlpL
ob[ecLs and how Lhey are used @he nexL pages wlll explaln each bullLln !avaScrlpL ob[ecL ln deLall
noLe LhaL an ob[ecL ls [usL a speclal klnd of daLa An ob[ecL has properLles and meLhods
roperLles
roperLles are Lhe values assoclaLed wlLh an ob[ecL
ln Lhe followlng example we are uslng Lhe lengLh properLy of Lhe SLrlng ob[ecL Lo reLurn Lhe number of characLers ln a sLrlng
scrlpL LypeLexL/[avascrlpL
var LxLello World!
documenLwrlLe(LxLlengLh)
/scrlpL
@he ouLpuL of Lhe code above wlll be
12

,eLhods
,eLhods are Lhe acLlons LhaL can be performed on ob[ecLs
ln Lhe followlng example we are uslng Lhe LoupperCase() meLhod of Lhe SLrlng ob[ecL Lo dlsplay a LexL ln uppercase leLLers
scrlpL LypeLexL/[avascrlpL
var sLrello world!
documenLwrlLe(sLrLoupperCase())
/scrlpL
@he ouLpuL of Lhe code above wlll be
LC WC8u!

!avaScrlpL SLrlng Cb[ecL
@he SLrlng ob[ecL ls used Lo manlpulaLe a sLored plece of LexL
8eLurn Lhe lengLh of a sLrlng
ow Lo reLurn Lhe lengLh of a sLrlng
SLyle sLrlngs
ow Lo sLyle sLrlngs
@he LoowerCase() and LoupperCase() meLhods
ow Lo converL a sLrlng Lo lowercase or uppercase leLLers
@he maLch() meLhod
ow Lo search for a speclfled value wlLhln a sLrlng
8eplace characLers ln a sLrlng replace()
ow Lo replace a speclfled value wlLh anoLher value ln a sLrlng
@he lndexCf() meLhod
ow Lo reLurn Lhe poslLlon of Lhe flrsL found occurrence of a speclfled value ln a sLrlng
CompleLe SLrlng Cb[ecL 8eference
lor a compleLe reference of all Lhe properLles and meLhods LhaL can be used wlLh Lhe SLrlng ob[ecL go Lo our compleLe SLrlng ob[ecL reference
@he reference conLalns a brlef descrlpLlon and examples of use for each properLy and meLhod!
SLrlng ob[ecL
@he SLrlng ob[ecL ls used Lo manlpulaLe a sLored plece of LexL
Lxamp|es of use
@he followlng example uses Lhe lengLh properLy of Lhe SLrlng ob[ecL Lo flnd Lhe lengLh of a sLrlng
var LxLello world!
documenLwrlLe(LxLlengLh)
@he code above wlll resulL ln Lhe followlng ouLpuL
12
@he followlng example uses Lhe LoupperCase() meLhod of Lhe SLrlng ob[ecL Lo converL a sLrlng Lo uppercase leLLers
var LxLello world!
documenLwrlLe(LxLLoupperCase())
@he code above wlll resulL ln Lhe followlng ouLpuL
LC WC8u!

!avaScrlpL uaLe Cb[ecL
@he uaLe ob[ecL ls used Lo work wlLh daLes and Llmes
8eLurn Lodays daLe and Llme
ow Lo use Lhe uaLe() meLhod Lo geL Lodays daLe
geLlull?ear()
use geLlull?ear() Lo geL Lhe year
geL@lme()
geL@lme() reLurns Lhe number of mllllseconds slnce 01011970
seLlull?ear()
ow Lo use seLlull?ear() Lo seL a speclflc daLe
Lou@CSLrlng()
ow Lo use Lou@CSLrlng() Lo converL Lodays daLe (accordlng Lo u@C) Lo a sLrlng
geLuay()
use geLuay() and an array Lo wrlLe a weekday and noL [usL a number
ulsplay a clock
ow Lo dlsplay a clock on your web page
CompleLe uaLe Cb[ecL 8eference
lor a compleLe reference of all Lhe properLles and meLhods LhaL can be used wlLh Lhe uaLe ob[ecL go Lo our compleLe uaLe ob[ecL reference
@he reference conLalns a brlef descrlpLlon and examples of use for each properLy and meLhod!
CreaLe a uaLe Cb[ecL
@he uaLe ob[ecL ls used Lo work wlLh daLes and Llmes
uaLe ob[ecLs are creaLed wlLh Lhe uaLe() consLrucLor
@here are four ways of lnsLanLlaLlng a daLe
new uaLe() // currenL daLe and Llme
new uaLe(mllllseconds) //mllllseconds slnce 1970/01/01
new uaLe(daLeSLrlng)
new uaLe(year monLh day hours mlnuLes seconds mllllseconds)
,osL parameLers above are opLlonal noL speclfylng causes 0 Lo be passed ln
Cnce a uaLe ob[ecL ls creaLed a number of meLhods allow you Lo operaLe on lL ,osL meLhods allow you Lo geL and seL Lhe year monLh day hour
mlnuLe second and mllllseconds of Lhe ob[ecL uslng elLher local Llme or u@C (unlversal or C,@) Llme
All daLes are calculaLed ln mllllseconds from 01 !anuary 1970 000000 unlversal @lme (u@C) wlLh a day conLalnlng 86400000 mllllseconds
Some examples of lnsLanLlaLlng a daLe
var Loday new uaLe()
var d1 new uaLe(CcLober 13 1973 111300)
var d2 new uaLe(79324)
var d3 new uaLe(7932411330)

SeL uaLes
We can easlly manlpulaLe Lhe daLe by uslng Lhe meLhods avallable for Lhe uaLe ob[ecL
ln Lhe example below we seL a uaLe ob[ecL Lo a speclflc daLe (14Lh !anuary 2010)
var myuaLenew uaLe()
myuaLeseLlull?ear(2010014)
And ln Lhe followlng example we seL a uaLe ob[ecL Lo be 3 days lnLo Lhe fuLure
var myuaLenew uaLe()
myuaLeseLuaLe(myuaLegeLuaLe()+3)
Note lf addlng flve days Lo a daLe shlfLs Lhe monLh or year Lhe changes are handled auLomaLlcally by Lhe uaLe ob[ecL lLself!
Compare @wo uaLes
@he uaLe ob[ecL ls also used Lo compare Lwo daLes
@he followlng example compares Lodays daLe wlLh Lhe 14Lh !anuary 2100
var xnew uaLe()
xseLlull?ear(2100014)
var Loday new uaLe()

lf (xLoday)

alerL(@oday ls before 14Lh !anuary 2100)

else

alerL(@oday ls afLer 14Lh !anuary 2100)


!avaScrlpL Array Cb[ecL
@he Array ob[ecL ls used Lo sLore mulLlple values ln a slngle varlable
CreaLe an array
CreaLe an array asslgn values Lo lL and wrlLe Lhe values Lo Lhe ouLpuL
(?ou can flnd more examples aL Lhe boLLom of Lhls page)
CompleLe Array Cb[ecL 8eference
lor a compleLe reference of all Lhe properLles and meLhods LhaL can be used wlLh Lhe Array ob[ecL go Lo our compleLe Array ob[ecL reference
@he reference conLalns a brlef descrlpLlon and examples of use for each properLy and meLhod!
WhaL ls an Array?
An array ls a speclal varlable whlch can hold more Lhan one value aL a Llme
lf you have a llsL of lLems (a llsL of car names for example) sLorlng Lhe cars ln slngle varlables could look llke Lhls
var car1Saab
var car2volvo
var car38,W
owever whaL lf you wanL Lo loop Lhrough Lhe cars and flnd a speclflc one? And whaL lf you had noL 3 cars buL 300?
@he besL soluLlon here ls Lo use an array!
An array can hold all your varlable values under a slngle name And you can access Lhe values by referrlng Lo Lhe array name
Lach elemenL ln Lhe array has lLs own lu so LhaL lL can be easlly accessed
CreaLe an Array
An array can be deflned ln Lhree ways
@he followlng code creaLes an Array ob[ecL called myCars
1
var myCarsnew Array() // regular array (add an opLlonal lnLeger
myCars0Saab // argumenL Lo conLrol arrays slze)
myCars1volvo
myCars28,W
2
var myCarsnew Array(Saabvolvo8,W) // condensed array
3
var myCarsSaabvolvo8,W // llLeral array
Note lf you speclfy numbers or Lrue/false values lnslde Lhe array Lhen Lhe varlable Lype wlll be number or 8oolean lnsLead of SLrlng
Access an Array
?ou can refer Lo a parLlcular elemenL ln an array by referrlng Lo Lhe name of Lhe array and Lhe lndex number @he lndex number sLarLs aL 0
@he followlng code llne
documenLwrlLe(myCars0)
wlll resulL ln Lhe followlng ouLpuL
Saab

,odlfy values ln an Array
@o modlfy a value ln an exlsLlng array [usL add a new value Lo Lhe array wlLh a speclfled lndex number
myCars0Cpel
now Lhe followlng code llne
documenLwrlLe(myCars0)
wlll resulL ln Lhe followlng ouLpuL
Cpel

!oln Lwo arrays concaL()
!oln Lhree arrays concaL()
!oln all elemenLs of an array lnLo a sLrlng [oln()
8emove Lhe lasL elemenL of an array pop()
Add new elemenLs Lo Lhe end of an array push()
8everse Lhe order of Lhe elemenLs ln an array reverse()
8emove Lhe flrsL elemenL of an array shlfL()
SelecL elemenLs from an array sllce()
SorL an array (alphabeLlcally and ascendlng) sorL()
SorL numbers (numerlcally and ascendlng) sorL()
SorL numbers (numerlcally and descendlng) sorL()
Add an elemenL Lo poslLlon 2 ln an array spllce()
ConverL an array Lo a sLrlng LoSLrlng()
Add new elemenLs Lo Lhe beglnnlng of an array unshlfL()

!avaScrlpL 8oolean Cb[ecL
@he 8oolean ob[ecL ls used Lo converL a non8oolean value Lo a 8oolean value (Lrue or false)
Check 8oolean value
Check lf a 8oolean ob[ecL ls Lrue or false
CompleLe 8oolean Cb[ecL 8eference
lor a compleLe reference of all Lhe properLles and meLhods LhaL can be used wlLh Lhe 8oolean ob[ecL go Lo our compleLe 8oolean ob[ecL
reference
@he reference conLalns a brlef descrlpLlon and examples of use for each properLy and meLhod!
CreaLe a 8oolean Cb[ecL
@he 8oolean ob[ecL represenLs Lwo values Lrue or false
@he followlng code creaLes a 8oolean ob[ecL called my8oolean
var my8ooleannew 8oolean()
lf Lhe 8oolean ob[ecL has no lnlLlal value or lf Lhe passed value ls one of Lhe followlng
O 0
O 0
O null
O
O false
O undeflned
O nan
Lhe ob[ecL lL ls seL Lo false lor any oLher value lL ls seL Lo Lrue (even wlLh Lhe sLrlng false)!
!avaScrlpL ,aLh Cb[ecL
@he ,aLh ob[ecL allows you Lo perform maLhemaLlcal Lasks
round()
ow Lo use round()
random()
ow Lo use random() Lo reLurn a random number beLween 0 and 1
max()
ow Lo use max() Lo reLurn Lhe number wlLh Lhe hlghesL value of Lwo speclfled numbers
mln()
ow Lo use mln() Lo reLurn Lhe number wlLh Lhe lowesL value of Lwo speclfled numbers
CompleLe ,aLh Cb[ecL 8eference
lor a compleLe reference of all Lhe properLles and meLhods LhaL can be used wlLh Lhe ,aLh ob[ecL go Lo our compleLe ,aLh ob[ecL reference
@he reference conLalns a brlef descrlpLlon and examples of use for each properLy and meLhod!
,aLh Cb[ecL
@he ,aLh ob[ecL allows you Lo perform maLhemaLlcal Lasks
@he ,aLh ob[ecL lncludes several maLhemaLlcal consLanLs and meLhods
Syntax for us|ng propert|es]methods of Math
var x,aLhl
var y,aLhsqrL(16)
Note ,aLh ls noL a consLrucLor All properLles and meLhods of ,aLh can be called by uslng ,aLh as an ob[ecL wlLhouL creaLlng lL
,aLhemaLlcal ConsLanLs
!avaScrlpL provldes elghL maLhemaLlcal consLanLs LhaL can be accessed from Lhe ,aLh ob[ecL @hese are L l square rooL of 2 square rooL of 1/2
naLural log of 2 naLural log of 10 base2 log of L and base10 log of L
?ou may reference Lhese consLanLs from your !avaScrlpL llke Lhls
,aLhL
,aLhl
,aLhSC8@2
,aLhSC8@1_2
,aLhn2
,aLhn10
,aLhCC2L
,aLhCC10L

,aLhemaLlcal ,eLhods
ln addlLlon Lo Lhe maLhemaLlcal consLanLs LhaL can be accessed from Lhe ,aLh ob[ecL Lhere are also several meLhods avallable
@he followlng example uses Lhe round() meLhod of Lhe ,aLh ob[ecL Lo round a number Lo Lhe nearesL lnLeger
documenLwrlLe(,aLhround(47))
@he code above wlll resulL ln Lhe followlng ouLpuL
3
@he followlng example uses Lhe random() meLhod of Lhe ,aLh ob[ecL Lo reLurn a random number beLween 0 and 1
documenLwrlLe(,aLhrandom())
@he code above can resulL ln Lhe followlng ouLpuL
023380036489106713
@he followlng example uses Lhe floor() and random() meLhods of Lhe ,aLh ob[ecL Lo reLurn a random number beLween 0 and 10
documenLwrlLe(,aLhfloor(,aLhrandom()*11))
@he code above can resulL ln Lhe followlng ouLpuL
7

!avaScrlpL 8egLxp Cb[ecL
8egLxp ls shorL for regular expresslon
CompleLe 8egLxp Cb[ecL 8eference
lor a compleLe reference of all Lhe properLles and meLhods LhaL can be used wlLh Lhe 8egLxp ob[ecL go Lo our compleLe 8egLxp ob[ecL reference
@he reference conLalns a brlef descrlpLlon and examples of use for each properLy and meLhod!
WhaL ls 8egLxp?
A regular expresslon ls an ob[ecL LhaL descrlbes a paLLern of characLers
When you search ln a LexL you can use a paLLern Lo descrlbe whaL you are searchlng for
A slmple paLLern can be one slngle characLer
A more compllcaLed paLLern can conslsL of more characLers and can be used for parslng formaL checklng subsLlLuLlon and more
8egular expresslons are used Lo perform powerful paLLernmaLchlng and searchandreplace funcLlons on LexL
SynLax
var paLLnew 8egLxp(paLLernmodlflers)

or more slmply

var paLL/paLLern/modlflers
O paLLern speclfles Lhe paLLern of an expresslon
O modlflers speclfy lf a search should be global casesenslLlve eLc
8egLxp ,odlflers
,odlflers are used Lo perform caselnsenslLlve and global searches
@he l modlfler ls used Lo perform caselnsenslLlve maLchlng
@he g modlfler ls used Lo perform a global maLch (flnd all maLches raLher Lhan sLopplng afLer Lhe flrsL maLch)
Lxample 1
uo a caselnsenslLlve search for w3schools ln a sLrlng
var sLrvlslL W3Schools
var paLL1/w3schools/l
@he marked LexL below shows where Lhe expresslon geLs a maLch
vlslL W3Schools

1ry |t yourse|f

Lxample 2
uo a global search for ls
var sLrls Lhls all Lhere ls?
var paLL1/ls/g
@he marked LexL below shows where Lhe expresslon geLs a maLch
ls Lhls all Lhere ls?

1ry |t yourse|f

Lxample 3
uo a global caselnsenslLlve search for ls
var sLrls Lhls all Lhere ls?
var paLL1/ls/gl
@he marked LexL below shows where Lhe expresslon geLs a maLch
ls Lhls all Lhere ls?

1ry |t yourse|f

LesL()
@he LesL() meLhod searches a sLrlng for a speclfled value and reLurns Lrue or false dependlng on Lhe resulL
@he followlng example searches a sLrlng for Lhe characLer e
Lxample
var paLL1new 8egLxp(e)
documenLwrlLe(paLL1LesL(@he besL Lhlngs ln llfe are free))
Slnce Lhere ls an e ln Lhe sLrlng Lhe ouLpuL of Lhe code above wlll be
Lrue

1ry |t yourse|f

exec()
@he exec() meLhod searches a sLrlng for a speclfled value and reLurns Lhe LexL of Lhe found value lf no maLch ls found lL reLurns oo
@he followlng example searches a sLrlng for Lhe characLer e
Lxample 1
var paLL1new 8egLxp(e)
documenLwrlLe(paLL1exec(@he besL Lhlngs ln llfe are free))
Slnce Lhere ls an e ln Lhe sLrlng Lhe ouLpuL of Lhe code above wlll be
e


!avaScrlpL 8rowser ueLecLlon
@he navlgaLor ob[ecL conLalns lnformaLlon abouL Lhe vlslLors browser
8rowser ueLecLlon
AlmosL everyLhlng ln Lhls LuLorlal works on all !avaScrlpLenabled browsers owever Lhere are some Lhlngs LhaL [usL donL work on cerLaln
browsers especlally on older browsers
SomeLlmes lL can be useful Lo deLecL Lhe vlslLors browser and Lhen serve Lhe approprlaLe lnformaLlon
@he navlgaLor ob[ecL conLalns lnformaLlon abouL Lhe vlslLors browser name verslon and more
Note @here ls no publlc sLandard LhaL applles Lo Lhe navlgaLor ob[ecL buL all ma[or browsers supporL lL
@he navlgaLor Cb[ecL
@he navlgaLor ob[ecL conLalns all lnformaLlon abouL Lhe vlslLors browser
Lxample
dlv ldexample/dlv

scrlpL LypeLexL/[avascrlpL

LxL p8rowser Codename + navlgaLorappCodename + /p
LxL+ p8rowser name + navlgaLorappname + /p
LxL+ p8rowser verslon + navlgaLorappverslon + /p
LxL+ pCookles Lnabled + navlgaLorcookleLnabled + /p
LxL+ plaLform + navlgaLorplaLform + /p
LxL+ puseragenL header + navlgaLoruserAgenL + /p

documenLgeLLlemenL8yld(example)lnner@,LxL

/scrlpL


!avaScrlpL Cookles
A cookle ls ofLen used Lo ldenLlfy a user
WhaL ls a Cookle?
A cookle ls a varlable LhaL ls sLored on Lhe vlslLors compuLer Lach Llme Lhe same compuLer requesLs a page wlLh a browser lL wlll send Lhe cookle
Loo WlLh !avaScrlpL you can boLh creaLe and reLrleve cookle values
Lxamples of cookles
O name cookle @he flrsL Llme a vlslLor arrlves Lo your web page he or she musL flll ln her/hls name @he name ls Lhen sLored ln a cookle
nexL Llme Lhe vlslLor arrlves aL your page he or she could geL a welcome message llke Welcome !ohn uoe! @he name ls reLrleved from
Lhe sLored cookle
O assword cookle @he flrsL Llme a vlslLor arrlves Lo your web page he or she musL flll ln a password @he password ls Lhen sLored ln a
cookle nexL Llme Lhe vlslLor arrlves aL your page Lhe password ls reLrleved from Lhe cookle
O uaLe cookle @he flrsL Llme a vlslLor arrlves Lo your web page Lhe currenL daLe ls sLored ln a cookle nexL Llme Lhe vlslLor arrlves aL your
page he or she could geL a message llke ?our lasL vlslL was on @uesday AugusL 11 2003! @he daLe ls reLrleved from Lhe sLored cookle
CreaLe and SLore a Cookle
ln Lhls example we wlll creaLe a cookle LhaL sLores Lhe name of a vlslLor @he flrsL Llme a vlslLor arrlves Lo Lhe web page he or she wlll be asked Lo
flll ln her/hls name @he name ls Lhen sLored ln a cookle @he nexL Llme Lhe vlslLor arrlves aL Lhe same page he or she wlll geL welcome message
llrsL we creaLe a funcLlon LhaL sLores Lhe name of Lhe vlslLor ln a cookle varlable
funcLlon seLCookle(c_namevalueexdays)

var exdaLenew uaLe()
exdaLeseLuaLe(exdaLegeLuaLe() + exdays)
var c_valueescape(value) + ((exdaysnull) ? explres+exdaLeLou@CSLrlng())
documenLcooklec_name + + c_value

@he parameLers of Lhe funcLlon above hold Lhe name of Lhe cookle Lhe value of Lhe cookle and Lhe number of days unLll Lhe cookle explres
ln Lhe funcLlon above we flrsL converL Lhe number of days Lo a valld daLe Lhen we add Lhe number of days unLll Lhe cookle should explre AfLer LhaL
we sLore Lhe cookle name cookle value and Lhe explraLlon daLe ln Lhe documenLcookle ob[ecL
@hen we creaLe anoLher funcLlon LhaL reLurns a speclfled cookle
funcLlon geLCookle(c_name)

var lxyA88cooklesdocumenLcooklespllL()
for (l0lA88cookleslengLhl++)

xA88cookleslsubsLr(0A88cooklesllndexCf())
yA88cookleslsubsLr(A88cooklesllndexCf()+1)
xxreplace(/s+|s+$/g)
lf (xc_name)

reLurn unescape(y)



@he funcLlon above makes an array Lo reLrleve cookle names and values Lhen lL checks lf Lhe speclfled cookle exlsLs and reLurns Lhe cookle value
asL we creaLe Lhe funcLlon LhaL dlsplays a welcome message lf Lhe cookle ls seL and lf Lhe cookle ls noL seL lL wlll dlsplay a prompL box asklng for
Lhe name of Lhe user and sLores Lhe username cookle for 363 days by calllng Lhe seLCookle funcLlon
funcLlon checkCookle()

var usernamegeLCookle(username)
lf (username!null username!)

alerL(Welcome agaln + username)

else

usernameprompL(lease enLer your name)
lf (username!null username!)

seLCookle(usernameusername363)



All LogeLher now
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon geLCookle(c_name)

var lxyA88cooklesdocumenLcooklespllL()
for (l0lA88cookleslengLhl++)

xA88cookleslsubsLr(0A88cooklesllndexCf())
yA88cookleslsubsLr(A88cooklesllndexCf()+1)
xxreplace(/s+|s+$/g)
lf (xc_name)

reLurn unescape(y)




funcLlon seLCookle(c_namevalueexdays)

var exdaLenew uaLe()
exdaLeseLuaLe(exdaLegeLuaLe() + exdays)
var c_valueescape(value) + ((exdaysnull) ? explres+exdaLeLou@CSLrlng())
documenLcooklec_name + + c_value


funcLlon checkCookle()

var usernamegeLCookle(username)
lf (username!null username!)

alerL(Welcome agaln + username)

else

usernameprompL(lease enLer your name)
lf (username!null username!)

seLCookle(usernameusername363)



/scrlpL
/head
body onloadcheckCookle()
/body
/hLml


!avaScrlpL lorm valldaLlon
!avaScrlpL lorm valldaLlon
!avaScrlpL can be used Lo valldaLe daLa ln @, forms before sendlng off Lhe conLenL Lo a server
lorm daLa LhaL Lyplcally are checked by a !avaScrlpL could be
O has Lhe user lefL requlred flelds empLy?
O has Lhe user enLered a valld emall address?
O has Lhe user enLered a valld daLe?
O has Lhe user enLered LexL ln a numerlc fleld?
8equlred llelds
@he funcLlon below checks lf a fleld has been lefL empLy lf Lhe fleld ls blank an alerL box alerLs a message Lhe funcLlon reLurns false and Lhe form
wlll noL be submlLLed
funcLlon valldaLelorm()

var xdocumenLformsmylormfnamevalue
lf (xnull || x)

alerL(llrsL name musL be fllled ouL)
reLurn false


@he funcLlon above could be called when a form ls submlLLed
Lxample
form namemylorm acLlondemo_formasp onsubmlLreLurn valldaLelorm() meLhodposL
llrsL name lnpuL LypeLexL namefname
lnpuL LypesubmlL valueSubmlL
/form

1ry |t yourse|f

Lmall valldaLlon
@he funcLlon below checks lf Lhe conLenL has Lhe general synLax of an emall
@hls means LhaL Lhe lnpuL daLa musL conLaln an [ slgn and aL leasL one doL () Also Lhe [ musL noL be Lhe flrsL characLer of Lhe emall address and
Lhe lasL doL musL be presenL afLer Lhe [ slgn and mlnlmum 2 characLers before Lhe end
funcLlon valldaLelorm()

var xdocumenLformsmylormemallvalue
var aLposxlndexCf([)
var doLposxlasLlndexCf()
lf (aLpos1 || doLposaLpos+2 || doLpos+2xlengLh)

alerL(noL a valld emall address)
reLurn false


@he funcLlon above could be called when a form ls submlLLed
Lxample
form namemylorm acLlondemo_formasp onsubmlLreLurn valldaLelorm() meLhodposL
Lmall lnpuL LypeLexL nameemall
lnpuL LypesubmlL valueSubmlL
/form


!avaScrlpL @lmlng LvenLs
1
2
3
4
3

!avaScrlpL can be execuLed ln LlmelnLervals
@hls ls called Llmlng evenLs
6
7
8
9
10
11
12


!avaScrlpL @lmlng LvenLs
WlLh !avaScrlpL lL ls posslble Lo execuLe some code afLer a speclfled LlmelnLerval @hls ls called Llmlng evenLs
lLs very easy Lo Llme evenLs ln !avaScrlpL @he Lwo key meLhods LhaL are used are
O seL@lmeouL() execuLes a code some Llme ln Lhe fuLure
O clear@lmeouL() cancels Lhe seL@lmeouL()
Note @he seL@lmeouL() and clear@lmeouL() are boLh meLhods of Lhe @, uC, Wlndow ob[ecL
@he seL@lmeouL() ,eLhod
Syntax
var LseL@lmeouL(ovosctlptstotemeotmllsecooJs)
@he seL@lmeouL() meLhod reLurns a value ln Lhe synLax deflned above Lhe value ls sLored ln a varlable called L lf you wanL Lo cancel Lhe
seL@lmeouL() funcLlon you can refer Lo lL uslng Lhe varlable name
@he flrsL parameLer of seL@lmeouL() can be a sLrlng of execuLable code or a call Lo a funcLlon
@he second parameLer lndlcaLes how many mllllseconds from now you wanL Lo execuLe Lhe flrsL parameLer
Note @here are 1000 mllllseconds ln one second
Lxample
When Lhe buLLon ls cllcked ln Lhe example below an alerL box wlll be dlsplayed afLer 3 seconds
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
funcLlon Llme,sg()

var LseL@lmeouL(alerL,sg()3000)

funcLlon alerL,sg()

alerL(ello)

/scrlpL
/head

body
form
lnpuL LypebuLLon valueulsplay alerL box ln 3 seconds
oncllckLlme,sg() /
/form
/body
/hLml

1ry |t yourse|f
Lxample lnflnlLe oop
@o geL a Llmer Lo work ln an lnflnlLe loop we musL wrlLe a funcLlon LhaL calls lLself
ln Lhe example below when a buLLon ls cllcked Lhe lnpuL fleld wlll sLarL Lo counL (for ever) sLarLlng aL 0
noLlce LhaL we also have a funcLlon LhaL checks lf Lhe Llmer ls already runnlng Lo avold creaLlng addlLlonal Llmers lf Lhe buLLon ls pressed more
Lhan once
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
var c0
var L
var Llmer_ls_on0

funcLlon LlmedCounL()

documenLgeLLlemenL8yld(LxL)valuec
cc+1
LseL@lmeouL(LlmedCounL()1000)


funcLlon do@lmer()

lf (!Llmer_ls_on)

Llmer_ls_on1
LlmedCounL()


/scrlpL
/head

body
form
lnpuL LypebuLLon valueSLarL counL! oncllckdo@lmer()
lnpuL LypeLexL ldLxL /
/form
/body
/hLml

1ry |t yourse|f

@he clear@lmeouL() ,eLhod
Syntax
clear@lmeouL(set@lmeoot_votloe)
Lxample
@he example below ls Lhe same as Lhe lnflnlLe oop example above @he only dlfference ls LhaL we have now added a SLop CounL! buLLon LhaL
sLops Lhe Llmer
Lxample
hLml
head
scrlpL LypeLexL/[avascrlpL
var c0
var L
var Llmer_ls_on0

funcLlon LlmedCounL()

documenLgeLLlemenL8yld(LxL)valuec
cc+1
LseL@lmeouL(LlmedCounL()1000)


funcLlon do@lmer()

lf (!Llmer_ls_on)

Llmer_ls_on1
LlmedCounL()



funcLlon sLopCounL()

clear@lmeouL(L)
Llmer_ls_on0

/scrlpL
/head

body
form
lnpuL LypebuLLon valueSLarL counL! oncllckdo@lmer()
lnpuL LypeLexL ldLxL
lnpuL LypebuLLon valueSLop counL! oncllcksLopCounL()
/form
/body
/hLml


!avaScrlpL CreaLe ?our Cwn Cb[ecLs
Cb[ecLs are useful Lo organlze lnformaLlon
CreaLe a dlrecL lnsLance of an ob[ecL
CreaLe a LemplaLe for an ob[ecL
!avaScrlpL Cb[ecLs
Larller ln Lhls LuLorlal we have seen LhaL !avaScrlpL has several bullLln ob[ecLs llke SLrlng uaLe Array and more ln addlLlon Lo Lhese bullLln
ob[ecLs you can also creaLe your own
An ob[ecL ls [usL a speclal klnd of daLa wlLh a collecLlon of properLles and meLhods
eLs lllusLraLe wlLh an example A person ls an ob[ecL roperLles are Lhe values assoclaLed wlLh Lhe ob[ecL @he persons properLles lnclude name
helghL welghL age skln Lone eye color eLc All persons have Lhese properLles buL Lhe values of Lhose properLles wlll dlffer from person Lo person
Cb[ecLs also have meLhods ,eLhods are Lhe acLlons LhaL can be performed on ob[ecLs @he persons meLhods could be eaL() sleep() work() play()
eLc
roperLles
@he synLax for accesslng a properLy of an ob[ecL ls
ob[namepropname
?ou can add properLles Lo an ob[ecL by slmply glvlng lL a value Assume LhaL Lhe personCb[ already exlsLs you can glve lL properLles named
flrsLname lasLname age and eyecolor as follows
personCb[flrsLname!ohn
personCb[lasLnameuoe
personCb[age30
personCb[eyecolorblue

documenLwrlLe(personCb[flrsLname)
@he code above wlll generaLe Lhe followlng ouLpuL
!ohn
,eLhods
An ob[ecL can also conLaln meLhods
?ou can call a meLhod wlLh Lhe followlng synLax
ob[namemeLhodname()
Note arameLers requlred for Lhe meLhod can be passed beLween Lhe parenLheses
@o call a meLhod called sleep() for Lhe personCb[
personCb[sleep()


CreaLlng ?our Cwn Cb[ecLs
@here are dlfferenL ways Lo creaLe a new ob[ecL
Create a d|rect |nstance of an ob[ect
@he followlng code creaLes an new lnsLance of an ob[ecL and adds four properLles Lo lL
personCb[new Cb[ecL()
personCb[flrsLname!ohn
personCb[lasLnameuoe
personCb[age30
personCb[eyecolorblue
alLernaLlve synLax (uslng ob[ecL llLerals)
personCb[flrsLname!ohnlasLnameuoeage30eyecolorblue
Addlng a meLhod Lo Lhe personCb[ ls also slmple @he followlng code adds a meLhod called eaL() Lo Lhe personCb[
personCb[eaLeaL
2 Create an ob[ect constructor
CreaLe a funcLlon LhaL consLrucL ob[ecLs
funcLlon person(flrsLnamelasLnameageeyecolor)

LhlsflrsLnameflrsLname
LhlslasLnamelasLname
Lhlsageage
Lhlseyecoloreyecolor

lnslde Lhe funcLlon you need Lo asslgn Lhlngs Lo LhlsproperLyname @he reason for all Lhe Lhls sLuff ls LhaL youre golng Lo have more Lhan one
person aL a Llme (whlch person youre deallng wlLh musL be clear) @haLs whaL Lhls ls Lhe lnsLance of Lhe ob[ecL aL hand
Cnce you have Lhe ob[ecL consLrucLor you can creaLe new lnsLances of Lhe ob[ecL llke Lhls
var mylaLhernew person(!ohnuoe30blue)
var my,oLhernew person(Sally8ally48green)
?ou can also add some meLhods Lo Lhe person ob[ecL @hls ls also done lnslde Lhe funcLlon
funcLlon person(flrsLnamelasLnameageeyecolor)

LhlsflrsLnameflrsLname
LhlslasLnamelasLname
Lhlsageage
Lhlseyecoloreyecolor

LhlsnewlasLnamenewlasLname

noLe LhaL meLhods are [usL funcLlons aLLached Lo ob[ecLs @hen we wlll have Lo wrlLe Lhe newlasLname() funcLlon
funcLlon newlasLname(new_lasLname)

LhlslasLnamenew_lasLname

@he newlasLname() funcLlon deflnes Lhe persons new lasL name and asslgns LhaL Lo Lhe person !avaScrlpL knows whlch person youre Lalklng abouL
by uslng Lhls So now you can wrlLe my,oLhernewlasLname(uoe)

?ou ave earned !avaScrlpL now WhaL?
!avaScrlpL Summary
@hls LuLorlal has LaughL you how Lo add !avaScrlpL Lo your @, pages Lo make your web slLe more dynamlc and lnLeracLlve
?ou have learned how Lo creaLe responses Lo evenLs valldaLe forms and how Lo make dlfferenL scrlpLs run ln response Lo dlfferenL scenarlos
?ou have also learned how Lo creaLe and use ob[ecLs and how Lo use !avaScrlpLs bullLln ob[ecLs
lor more lnformaLlon on !avaScrlpL please look aL our !avaScrlpL examples and our !avaScrlpL reference
now ?ou know !avaScrlpL WhaLs nexL?
@he nexL sLep ls Lo learn abouL Lhe @, uC, [Cuery and A!Ax
lf you wanL Lo learn abouL serverslde scrlpLlng Lhe nexL sLep ls Lo learn AS or
n1ML DCM
@he @, uC, deflnes a sLandard way for accesslng and manlpulaLlng @, documenLs
@he @, uC, ls plaLform and language lndependenL and can be used by any programmlng language llke !ava !avaScrlpL and v8ScrlpL
lf you wanL Lo learn more abouL Lhe uC, please vlslL our @, uC, LuLorlal
[uery
[Cuery ls a !avaScrlpL lbrary
[Cuery greaLly slmpllfles !avaScrlpL programmlng
lf you wanL Lo learn more abouL [Cuery please vlslL our [Cuery LuLorlal
AIAk
A!Ax Asynchronous !avaScrlpL and x,
A!Ax ls noL a new programmlng language buL a new way Lo use exlsLlng sLandards
A!Ax ls abouL exchanglng daLa wlLh a server and updaLe parLs of a web page wlLhouL reloadlng Lhe whole page
Lxamples of appllcaLlons uslng A!Ax Coogle ,aps Cmall ?ouLube and lacebook Labs
lf you wanL Lo learn more abouL A!Ax please vlslL our A!Ax LuLorlal
AS ] n
Whlle scrlpLs ln an @, flle are execuLed on Lhe cllenL (ln Lhe browser) scrlpLs ln an AS/ flle are execuLed on Lhe server
WlLh AS/ you can dynamlcally edlL change or add any conLenL of a Web page respond Lo daLa submlLLed from @, forms access any daLa
or daLabases and reLurn Lhe resulLs Lo a browser cusLomlze a Web page Lo make lL more useful for lndlvldual users
Slnce AS/ flles are reLurned as plaln @, Lhey can be vlewed ln any browser
lf you wanL Lo learn more abouL AS please vlslL our AS LuLorlal
lf you wanL Lo learn more abouL please vlslL our LuLorlal

You might also like