You are on page 1of 208

JavaScript

A Comprehensive Beginner's Guide to Mastering JavaScript Programming Incrementally

Ryan roffe
©B BCopyrightB B2023B B–B BRyanB Broffe
AllB BrightsB Breserved.
TheB BcontentB BcontainedB BwithinB BthisB BbookB BmayB BnotB BbeB Breproduced,B Bduplicated,B BorB
transmittedB BwithoutB BdirectB BwrittenB BpermissionB BfromB BtheB BauthorB BorB BtheB Bpublisher.
B

UnderB BnoB BcircumstancesB BwillB BanyB BblameB BorB BlegalB BresponsibilityB BbeB BheldB BagainstB BtheB
publisher,B BorB Bauthor,B BforB BanyB Bdamages,B Breparation,B BorB BmonetaryB BlossB BdueB BtoB BtheB
B

informationB BcontainedB BwithinB BthisB Bbook,B BeitherB BdirectlyB BorB Bindirectly.


B

LegalB BNotice:
ThisB BbookB BisB BcopyrightB Bprotected.B BItB BisB BonlyB BforB BpersonalB Buse.B BYouB BcannotB Bamend,B
distribute,B Bsell,B Buse,B BquoteB BorB BparaphraseB BanyB Bpart,B BorB BtheB BcontentB BwithinB BthisB
B

book,B BwithoutB BtheB BconsentB BofB BtheB BauthorB BorB Bpublisher.


B

DisclaimerB BNotice:
PleaseB BnoteB BtheB BinformationB BcontainedB BwithinB BthisB BdocumentB BisB BforB BeducationalB BandB
entertainmentB BpurposesB Bonly.B BAllB BeffortB BhasB BbeenB BexecutedB BtoB BpresentB Baccurate,B BupB
B

toB Bdate,B Breliable,B BcompleteB Binformation.B BNoB BwarrantiesB BofB BanyB BkindB BareB BdeclaredB BorB
B

implied.B BReadersB BacknowledgeB BthatB BtheB BauthorB BdoB BnotB BengageB BinB BtheB BrenderingB BofB
B

legal,B Bfinancial,B Bmedical,B BorB BprofessionalB Badvice.B BTheB BcontentB BwithinB BthisB BbookB BhasB
B

beenB BderivedB BfromB BvariousB Bsources.B BPleaseB BconsultB BaB BlicensedB BprofessionalB BbeforeB
B

attemptingB BanyB BtechniquesB BoutlinedB BinB BthisB Bbook.


B

ByB BreadingB BthisB Bdocument,B BtheB BreaderB BagreesB BthatB BunderB BnoB BcircumstancesB BisB BtheB
authorB BresponsibleB BforB BanyB Blosses,B BdirectB BorB Bindirect,B BthatB BareB BincurredB BasB BaB BresultB
B

ofB BtheB BuseB BofB BtheB BinformationB BcontainedB BwithinB BthisB Bdocument,B Bincluding,B BbutB BnotB
B

limitedB Bto,B Berrors,B Bomissions,B BorB Binaccuracies.


B

BB
TABLE OF CONTENTS
Introduction
Chapter 1: What is JavaScript
Chapter 2: Values, Types, and Operators
Chapter 3: Program Structure
Chapter 4: Functions
Chapter 5: Data Structures: Objects and Arrays
Chapter 6: Higher-Order Functions
Chapter 7: The Secret Life of Objects
Chapter 8: A Robot
Chapter 9: Bugs and Errors
Chapter 10: Regular Expressions
Chapter 11: Modules
Chapter 12: Asynchronous Programming
Conclusion
Introduction
JavaScriptB BisB BaB BdistinguishedB BandB BdecipheredB BprogrammingB BlanguageB
thatB BadheresB BtoB BtheB BECMAScriptB Bspecification.B BTheB BprogrammingB
B

languageB BconsistsB BofB Bhigh-poweredB Btyping,B BtheB BcurlyB BbracketB


B

syntax,B
B Btop-qualityB Bfunctions,B BandB Bprototype-basedB Bobject-
orientation.B BAccompaniedB BbyB BHTMLB BandB BCSS,B BJavaScriptB BisB BoneB BofB
theB BsignificantB BtechnologiesB BofB BtheB BWorldB BWideB BWeb.B BJavaScriptB
B

facilitatesB BinterchangeableB BwebB BpagesB BandB BisB BaB BvitalB BpartB BofB BwebB
B

applications.B BAlmostB BeveryB BwebsiteB ButilizesB BJavaScript,B BandB BallB BtheB


B

significantB BwebB BbrowsersB BconsistB BofB BtheB BJavaScriptB BengineB BtoB


B

functionB Bcorrectly.B BBrendanB BEichB BdevelopedB BJavaScriptB BinB B1995B


B

whenB BheB BwasB BwithB BNetscapeB BCommunications.B BJavaScriptB BaidsB


B

functional,B
B Bevent-driven,B Bprototype-basedB BandB Bobject-orientedB
programmingB Bstyles.B BJavaScriptB BupgradesB BwebB BuserB BinterfaceB BbyB
B

affirmingB BactivitiesB BtakenB BonB BtheB Bclient-sideB BbyB BtheB Buser.B BYouB BcanB
B

insertB BJavaScriptB BenginesB BintoB BdifferentB BtypesB BofB BhostB Bsoftware,B


B

whichB BincludesB BdatabasesB BandB BwebB Bservers,B BandB Bnon-webB BrelatedB


B

programsB BlikeB BwordB Bprocessors.


B

TheB BconceptsB BofB BJavaScriptB BareB BexplainedB BfurtherB BinB BthisB BbookB
withB BtheB BgoalB BtoB BhelpB ByouB BlearnB BandB BunderstandB BJavaScriptB
B

languageB BwithoutB Bpressure.B BTheB BknowledgeB BofB BHTML,B BtextB Beditor,B


B

webB Bbrowser,B BandB BCSSB BareB BallB Bthat'sB BneededB BtoB BlearnB BJavaScript.B
B

ToB BgetB BtheB BlearningB BprocessB Bstarted,B BoneB BofB BtheB BessentialB BtoolsB BisB
B

aB BtextB Beditor,B BandB BitB BisB BrequiredB BtoB BwriteB Bcodes.B BYou’llB BalsoB BneedB
B

aB BbrowserB BtoB BunveilB ByourB BdevelopedB BwebB Bpages.B BThereB BareB


B

differentB BtypesB BofB BtextB BeditorsB BsuchB BasB BtheB BSublimeB BText,B
B
Notepad++B BandB BbrowsersB BsuchB BasB BFirefox,B BGoogleB BChrome,B BandB BsoB
B

on.B B
B

BB
Chapter 1: What is JavaScript
BB BB BB BB

JavaScript,B BabbreviatedB BJS,B BisB BaB Bhigh-levelB BprogrammingB BlanguageB


introducedB BtoB BaddB BspecificB BprogramsB BtoB BwebB Bpages,B BandB BitB BhasB
B

beenB BadoptedB BbyB BallB BmajorB BwebB Bbrowsers.B BJavaScriptB BcanB BbeB BusedB
B

toB BbuildB BinteractiveB BwebB BapplicationsB BtoB BfunctionB BappropriatelyB


B

withoutB BreloadingB BeveryB BpageB Bper-action.B BJavaScriptB BisB BusedB BtoB


B

createB BdifferentB BformsB BofB BactivitiesB BwithinB BwebB BpagesB BandB BisB BoneB
B

ofB BtheB BessentialB BcomponentsB BofB BtheB BWorldB BWideB BWebB B(www),B
B

whichB
B BareB HTMLB
B (HypertextB
B MarkupB
B Language)B
B andB
B CSSB
B

(CascadingB BStyleB BSheets).B BJavaScriptB BandB BHTMLB BareB BusedB BtoB


B

developB BwebB Bpages.B BJavaScriptB BbringsB BaB BpageB BtoB BlifeB BbyB BaddingB
B

specialB BeffectsB BsuchB BasB Bsliders,B Bpop-ups,B BformB Bvalidations,B Betc.B BCSSB
B

determinesB BtheB BcolorB Bintensity,B BimageB Bsize,B BbackgroundB Bcolors,B


B

typeface,B BfontB Bsize,B Betc.


B

Client-Side JavaScript
BB

Client-SideB BJavaScriptB BisB BtheB BusualB BformB BofB BJavaScriptB Blanguage.B


TheB BscriptB BmustB BbeB BinsertedB BorB BreferencedB BbyB BanB BHTMLB BdocumentB
B

soB BthatB BtheB BbrowserB BcanB BinterpretB BtheB Bcode.B BItB BenablesB BwebB BpagesB
B

toB BincludeB BinteractiveB BprogramsB BwithB BtheB Buser,B BdevelopB BHTMLB


B

contentB Bdynamically,B BandB BcommandB BtheB Bbrowser.B BUsersB BuseB


B

JavaScriptB BcodeB BwhenB BtheyB BwantB BtoB BsubmitB BformsB BandB BalsoB
B

determineB BifB BallB BentriesB BareB BvalidB BbeforeB BitB BtransfersB BthemB BtoB BtheB
B

server.
B

Advantages of JavaScript
BB BB
·B BWithB BJavaScript,B BusersB BcanB BorganizeB BinputB BbeforeB BgettingB BtheB
pageB BsentB BtoB BtheB Bserver,B BwhichB BautomaticallyB BreducesB BloadsB BonB
B

theB Bserver.
B

·B BJavaScriptB BenablesB BswiftB BresponseB BtoB BpageB Bvisitors.B BTheB BpageB BdoesB
notB BhaveB BtoB BreloadB BbeforeB BvisitorsB BcanB BseeB BifB BthereB BwasB BanB BerrorB
B

inB Btyping.
B

·B BJavaScriptB BisB BusedB BtoB BbuildB BaB BreactiveB BinterfaceB BthatB BgivesB BaB
reactionB BwhenB BtheB BmouseB BhoversB BoverB Bthem.
B

Limitations of JavaScript
BB BB

JavaScriptB BprogrammingB BlanguageB BlacksB BtheB BfollowingB BessentialB


features.B BTheyB Bare:
B

·B BForB BsecurityB Breasons,B Bclient-sideB BJavaScriptB BdoesB BnotB BreadB BorB


writeB Bfiles
B

·B BJavaScriptB BforB BnetworkingB Bapplications


·B BJavaScriptB BdoesB BnotB BcontainB BmultiprocessorB Bcapabilities
JavaScriptB BDevelopmentB BTools
YouB BdoB BnotB BneedB BanB BexpensiveB BdevelopmentB BtoolB BtoB BwriteB
JavaScriptB Bcodes.B BYouB BcanB BwriteB BwithB BaB BsimpleB BtextB BeditorB BsuchB BasB
B

MicrosoftB BFrontPage,B BMacromediaB BDreamweaverB BMX,B BMacromediaB


B

HomeSiteB B5,B Betc.


B

Javascript Placement
BB

JavaScriptB BcodeB BisB BinsertedB BanywhereB BinB BanB BHTMLB Bdocument.B


However,B ByouB BwantB BtoB BinsertB BJavaScriptB BcodeB BinB BanB BHTMLB BfileB
B

likeB Bthis:
B

TheB BScriptB BwithinB B<head>B B</head>B Bpart.


TheB BScriptB BwithinB B<body>B B</body>B Bpart.
TheB BScriptB BwithinB B<body>B B</body>B BandB B<head>B B</head>B Bpart.
IncludeB BexternalB BfileB BScriptB BinB BtheB B<head>...</head>B Bpart.
JavaScriptB BinB B<head>...</head>B BSection
InB BsomeB Bcases,B BwhenB ByouB BwantB BtheB BscriptB BtoB BrunB BonB BaB BspecialB
event,B BsuchB BasB BanB BactionB BwhenB BaB BbuttonB Bclicked,B BplaceB BtheB BscriptB
B

inB BtheB BheadB BsectionB BlikeB Bthis:


B

<html>
<head>

<scriptB Btype="text/JavaScript">
<!--

functionB BsayHi()B B{
alert("HelloB BWorld")
}
//-->
</script>
</head>
<body>

TapB BhereB BforB Bresult


<inputB Btype="button"B Bonclick="sayHi()"B Bvalue="SayB BHi"B B/>
</body>
</html>

JavaScriptB BinB B<body>...</body>B BSection


SometimesB ByouB BwantB BaB BscriptB BtoB BrunB BimmediatelyB BandB BtoB BcreateB
scriptB BonB BtheB BcontentB Bpage,B BinsertB BtheB BscriptB BwithinB BtheB B<body>B
B

section.B BThisB BisB BwhatB BtheB BcodeB BshouldB BlookB Blike:


B

<html>
<head>
</head>
<body>

<scriptB Btype="text/JavaScript">
<!--

document.write("HelloB BWorld")
//-->
</script>

<p>ThisB BisB BwebB BpageB BbodyB B</p>


</body>
</html>

JavaScriptB BinB B<body>B BandB B<head>B BSections


InsertB ByourB BJavaScriptB BcodeB BinB B<head>B BandB B<body>B BsectionB BlikeB Bthis:
<html>
<head>

<scriptB Btype="text/JavaScript">
<!--

functionB BsayHi()B B{
alert("HelloB BWorld")
}
//-->
</script>
</head>
<body>

<scriptB Btype="text/JavaScript">
<!--

document.write("HelloB BWorld")
//-->
</script>

<inputB Btype="button"B Bonclick="sayHi()"B Bvalue="SayB BHi"B B/>


</body>
</html>

JavaScript in External Files


BB BB BB

ToB BavoidB BtheB BuseB BofB BidenticalB BJavaScriptB BcodeB Brepetition,B BtheB
BlanguageB BenablesB ByouB BtoB BcreateB BanB BexternalB BfileB BandB BstoreB
BJavaScriptB BcodesB BandB BthenB BintegrateB BtheB BexternalB BfileB BintoB BtheB
BHTMLB Bfiles.B BTheB BsampleB BbelowB BdisplaysB BhowB BtoB BintegrateB BanB
BexternalB BJavaScriptB BfileB BwithinB BtheB BHTMLB BcodeB ButilizingB BtheB BscriptB
BtagB BandB BsrcB Battribute.
<html>
<head>

<scriptB Btype="text/javascript"B Bsrc="filename.js"B B></script>


</head>
<body>
.......
</body>
</html>

TheB BexternalB BfileB BsourceB BfileB BshouldB BbeB BsavedB BwithB BanB BextensionB
B.js.
Summary

InB BthisB BfirstB Bchapter,B BweB BexplainedB BtheB BoriginationB BofB BJavaScriptB
BandB BitsB BplacementB BintoB BinternalB BandB BexternalB Bfiles.B BWeB BdiscussedB
BtheB BuseB BofB BJavaScriptB BtoB BbuildB BinteractiveB BwebB BapplicationsB BtoB
BperformB BappropriatelyB BwithoutB BhavingB BtoB BreloadB BeveryB BpageB Bper-
action.
Exercise

HowB BdoB ByouB BinsertB BJavaScriptB BcodeB BintoB BtheB Bhead,B BbodyB BandB
BincludeB BexternalB BfileB BscriptB BinB BanB BHTMLB Bdocument?
Solution

TheB BScriptB BforB BtheB BheadB BpartB BisB B<head>B B</head>.


TheB BScriptB BforB BtheB BbodyB BpartB BisB B<body>B B</body>.
TheB BScriptB BwithinB BtheB BbodyB BisB B<body>B B</body>B BandB B<head>B B</head>.
TheB BScriptB BtoB BIncludeB BexternalB BfileB BScriptB BinB BtheB B<head>...</head>.
Chapter 2: Values, Types, and
BB BB BB BB B

BOperators
InB BtheB BworldB BofB Bcomputers,B BthereB BisB Bdata.B BYouB BcanB BcreateB BnewB
data,B BreadB BdataB BandB BchangeB Bdata,B BwhichB BareB BallB BstoredB BasB BaB Blook-
B

alikeB BlongB BsuccessionB BofB Bbits.B BDefineB BbitsB BasB BzerosB BandB BonesB BthatB
takeB BaB BstrongB BorB BweakB Bsignal,B BandB BhighB BorB BlowB BelectricalB BchargeB
B

fromB BinsideB BtheB Bcomputer.B BAllB BdataB BandB BpiecesB BofB BinformationB BareB
B

describedB BasB BaB BsuccessionB BofB BzerosB BandB BonesB BandB BrepresentedB BinB
B

bits.
B

Values

TakeB BaB BdeepB BbreathB BandB BthinkB BofB BanB BoceanB BofB Bbits.B BTheB BlatestB BPCsB
containsB BmoreB BthanB B30B BbillionB BbitsB BinB BitsB BdataB Bstorage.B BWeB BuseB
B

bitsB BtoB BcreateB Bvalues.B BTheB BcomputerB BcanB BfunctionB BcorrectlyB


B

becauseB BeveryB BbitB BofB BinformationB BisB BsplitB BintoB Bvalues.B BEveryB BvalueB
B

consistsB BofB BaB BtypeB BthatB BinfluencesB BitsB Brole,B BandB BvaluesB BcanB BbeB
B

numbers,B BtextB BorB Bfunctions,B Betc.B BToB BgenerateB Bvalue,B ByouB BneedB BtoB
B

invokeB BitsB Bname,B BandB BitB BappearsB BfromB BwhereB BitB BwasB Bstored.
B

Arithmetic

ArithmeticB BisB BtheB BmajorB BthingB BtoB BdoB BwithB Bnumbers.B BTheB
multiplication,B Baddition,B BandB BsubtractionB BofB BmoreB BthanB BoneB
B

numberB BtoB BproduceB BanotherB BnumberB BisB BanB BarithmeticB Boperation.B


B

ThisB BisB BanB BexampleB BofB BwhatB BtheyB BlookB BlikeB BinB BJavaScript:
B

100B B+B B4B B*B B11


TheB B+B BandB B*B BsymbolsB BareB BcalledB Boperators,B BtheB BfirstB BmeansB
additionB BwhileB BtheB BotherB BmeansB Bmultiplication.B BAnB BoperatorB
B

insertedB BbetweenB BtwoB BvaluesB BwillB BproduceB BanotherB Bvalue.B BTheB B-B
B

operatorB BisB BforB BsubtractionB BandB BtheB B/B BoperatorB BisB BforB BtheB Bdivision.B
B

IfB BoperatorsB BshowB BtogetherB BwithoutB Bparentheses,B BtheB BprecedenceB BofB


B

theB BoperatorsB BdecidesB BtheB BwayB BtheyB BareB Bapplied.B BIfB BseveralB
B

operatorsB BwithB BtheB BsameB BprecedenceB BshowB BrightB BnextB BtoB BeachB
B

otherB BlikeB B1B B-B B2B B+B B1,B BapplyB BthemB BleftB BtoB Bright:B B(1B B-B B2)B B+B B1.
B

SpecialB Bnumbers
JavaScriptB BconsistsB BofB BthreeB BuniqueB BvaluesB BthatB BdoB BnotB BactB BlikeB
numbersB BbutB BareB BregardedB BasB Bnumbers.B BInfinityB BandB B-InfinityB BareB
B

theB BfirstB Btwo,B BwhichB BmeanB BtheB BpositiveB BandB BnegativeB Binfinities,B
B

andB BtheB BlastB BvalueB BisB BtheB BNaN.B BNaNB BsaysB B“notB BaB Bnumber,”B
B

althoughB BitB BisB BaB BvalueB BofB BtheB BnumberB Btype.


B

Strings

AB BstringB BisB BtheB BsuccessionB BofB Bnumbers.B BTheB BstringB BisB BtheB BnextB
dataB Btype,B BandB BtheyB BrepresentB Btext.B BStringsB BconfineB BtheirB BcontentB
B

inB Bquotes.
B

`DownB BtheB BwalkwayB Bpath.B B`


"OnB BtopB BofB BtheB Broof."
'IB BamB BatB Bhome.'
QuotesB BareB BusedB BinB BdifferentB BtypesB BlikeB BtheB BdoubleB Bquotes,B BsingleB
quotes,B BorB BtheB BbackticksB BtoB BmarkB Bstrings.B BItB BisB BessentialB BthatB BtheB
B

stringsB Bmatch.B BTheB BelementsB BwithinB BtheB BquotesB BcreateB BaB BstringB
B

valueB BbyB BJavaScript.B BJavaScriptB BusesB BtheB BUnicodeB BstandardB BtoB


B

BassignB BaB BnumberB BtoB BeveryB BcharacterB Bneeded,B BincludingB BArabic,B


BArmenian,B BJapanese,B Betc.B BYouB BcannotB Bsubtract,B Bmultiply,B BorB BdivideB
stringsB BbutB ByouB BcanB BuseB BtheB B+B Boperator,B BwhichB BwillB BnotB BaddB BbutB
B

concatenatesB BtwoB BstringsB Btogether.B BConcatenationB BmeansB BtoB BglueB


B

stringsB Btogether.
B

Unary operatorsBB

SymbolsB BdoB BnotB BrepresentB BallB BtheB Boperators.B BYouB BcanB BwriteB BsomeB
operatorsB BinB Bwords.B BAB BclearB BexampleB BisB BaB BtypeB BofB Boperator,B BandB
B

thisB BoperatorB BcreatesB BaB BstringB BvalueB BwithB BtheB BnameB BofB BtheB BtypeofB
B

itsB BattachedB Bvalue.


B

console.log(typeofB B4.5)
//B B→B Bnumber
console.log(typeofB B"x")
//B B→B Bstring
TheB BsecondB BdisplayedB BoperatorB BisB BcalledB BtheB BbinaryB BoperatorB
becauseB BtheyB BuseB BtwoB Bvalues,B BwhileB BoperatorsB BthatB BuseB BoneB BvalueB
B

areB BtheB BunaryB Boperator.


B

console.log(-B B(10B B-B B2))


//B B→B B-8
BooleanB Bvalues
BooleanB BisB BaB BvalueB BthatB BdiffersB BonlyB BbetweenB BtwoB BpossibilitiesB BsuchB
asB B“on”B BandB B“off”B BandB BsoB Bon.B BTheB BBooleanB BconsistsB BofB BonlyB BtrueB
B

andB Bfalse.
B

Comparison

ComparisonB BisB BaB BwayB BtoB BcreateB BBooleanB Bvalues:


console.log(3B B>B B2)
//B B→B Btrue
console.log(3B B<B B2)
//B B→B Bfalse
TheB B>B BandB B<B BcharactersB BareB BtheB BsignsB BthatB BrepresentB B“isB BgreaterB
than”B BandB B“isB BlessB Bthan,”B Baccordingly.B BYouB BcanB BuseB BbinaryB
B

operatorsB BinB BaB BBooleanB BvalueB BthatB BdeterminesB BifB BtheB BcontainedB
B

valueB BifB BtrueB BorB Bfalse.


B

YouB BcanB BcompareB BstringsB BinB BtheB BsameB Bmanner.


console.log("Aardvark"B B<B B"Zoroaster")
//B B→B Btrue
YouB BcanB BinstructB BstringsB BinB BalphabeticalB Border,B BuppercaseB BlettersB
areB BoftenB B“less”B BthanB Blowercase,B BsoB B"Z"B B<B B"a,"B BandB Bnon-alphabeticB
B

charactersB B(!B B-,B BandB BsoB Bon)B BareB BalsoB BpresentB BinB BtheB Bordering.B
B

WhenB BJavaScriptB BwantB BtoB BcompareB Bstrings,B BitB BrecognizesB BcharactersB


B

fromB BleftB BtoB Bright,B BdifferentiatingB BtheB BUnicodeB BcodesB Bindividually.


B

HereB BareB BotherB BrelatedB BoperatorsB B<=B B(lessB BthanB BorB BequalB Bto),B B>=B
(greaterB BthanB BorB BequalB Bto),B B==B B(equalB Bto),B Band!=B B(notB BequalB Bto).
B

console.log("Itchy"B B!=B B"Scratchy")


//B B→B Btrue
console.log("Apple"B B==B B"Orange")
//B B→B Bfalse
InB BJavaScript,B BthereB BisB BonlyB BoneB BvalueB BthatB BisB BnotB BequalB BtoB Bitself,B
whichB BisB BtheB BNaNB B(“notB BaB Bnumber”).
B

console.log(NaNB B==B BNaN)


//B B→B Bfalse
LogicalB Boperator
JavaScriptB BendorsesB BonlyB BthreeB BoperatorsB BthatB ByouB BcanB BapplyB BtoB
BooleanB Bvalues,B BtheyB BareB Band,B Bor,B BandB Bnot.B BTheB B&&B BoperatorB
B

signifiesB BlogicalB BorB BandB BitsB BresultsB BdependB BonB BwhereB BtheB BvaluesB
B

imputedB BareB BtrueB BorB Bfalse.


B

console.log(trueB B&&B Bfalse)


//B B→B Bfalse
console.log(trueB B&&B Btrue)
//B B→B Btrue
TheB B||B BoperatorB BindicatesB BlogicalB Bor.B BThisB BoperatorB BoutputsB BtrueB BifB
theB BgivenB BvalueB BisB Btrue.
B

console.log(falseB B||B Btrue)


//B B→B Btrue
console.log(falseB B||B Bfalse)
//B B→B Bfalse
AnB BexclamationB BmarkB B(!)B BindicatesB BNot.B BItB BisB BanB BoperatorB BthatB
overturnsB BtheB BsetB Bvalue,B BandB BitB BchangesB BfromB BtrueB BtoB BfalseB BandB
B

falseB BtoB Btrue.


B

TheB B||B BconsistsB BofB BtheB BlowestB BprecedenceB BofB BallB Boperators,B BthenB
&&,B BtheB BcomparisonB BoperatorsB B(>,B B==,B Betc.),B BandB BsoB Bon.B BTheB
B

exampleB BbelowB BstatesB BthatB BparenthesesB BareB Bnecessary:


B

1B B+B B1B B==B B2B B&&B B10B B*B B10B B>B B50
EmptyB Bvalues
NullB BandB BundefinedB BareB BtheB BonlyB BtwoB BtypesB BofB BspecialB BvaluesB BthatB
areB BusedB BtoB BindicateB BtheB Bnon-appearanceB BofB BanB BimportantB Bvalue.B
B

TheyB BcontainB BzeroB Bdata.


B

AutomaticB BtypeB Bconversion


EarlierB BIB BsaidB BthatB BJavaScriptB BacceptsB BpracticallyB BallB BgivenB
programs,B BincludingB BprogramsB BwithB BoddB Bbehaviors.B BAutomaticB BtypeB
B

conversionB BillustratesB BinB BtheB BfollowingB Bexpressions:


B

console.log(8B B*B Bnull)


//B B→B B0
console.log("5"B B-B B1)
//B B→B B4
console.log("5"B B+B B1)
//B B→B B51
console.log("five"B B*B B2)
//B B→B BNaN
console.log(falseB B==B B0)
//B B→B Btrue
WhenB ByouB BassignB BanB BoperatorB BtheB BwrongB Bvalue,B BJavaScriptB BsilentlyB
returnsB BthatB BvalueB BtoB BtheB BexactB BtypeB BitB BrequiresB BusingB BtheB BtypeB
B

coercionB Brule.B BInB BtheB BfirstB Bexpression,B BtheB BnullB BturnsB BtoB B0,B BandB
B

BtheB B5B BinB BtheB BsecondB BremainsB B5B B(fromB BstringB BtoB Bnumber).B BInB BtheB
BthirdB Bexpression,B BthereB BwasB BaB BstringB BconcatenationB BbeforeB BtheB

numericB Baddition,B BwhichB BconvertsB BtheB B1B BtoB B1B B(fromB BnumberB BtoB BaB
B

string).B BWhenB BoddB BnumbersB BsuchB BasB B"five"B BorB BundefinedB BchangesB
B

toB BtheB Bnumber,B BitB BgetsB BtheB BvalueB BofB BNaN.B BIfB ByouB BwantB BtoB
B

differentiateB BbetweenB BvaluesB BofB BtheB BsameB BtypeB BusingB B==,B BtheB
B

outputB BshouldB BbeB BtrueB BifB BtheB BvaluesB BareB BsimilarB BexceptB BNaN.B BIfB
B

youB BwantB BtoB BtestB BifB BaB BvalueB BcontainsB BaB BrealB Bvalue,B BuseB BtheB B==B
B

(or!B B=)B BoperatorB BtoB BcompareB Bit.B BToB BavertB BunexpectedB BtypeB
B

conversions,B BuseB BtheB Bthree-characterB BcomparisonB Boperators.


B
Short-circuitingB BofB BlogicalB Boperators
TheB B&&B BandB B||B BareB BcalledB BtheB BlogicalB Boperators.B BTheyB BareB BusedB BtoB
holdB BseveralB BtypesB BofB BvaluesB BinB BaB BspecificB Bway.B BTheyB BchangeB BtheB
B

valuesB BcontainedB BinB BtheB BleftB BsideB BtoB BBooleanB BtypeB BtoB Bdecide,B
B

althoughB BitB BdependsB BonB BtheB BoperatorsB BandB BtheB BtypeB BofB BgeneratedB
B

result,B BbutB BwillB BalwaysB BreinstateB BtheB BleftB BorB Bright-handB Bvalue.B BTheB
B

||B BoperatorB BsendsB BbackB BvalueB BtoB BtheB BleftB BwhenB BitB BcanB BbeB BchangedB
B

toB BtrueB BandB BwillB BreinstateB BtheB BvalueB BtoB BtheB Bright.
B

console.log(nullB B||B B"user")


//B B→B Buser
console.log("Kate"B B||B B"user")
//B B→B BKate
ThisB BfunctionB BisB BusedB BtoB BreturnB BvaluesB BtoB BitsB BdefaultB BvalueB BandB
placedB BwithinB BanB BemptyB BvalueB BasB BaB Breplacement.B BStringsB BandB
B

numbersB BtoB BBooleanB BvalueB BconversionB BrulesB BindicateB BthatB B0,B BNaN,B
B

andB BemptyB BstringB B(")B BcountB BasB BfalseB BwhileB BotherB BvaluesB BareB Btrue.B
B

ThereforeB B0B B||B B-1B BoutputsB B-1,B BandB B""B B||B B"!?"B ByieldsB B"!?".B BTheB B&&B
B

operatorB BoperatesB BidenticallyB BbutB BtheB BotherB BwayB Baround.B BWhenB


B

valuesB BtoB BtheB BleftB BcanB BbeB BchangedB BtoB Bfalse,B BreturnB BtheB Bvalue,B BorB
B

itB BsendsB BtheB BvalueB BtoB BtheB Bright.B BBothB BoperatorsB BevaluateB BtheB
B

valueB BtoB BtheB BrightB BonlyB BwhenB BitB BisB Brequired.B BForB Bexample,B BweB
B

haveB BtheB BfollowingB BvaluesB BsetB BasB BtrueB B||B BX,B BtheB BvalueB BofB BXB BwillB
B

beB BtrueB BandB BwillB BnotB BconsiderB Bit.B BTheB BsameB BruleB BappliesB BtoB BtheB
B

falseB B&&B BX,B BwhichB BtheB BxB BisB BfalseB BandB BwillB BoverlookB Bit.B BYouB BcanB
B

callB BthisB BprocessB BtheB Bshort-circuitB Bevaluation.


B

Summary
ThisB BchapterB BlooksB BatB BtheB BfourB BtypesB BofB BJavaScriptB Bvalues,B BwhichB
areB Bstrings,B Bnumbers,B BundefinedB BvaluesB BandB BBooleans.B BTheseB BvaluesB
B

areB BdevelopedB BbyB BinsertingB BtheirB BnamesB BasB Btrue,B BnullB BorB BvalueB
B

(13,B B"ABC").B BOperatorsB BcanB BintegrateB BandB BchangeB Bvalues.B BWeB


B

lookedB BatB BbinaryB BoperatorsB BforB BarithmeticB B(+,B B-,B B*,B B/,B BandB B%),B
B

stringB BconcatenationB B(+),B BcomparisonB B(==,B B!=,B B===,B B!==,B B<,B B>,B B<=,B B>=),B
B

andB BlogicB B(&&,B B||),B BandB BalsoB BvariousB BunaryB BoperatorsB B(-B BtoB BnullifyB
B

aB Bnumber,B B!B BtoB BnullifyB Blogically,B BandB BtypeB BofB BtoB BsearchB BforB BaB
B

value’sB Btype)B BandB BaB BternaryB BoperatorB B(?:)B BtoB BchooseB BoneB BofB BtwoB
B

valuesB BdependingB BonB BaB BthirdB Bvalue.B BYouB BwillB BgetB BsufficientB
B

informationB BtoB BuseB BJavaScriptB BlikeB BaB BsmallB Bcalculator,B BandB ByouB BwillB
B

improveB BinB BtheB BfollowingB Bchapters.


B

Exercise

WriteB BaB BJavaScriptB BpracticeB BtoB BbuildB BaB BvariableB BthroughB B


aB Buser-definedB Bname.
Solution
BB
Chapter 3: Program Structure
BB BB BB

WeB BwillB BbeginB BtheB BexpansionB BofB BtheB BJavaScriptB BprogrammingB


languageB BcommandsB BbeyondB BsentenceB BfragmentsB BandB Bnouns.
B

ExpressionsB BandB Bstatements


AB BblockB BofB BcodeB BthatB BmanufacturesB BaB BvalueB BisB BcalledB BanB
expression.B BAB BsingleB BvalueB BisB BwrittenB BpreciselyB BasB B22,B BorB
B

psychoanalysisB BisB BcalledB BanB Bexpression.B BAnB BexpressionB BwithinB BaB


B

binaryB BoperatorB BsetB BtoB BtwoB BexpressionsB BorB BwithinB BparenthesesB BisB
B

anB Bexpression.B BAnB BexpressionB BthatB BcanB BaccommodateB BotherB


B

expressionsB BcomparablyB BtoB BhowB BtheB BhumanB BlanguageB Btranslates.B BItB


B

enablesB BusB BtoB BdevelopB BexpressionsB BthatB BnarrateB BtheB BarbitrarilyB


B

complexB Bcomputations.B BWhenB BanB BexpressionB BisB BcomparableB BtoB BaB


B

sentenceB Bfragment,B BtheB BJavaScriptB BstatementB BwillB BcompleteB BtheB


B

sentence.B BAB BlistB BofB BstatementsB BisB BcalledB BaB Bprogram,B BandB BtheB BmostB
B

accessibleB BtypeB BofB BstatementB BisB BaB BlineB BofB BcodeB BwithB BaB BsemicolonB
B

endingB Bit.
B

ForB Binstance:
1;
!false;

WithB BthisB Bfunction,B BaB BstatementB BcanB BstandB Bindependently,B BandB BitB
canB BaddB BaB BfeatureB BthatB BchangesB BcolorsB BoccasionallyB BtoB BaB BscreenB BorB
B

modifyB BtheB BinnerB BstateB BofB BtheB BmachineB BinfluencingB BtheB BfollowingB
B

statementsB BafterB Bit.


B

Bindings

JavaScriptB BusesB BbindingB BofB BvariablesB BtoB BholdB Bvalues,B BforB Binstance:
GetB BmoneyB B=B B5B B*B B5;
GetB BisB BtheB BkeywordB BinB BthatB Bstatement,B BandB BitB BmeansB BthatB BtheB
sentenceB BwillB BspecifyB BaB BbindingB BtogetherB BwithB BtheB BbindingB BnameB
B

andB BvalueB BcanB BbeB BattachedB BusingB BtheB B=B BoperatorB BandB BanB
B

expression.B BUseB BaB BdefinedB BbindingB BasB BanB Bexpression,B BanB BexpressionB
B

containingB BtheB BbindingB Bvalue.B BHereB BisB BanB BexampleB Bbelow:


B

letB BtenB B=B B10;


console.log(tenB B*B Bten);
//B B→B B100
TheB B=B BoperatorB BisB BusedB BonB BexistingB BbindingsB BtoB BremoveB BtheB
bindingB BfromB BaB BsetB BvalueB BandB BpointB BthemB BtoB BaB BnewB Bone.
B

letB BmoodB B=B B"light";


console.log(mood);

//B B→B Blight


moodB B=B B"dark";
console.log(mood);

//B B→B Bdark


DefiningB BaB BbindingB BwithoutB BassigningB BaB BvalueB BwillB BresultB BinB
nothingB BtoB Bhold.B BTherefore,B BaskingB BforB BtheB BvalueB BofB BaB BbindingB
B

produceB BtheB BundefinedB Bvalue.B BYouB BcanB BdefineB BmultipleB BbindingB BbyB
B

aB BsingleB BstatementB BdividedB BbyB Bcommas.


B

letB BoneB B=B B1,B BtwoB B=B B2;


console.log(oneB B+B Btwo);
//B B→B B3
UseB BtheB BvarB BandB BconstB BwordsB BtoB BdevelopB BbindingsB Bfamiliarly:
varB BnameB B=B B"Ayad";
constB BgreetingB B=B B"HelloB B";
console.log(greetingB B+B Bname);
//B B→B BHelloB BAyad
TheB BwordB BconstB BmeansB Bconstant.B BItB BdescribesB BaB BresoluteB Bbinding,B
whichB BpointsB BtoB BitsB BsetB BvalueB BforB BitsB Blifetime.B BTheseB BwordsB BareB
B

oftenB BusedB BtoB BdeclareB BaB BnameB BtoB BaB BvalueB BtoB BenableB BeasyB
B

referenceB BlaterB Bon.


B

BindingB Bnames
AlthoughB BthereB BareB BsomeB BreservedB BwordsB BlikeB Bconst,B Bclass,B Bdefault,B
break,B Bcontinue,B Bdelete,B Bdo,B BelseB ByetB BanyB BwordB BcanB BbeB BcalledB BaB
B

bindingB Bname,B BitB BcanB BalsoB BconsistB BofB BdigitsB BbutB BdoB BnotB BbeginB BtheB
B

statementB BwithB BaB Bfigure.B BAB BbindingB BnameB BcanB BalsoB BcontainB BdollarB
B

signsB B($)B BorB BunderscoresB B(_)B BbutB BdoB BnotB BentertainB BanyB BotherB
B

specialB BcharactersB BorB Bpunctuation.


B

TheB Benvironment
TheB BgroupB BofB BbindingB BandB BvaluesB BexistingB BatB BaB BstipulatedB BtimeB BisB
BknownB BasB BtheB Benvironment.B BWhenB ByouB BlaunchB BaB Bprogram,B BtheB
BenvironmentB BholdsB BtheB BlanguageB BstandardB BbindingB BandB BoftenB

containsB BtheB BbindingB BthatB BcreatesB BinteractionB BwithB BsystemB


B

surroundings.B BForB Binstance,B BaB BbrowserB BcarriesB BfunctionsB BthatB


B

communicateB BwithB BtheB BlaunchedB BwebsiteB BasB BwellB BasB BreadB BtheB
B

keyboardB BandB BmouseB Binput.


B

Functions

AB BbitB BofB BprogramB BenclosedB BinB BvalueB BisB BcalledB BaB Bfunction,B BandB
theseB BvaluesB BareB BaddedB BtoB BlaunchB BtheB BwrappedB Bprogram.B BForB
B

instance,B BaB BfunctionB BthatB BdisplaysB BaB BsmallB BdialogB BboxB BforB BuserB
B

input.
B
PromptB B("EnterB Bpasscode");
TheB BprocessB BofB BeffectingB BaB BfunctionB BisB BdescribedB BasB BaB Bcalling,B
invoking,B BorB Bapplying.B BCallB BaB BfunctionB BbyB BinsertingB BparenthesesB
B

followingB BanB BexpressionB BthatB BprovidesB BaB BfunctionB Bvalue.B BSetB BtheB
B

parenthesisB BvalueB BtoB BtheB BprogramB BwithinB BtheB Bfunction.B BDefineB


B

valuesB BsetB BtoB BfunctionsB BasB Barguments.


B

TheB Bconsole.logB Bfunction


InB BtheB BaboveB Bsamples,B BweB BusedB BtheB Bconsole.logB BtoB BoutputB Bvalues.B
AllB BmajorB BbrowsersB ButilizeB BtheB Bconsole.logB BfunctionB BtoB BstateB BoutB
B

itsB BargumentsB BtoB BtheB BdeviceB BthatB BoutputsB BtheB Btext.B BInB BmodernB
B

browsers,B BtheB BoutputB BisB BoftenB BinB BtheB BJavaScriptB BconsoleB BthatB BisB
B

invisibleB BbyB Bdefault;B ByouB BcanB BtapB BtheB BF12B BcommandB BonB ByourB
B

keyboardB BorB BtheB Bcommand-option-IB BonB BMac.B BBindingB BnamesB BdoB


B

notB BaccommodateB BperiodB Bcharacters,B BbutB Bconsole.logB BdoesB BbecauseB


B

itB BisB BanB BexpressionB BthatB BreclaimsB BtheB BlogB BpropertyB BfromB BtheB
B

consoleB BbindingB Bvalue.


B

ReturnB Bvalues
FunctionsB BareB BusedB BtoB BproduceB BsideB Beffects.B BTheyB BcanB BalsoB BprovideB
valuesB BthatB BdoB BnotB BneedB BsideB Beffects.B BForB Binstance,B BtheB BfunctionB
B

Calculate.maxB BwillB BtakeB BaB BsumB BofB BnumberB BargumentsB BandB BreturnsB
B

theB Bgreatest.
B

console.log(Calculate.max(2,B B4));
//B B→B B4
JavaScriptB BregardsB BanythingB BthatB BprovidesB BvalueB BasB BanB Bexpression,B
whichB BenablesB BfunctionB BcallsB BtoB BattachB BintoB BtheB BsubstantialB
B

expression.B BLet’sB BcallB BtheB BCalculate.min,B BwhichB BisB BaB BdirectB BoppositeB
B

toB BCalculate.max:
B
console.log(Math.min(2,B B4)B B+B B100);
//B B→B B102
ControlB Bflow
WhenB BmoreB BthanB BoneB BstatementB BisB BwithinB BaB Bprogram,B BtheyB
executeB BinB BaB BstoryB BformB BfromB BtheB BbeginningB BofB BtheB BcodeB BtoB BtheB
B

end.B BThisB BtypeB BofB BprogramB BconsistsB BofB BtwoB BtypesB BofB Bstatement;B
B

theB BfirstB BdemandB BnumbersB BfromB BtheB BuserB BwhileB BtheB BsecondB
B

displaysB BtheB BsquareB BofB BtheB BnumberB BandB BexecutesB BimmediatelyB


B

afterB BtheB Bfirst.


B

letB BtheNumberB B=B BNumber(prompt("SelectB BaB BdigitB B"));


console.log("YourB BdigitB BisB BtheB BsquareB BrootB BofB B"B B+B BtheNumberB B*B
theNumber);
B

AB BvalueB BisB BchangedB BtoB BaB BnumberB BbyB BtheB BfunctionB BnumberB BandB
outputsB BaB BstringB Bvalue.
B

ConditionalB Bexecution
TheB BkeyboardB BisB BusedB BtoB BdevelopB BconditionalB BexecutionsB BinB
JavaScript.B BYouB BmayB BwantB BsomeB BcodeB BtoB BexecuteB Bif,B BandB BonlyB Bif,B BaB
B

specificB BconditionB BisB Bpositive.B BLetB BusB BdisplayB BtheB BsquareB BofB BtheB
B

inputB BifB BonlyB BitB BisB BaB Bnumber.


B

letB BtheNumberB B=B BNumber(prompt("SelectB BaB BdigitB B"));


ifB B(!B BNumber.isNaN(theNumber))B B{
console.log("YourB BdigitB BisB BtheB BsquareB BrootB BofB B"B B+
theNumberB B*B BtheNumber);
}

TheB BifB BkeywordB BperformsB BorB BevadesB BaB BstatementB BdeterminedB BbyB
theB BBooleanB BexpressionB Bvalue.B BTypeB BtheB BdeterminingB BexpressionB
B
afterB BtheB BkeyboardB BwithinB BtheB BparenthesesB BaccompaniedB BbyB BtheB
B

statementB BtoB Baccomplish.


B

TheB BNumber.isNaNB BfunctionB BisB BaB Bhigh-levelB BJavaScriptB BfunctionB BthatB


outputsB BonlyB BtrueB BifB BtheB BstatementB BisB BdeclaredB BasB BNaN.B BTheB
B

numberB BfunctionB BreturnsB BNaNB BwhenB BanB BassignedB BstringB BisB BnotB BaB
B

validB Bnumber.B BStatementsB BafterB BtheB BifB BstatementB BisB BenclosedB BinB
B

bracesB B({and}).B BBracesB BareB BusedB BtoB BcategorizeB BdifferentB BnumbersB BofB
B

statementB BwithinB BanB BindividualB Bstatement.


B

28

ifB B(1B B+B B1B B==B B2)B Bconsole.log("It'sB Btrue");


//B B→B BIt'sB Btrue
TheB BelseB BkeywordB BcanB BbeB ButilizedB BtogetherB BwithB BtheB BifB BstatementB
toB BprovideB BtwoB BdifferentB BexecutionB Bpaths.
B

letB BtheNumberB B=B BNumberB B(prompt("SelectB BaB Bdigit"));


ifB B(!B BNumber.isNaN(theNumber))B B{
console.log("YourB BdigitB BisB BtheB BsquareB BrootB BofB B"B B+
theNumberB B*B BtheNumber);
}B BelseB B{
console.log("Hey.B BWhyB Bdidn'tB ByouB BgiveB BmeB BaB Bnumber?");
}

IfB BthereB BareB BmoreB BthanB BtwoB BpathsB BtoB BchooseB Bfrom,B ByouB BcanB
“chain”B Bmultiple
B

if/elseB BpairsB Btogether.B BBelowB BisB BanB Bexample:


letB BnumB B=B BNumberB B(prompt("PickB BaB Bnumber"));
ifB B(numB B<B B10)B B{
console.log("Small");
}B BelseB BifB B(numB B<B B100)B B{
console.log("Medium");

}B BelseB B{
console.log("Large");
}

TheB BprogramB BconfirmsB BifB BtheB BnumB BisB BlessB BthanB B10,B BandB BifB BitB Bis,B BitB
selectsB BthatB Bbranch,B BandB BthenB BdisplaysB B"Small".B BButB BifB BtheB BnumB BisB
B

greaterB BthanB B10,B BitB BselectsB BtheB BelseB BbranchB BwhichB BconsistsB BofB BaB
B

secondB BifB BstatementB BofB BitsB Bown.


B

while and do loops


BB BB BB

ThisB BisB BtheB BwayB BtoB BwriteB BaB BprogramB BthatB BdisplaysB BallB BtheB BevenB
numbersB BfromB B0B BtoB B12.
B

console.log(0);
console.log(2);
console.log(4);
console.log(6);
console.log(8);
console.log(10);
console.log(12);

AB BwayB BtoB BrunB BaB BclockB BofB BcodeB BmultipleB BtimesB BisB BdescribedB BasB BaB
loop.
B

TheB BloopingB BcontrolB BflowB BenablesB BtheB BuserB BtoB BreturnB BtoB BcertainB
pointsB BinB BwrittenB BprogramsB BandB BredoB BitB BwithB BtheB BcurrentB BstateB BofB
B

theB Bprogram.B BIntegrateB BthisB BwithB BaB BbindingB BthatB BenumeratesB BasB
B

follows:
B

letB BnumberB B=B B0;


whileB B(numberB B<=B B12)B B{
console.log(number);
numberB B=B BnumberB B+B B2;
}

//B B→B B0
//B B→B B2
//B B…B Betcetera
AB BstatementB BthatB BbeginsB BwithB BtheB BkeywordB BandB BatB BtheB BsameB BtimeB
producingB BaB Bloop.B BTheB BkeywordB BwhileB BaccompaniedB BbyB BanB
B

expressionB BinB BparenthesesB BfollowedB BbyB BaB BstatementB BlikeB BtheB BifB
B

statement.B BTheB BloopB BbecomesB BcontinuousB BuntilB BtheB BexpressionB


B

providesB BaB BvalueB BthatB BstatesB BtrueB BwhenB BtranslatedB BtoB BBoolean.B
B

EachB BtimeB BtheB BloopB Brepeats,B BnumbersB BadoptB BaB BnumberB BtwiceB BofB
B

theirB BpreviousB Bvalue.B BLetB BusB BwriteB BaB BprogramB BthatB BevaluatesB BandB
B

displayB BtheB BvalueB BofB B210B B(2B BraisedB BtoB BtheB BpowerB BofB B10th).B BWeB BwillB
B

utilizeB BtwoB Bbindings.B BOneB BtoB BkeepB BanB BeyeB BonB BourB BresultB BandB BtheB
B

otherB BtoB BcalculateB BhowB BmanyB BtimesB BtheB BvalueB BofB BtwoB BmultipliedB
B

byB BtheB Bresult.B BItB BmultipliesB BuntilB BtheB BsecondB BbindingB BreachesB B10:
B

letB BresultB B=B B1;


letB BcounterB B=B B0;
whileB B(counterB B<B B10)B B{
resultB B=B BresultB B*B B2;
counterB B=B BcounterB B+B B1;
}
console.log(result);

//B B→B B1024


AB BdoB BloopB BisB BaB BcommandB BstructureB BrelatedB BtoB BaB BwhileB Bloop.B BAB BdoB
loopB BalwaysB BtakeB BplaceB BatB BleastB BonceB BinB BaB Bstatement,B BandB BthenB BitB
B
beginsB BtoB BcheckB BifB BitB BendsB BafterB BtheB BfirstB BexecutionB Bonly.B BFollowB
B

theB BfollowingB Bsteps:


B

letB ByourName;
doB B{
yourNameB B=B Bprompt("WhoB BareB Byou?");
}B BwhileB B(!B ByourName);
console.log(yourName);
BB
BB

for loops
BB

AB BlotB BofB BloopsB BfollowB BtheB BwhileB BloopB Bpattern,B BcreatingB BaB BcounterB
bindingB BtoB BtrackB BtheB Bloop'sB Bprogress.B BThenB BaB BwhileB BloopB BwithB BaB
B

testB BexpressionB BtoB BseeB BifB BtheB BcounterB BreachesB BtheB BsetB Bvalue.
B

forB B(letB BnumberB B=B B0;B BnumberB B<=B B10;B BnumberB B=B BnumberB B+B B4)B B{
console.log(number);
}

//B B→B B0
//B B→B B4
//B Betc
TheB BparenthesesB BmustB BconsistB BofB BtwoB BsemicolonsB BafterB BtheB
keyword,B BtheB BfirstB BpartB BthatB BisB BbeforeB BtheB BfirstB BsemicolonB
B

separatesB BtheB BloopB BbyB BdescribingB BaB Bbinding.B BTheB BotherB BpartB BisB BtheB
B

statementB BthatB BdeterminesB BifB BtheB BloopB BshouldB Bcontinue.B BHereB BisB
B

theB BcodeB BthatB BevaluateB B210B BusingB BforB BinsteadB BofB Bwhile:
B

letB BresultB B=B B1;


forB B(letB BcounterB B=B B0;B BcounterB B<B B10;B BcounterB B=B BcounterB B+B B1)B B{
resultB B=B BresultB B*B B2;
}
console.log(result);

//B B→B B1024


BreakingB BOutB BofB BaB BLoop
ThereB BareB BotherB BwaysB BtoB BendB BaB BloopB BotherB BthanB BmakingB BaB BloopingB
conditionB BgiveB BaB Bfalse.B BBreakB BcanB BinfluenceB BjumpingB BoutB BofB BtheB
B

confinedB Bloop.B BTheB BbreakB BstatementB BevaluatesB BthisB BprogramB BifB BtheB
B

firstB Bnumber,B BwhichB BisB BbothB BgreaterB BthanB BorB BequalB BtoB B20,B BandB BcanB
B

beB BdividedB BbyB B7.


B

forB B(letB BcurrentB B=B B20;B BcurrentB B=B BcurrentB B+B B1)B B{
ifB B(currentB B%B B7B B==B B0)B B{
console.log(current);
break;
}
}

//B B→B B21


TheB B(%)B BoperatorB BisB BusedB BtoB BcheckB BifB BaB BnumberB BcanB BbeB BdividedB BbyB
anotherB Bnumber.B BIfB BitB BcanB BbeB Bdivided,B BthenB BtheB BremainingB BdivisionB
B

isB Bzero.B BTheB BforB BinB BtheB BexampleB BisB BnotB BcheckedB BatB BtheB BendB BofB
B

theB Bloop,B BwhichB BmeansB BuntilB BtheB BbreakB BstatementB BinsideB BisB
B

implementedB BtheB BloopB BbecomesB BinfiniteB BandB BneverB Bstops.


B

UpdatingB BbindingsB Bsuccinctly


WhenB ByouB BareB BinB BaB Bloop,B BprogramsB BwillB BupdateB BaB BbindingB
regularlyB BtoB BstoreB BaB BvalueB BbasedB BonB BitsB BpreviousB Bvalue.
B

counterB B=B BcounterB B+B B1;


JavaScriptB BoffersB BaB Bshortcut.
counterB B+=B B1;
RelatedB BshortcutsB BfunctionB BforB BseveralB BotherB Boperators,B BlikeB BresultB
*=B B2B BtoB BmultiplyB BresultB BorB BcounterB B-=B B1B BtoB BcountB BinB BdescendingB
B

order.
B

ThisB BenablesB BusB BtoB BminimizeB BourB BcountingB Bexample.


forB B(letB BnumberB B=B B0;B BnumberB B<=B B12;B BnumberB B+=B B2)B B{
console.log(number);
}

ForB BcounterB B+=B B1B BandB BcounterB B-=B B1,B BhereB BareB BshorterB Bequivalents:
counter++B BandB Bcounter--.
DispatchingB BonB BaB BvalueB BwithB Bswitch
DispatchingB BonB BaB BvalueB BwithB BswitchB BCodesB BcanB BlookB BlikeB Bthis:
ifB B(xB B==B B"value1")B Baction1();
elseB BifB B(xB B==B B"value2")B Baction2();
elseB BifB B(xB B==B B"value3")B Baction3();
elseB BdefaultAction();
TheB BswitchB BisB BusedB BtoB BexpressB BtheB BaboveB BformB BofB BdispatchB
straightforwardly.B BBelowB BisB BaB BgoodB Bexample:
B

switchB B(prompt("WhatB BisB BtheB BatmosphereB Blike?"))B B{


caseB B"rainy":
console.log("DoB BnotB BforgetB BtoB BcomeB BwithB BanB Bumbrella.");
break;

caseB B"sunny":
console.log("BeB BlightB BwithB ByourB Bdressing.");
caseB B"cloudy":
console.log("MoveB Bout.");
break;
default:

console.log("WeatherB BtypeB BUnknown!");


break;
}
Capitalization

NamesB BbindingB BdoB BnotB BallowB Bspaces,B BbutB BitB BsupportsB BtheB BusageB BofB
severalB BwordsB BtoB BdefineB BtheB BbindingB Bvalues.B BHereB BareB BaB BfewB BtypesB
B

thatB BcanB BbeB ButilizedB BwhenB BbindingB BnamesB BwithB BdifferentB Bwords:
B

fuzzylittleturtle
fuzzy_little_turtle
FuzzyLittleTurtle
fuzzyLittleTurtle
Comments

SometimesB BrawB BcodesB BdoB BnotB BtransmitB BeveryB BsingleB BpieceB BofB
informationB BthatB ByouB BwantB BtheB BprogramB BtoB BsendB BtoB BreadersB BorB
B

spreadsB BtheB BmessageB BinB BaB BwayB BpeopleB BwillB BfindB BitB BhardB BtoB
B

decipher.B BOtherB BtimesB ByouB BfeelB BlikeB ByouB BshouldB BattachB BsomeB
B

similarB BthoughtsB BtoB ByourB Bprogram,B BtheB BcommentB BperformsB BthisB


B

function.B BAB BcommentB BisB BaB BbitB BchunkB BofB BtheB BtextB BcontainedB BinB BaB
B

program,B BbutB BtheB BcomputerB BignoresB Bit.B BToB BcodeB BaB BsingleB BlineB
B

comment,B BuseB BtheB BtwoB BslashB BcharactersB B(//),B BfollowedB BbyB BtheB
B

commentB Btext.
B

letB BaccountBalanceB B=B BcalculateBalance(account);


//B BIt'sB BaB Byellow-orangeB BonB BtheB BmangoB BtreeB BaccountBalance.adjust();
//B BCatchingB BgreenB BtattersB BinB BourB Bhome.B BletB BreportB B=B BnewB BReport();
//B WhereB
B BtheB BsunB andB
B theB
B BmoonB meets:B
B

addToReport(accountBalance,B Breport);
B
//B BIt'sB BaB BlargeB Bhallway,B BandB BtheB BlightsB BareB BquiteB Bamazing.
AB B//B BcommentB BappearsB BonlyB BatB BtheB BendB BofB BtheB Bline.B BAnyB BtextB
withinB B/*B BandB B*/B BignoreB Bit,B BandB BitB BdoesB BnotB BmatterB BifB BitB BcontainsB
B

lineB Bbreaks.B BItB BisB BusedB BtoB BattachB BblocksB BofB BinformationB BaboutB BaB
B

programB BorB Bfile.


B

Summary

NowB ByouB BunderstandB BthatB ByouB BcanB BdevelopB BaB BprogramB BthroughB BtheB
useB BofB Bstatements,B BwhichB BstatementB BitselfB BcanB BcontainB BseveralB
B

statements.B BStatementsB BconsistB BofB Bexpressions,B BandB ByouB BcanB BcreateB


B

expressionsB BthroughB BsmallerB Bexpressions.B BSettingB BstatementsB BafterB


B

eachB BanotherB BprovidesB BanB BexecutedB BprogramB BfromB BtopB BtoB Bbottom.B
B

DisturbancesB BcanB BalsoB BcomeB BintoB BtheB BflowB BofB BinfluenceB BthroughB
B

conditionalB B(if,B Belse,B BandB Bswitch)B BandB BloopingB B(while,B Bdo,B BandB Bfor)B
B

statements.B BAndB BweB BtouchedB Bbindings,B BtheyB BcategorizeB BbitsB BofB BdataB
B

underB BaB Bname,B BandB BtheyB BcanB BalsoB BtrackB BstateB BwithinB BtheB Bprogram.B
B

TheB BdefinedB BbindingsB BenjoyB BtheB BenvironmentB Bbetter.B BWeB BalsoB


B

touchedB BonB BtheB BfunctionsB BsectionB BbeingB BuniqueB BvaluesB BthatB


B

summarizeB BaB BpieceB BofB Bprogram.B BYouB BcanB BcallB BthemB BbyB BtypingB
B

functionName(argument1,B Bargument2).B BThisB BtypeB BofB BfunctionB BcallB BisB


B

anB BexpressionB BandB BcanB BprovideB Bvalue.


B

Exercise

WriteB BaB BJavaScriptB BprogramB BthatB BdisplaysB BtheB BlargerB BandB BacceptsB
doubleB Bintegers.
B

Solution
ItB BisB BimportantB BtoB BknowB BthatB ByouB BcanB BwriteB B.lengthB BatB BtheB BendB BofB
aB BstringB BtoB BfindB BitsB Blength.
B

letB BabcB B=B B"abc";


console.log(abc.length);

//B B→B B3
Chapter 4: FunctionsBB BB

FunctionsB BareB BtheB BalphaB BandB BomegaB BofB BJavaScriptB BprogrammingB


Blanguage.B BTheB BconceptB BofB BenclosingB BaB BbitB BofB BprogramB BcontainedB BinB
BvalueB BhasB BaB BlotB BofB Badvantages.B BItB BprovidesB BaB BwayB BtoB BorganizeB
BmoreB BprominentB Bprograms,B BtoB BminimizeB Brepetition,B BrelateB BnamesB
BwithB Bsubprograms,B BandB BseparateB BprogramsB BfromB Bthemselves.B
BFunctionsB BareB BusedB BtoB BdescribeB BnewB Bwords.
DefiningB BaB Bfunction
AB BfunctionB BisB BaB BsystematicB BbindingB BwherebyB BaB BfunctionB BdefinesB BtheB
BbindingB Bvalue.B BTheB BcodeB BbelowB BindicatesB BaB BfunctionB BthatB BprovidesB
BtheB BsquareB BofB BaB BstatedB Bnumber:
constB BsquareB B=B Bfunction(x)B B{
returnB BxB B*B Bx;
};
console.log(square(12));

//B B→B B144


CreateB BaB BfunctionB BwithB BanB BexpressionB BthatB BbeginsB BwithB BtheB
BkeyboardB Bfunction.B BFunctionsB BconsistsB BofB BaB BbodyB BandB BaB BsetB BofB
BparametersB BthatB BaccommodatesB BtheB ByetB BtoB BbeB BexecutedB BstatementsB
BwhenB ByouB BcallB BaB Bfunction.B BTheB BfunctionB BbodyB BshouldB BalwaysB BbeB
BenclosedB BinB Bbraces,B BevenB BwhenB BitB BisB BjustB BanB BindividualB Bstatement.B
BAB BfunctionB BcanB BcontainB BseveralB BparametersB BorB BzeroB Bparameter.B BInB
BtheB BbelowB Bexample,B BmakeNoiseB BcontainsB BnoB BparameterB BnamesB BandB
BpowerB BconsistsB BofB Btwo:
constB BmakeNoiseB B=B Bfunction()B B{
console.log("Pling!");
};
makeNoise();

//B B→B BPling!


constB BpowerB B=B Bfunction(base,B Bexponent)B B{
letB BresultB B=B B1;
forB B(letB BcountB B=B B0;B BcountB B<B Bexponent;B Bcount++)B B{
resultB B*=B Bbase;
}

returnB Bresult;
};

console.log(power(2,B B10));
//B B→B B1024
SomeB BfunctionsB BcanB BcreateB BvaluesB BsuchB BasB BsquareB BandB BpowerB BwhileB
BsomeB BresultsB BonlyB BintoB BaB BsideB Beffect.B BAB BreturnB BkeywordB BthatB BdoesB
BnotB BcontainB BanB BexpressionB BatB BtheB BendB BwillB BbeB BreturnedB BasB
Bundefined.
Bindings and scopes
BB BB

EveryB BbindingB BconsistsB BofB BaB BscopeB BthatB BenablesB BtheB BvisibilityB BofB
BtheB Bbinding.B BWheneverB ByouB BcallB BaB Bfunction,B BnewB BillustrationsB BofB
BbindingB BareB Bdeveloped.B BThisB BcreatesB BseparationB BbetweenB Bfunctions,B
BeveryB BfunctionB BcallB BbehavesB BinB BitsB BownB BworldB BandB BisB BeasyB BtoB
Bunderstand.B BFunctionsB BthatB BwereB BdeclaredB BwithB BtheB BvarB BkeywordB
BinB BtheB Bpre-2015B BJavaScriptB BandB BcanB BbeB BseenB BthroughoutB BtheB BglobalB
Bscope.B BTheyB BareB BabsentB BinB BaB Bfunction.
letB BxB B=B B10;
ifB B(true)B B{
letB ByB B=B B20;
varB BzB B=B B30;
console.log(xB B+B ByB B+B Bz);
//B B→B B60
}

//B ByB BisB BnotB BvisibleB Bhere


console.log(xB B+B Bz);
//B B→B B40
NestedB Bscope
JavaScriptB BdifferentiateB BbetweenB BtheB BglobalB BandB BlocalB Bbindings.B BYouB
BcanB BcreateB BblockB BandB BfunctionsB BwithinB BtheB BotherB BfunctionsB BandB
BblocksB BmanufacturingB BseveralB BdegreesB BofB Blocality.B BForB Binstance,B BthisB
BfunctionB BproducesB BtheB BneededB BcomponentsB BtoB BmakeB BaB BgroupB
BhummusB BcontainsB BanotherB BfunctionB BwithinB Bit:
constB BhummusB B=B Bfunction(factor)B B{
constB BingredientB B=B Bfunction(amount,B Bunit,B Bname)B B{
letB BingredientAmountB B=B BamountB B*B Bfactor;
ifB B(ingredientAmountB B>B B1)B B{
unitB B+=B B"s";
}

console.log(`${ingredientAmount}B B${unit}B B${name}`);


};

ingredient(1,B B"can",B B"chickpeas");


ingredient(0.25,B B"cup",B B"tahini");
ingredient(0.25,B B"cup",B B"lemonB Bjuice");
ingredient(1,B B"clove",B B"garlic");
ingredient(2,B B"tablespoon",B B"oliveB Boil");
ingredient(0.5,B B"teaspoon",B B"cumin");
};

TheB BcodeB BwithinB BtheB BcomponentB BfunctionB BcanB BaccessB BtheB BfactorB
BbindingB BfromB BtheB BouterB Bfunction.B BTheB BsetB BofB BbindingsB BaccessibleB
BwithinB BaB BblockB BisB BdecidedB BbyB BtheB BblockB BpositionB BinB BtheB BprogramB
Btext.B BEveryB BlocalB BscopeB BcanB BaccessB BtheB BcontainedB BlocalB BscopeB BandB
BeveryB BscopeB BcanB BasB BwellB BaccessB BtheB BglobalB Bscope.B BThisB BconceptB BisB
BnamedB BlexicalB Bscoping.
FunctionsB BasB Bvalues
AB BfunctionB BbindingB BoftenB BbehavesB BasB BaB BnameB BforB BaB BparticularB
BblockB BofB Bprogram.B BThisB BtypeB BofB BbindingB BdoesB BnotB BchangeB BbecauseB
BitB BisB Bdefined.B BFunctionsB BcanB BbeB BusedB BinB BarbitraryB BexpressionsB BasB
BwellB BasB BusedB BtoB BsaveB BaB BfunctionB BvalueB BintoB BaB BnewB Bbinding.B BAB
BbindingB BthatB BstoresB BaB BfunctionB BisB BaB BsystematicB BbindingB BandB BaB BnewB
BvalueB BcanB BbeB BassignedB Blike:
letB BlaunchMissilesB B=B Bfunction()B B{
missileSystem.launch("now");
};

ifB B(safeMode)B B{
launchMissilesB B=B Bfunction()B B{/*B BdoB BnothingB B*/};
}

DeclarationB Bnotation
ThereB BisB BaB BlittleB BwayB BtoB BgenerateB BaB BfunctionB Bbinding.B BWhenB ByouB
BuseB BtheB BfunctionB BkeywordB BatB BtheB BbeginningB BofB BaB Bstatement,B BitB BwillB
BfunctionB Bdifferently.
functionB Bsquare(x)B B{
returnB BxB B*B Bx;
}

ThisB BstatementB BdescribesB BtheB BbindingB BsquareB BandB BdirectsB BitB BatB BaB
BstatedB Bfunction.B BThisB BtypeB BofB BfunctionB BdefinitionB BconsistsB BofB BoneB
Bprecision.
console.log("MyB BmindB BtellsB BmeB BeveryB Btime:",B Bfuture());
functionB Bfuture()B B{
returnB B"IllB BsurpassB BBillB BGates";
}

ArrowB Bfunctions
FunctionsB BcontainsB BaB BthirdB BnotationB BthatB BdoesB BnotB BlookB BidenticalB
BtoB BtheB Bothers.B BYouB BcanB BuseB BtheB BarrowB B(=>)B BasB BanB BalternativeB BtoB
BtheB BfunctionB Bkeyword.B BTheB BarrowB B(=>)B BcontainsB BanB BequalB BsignB BandB
BtheB BgreaterB BthanB Bcharacter.
constB BpowerB B=B B(base,B Bexponent)B B=>B B{
letB BresultB B=B B1;
forB B(letB BcountB B=B B0;B BcountB B<B Bexponent;B Bcount++)B B{
resultB B*=B Bbase;
}

returnB Bresult;
};

IfB ByouB BhaveB BjustB BoneB BparameterB Bname,B BexcludeB BtheB BparenthesesB
BsurroundingB BtheB BparameterB Blist.B BSometimesB BtheB BbodyB BisB BaB BsingleB
BexpressionB BinsteadB BofB BaB BblockB BofB Bbraces,B BtakingB BbackB BtheB
BexpressionB BfromB BtheB Bfunction.B BTherefore,B BsquareB BdefinitionsB
BperformB BtheB BsameB Btask.
constB Bsquare1B B=B B(x)B B=>B B{returnB BxB B*B Bx;};
constB Bsquare2B B=B BxB B=>B BxB B*B Bx;
WhenB BthereB BisB BnoB BparameterB BonB BanB BarrowB Bfunction,B BitsB BparameterB
BlistB BbecomesB BaB BsetB BofB BunoccupiedB BandB BineffectiveB Bparentheses.
constB BhornB B=B B()B B=>B B{
console.log("Toot");
};

YouB Bdon’tB BhaveB BtoB BuseB BbothB BtheB BfunctionB BexpressionsB BandB BarrowB
BfunctionsB BinB BtheB Blanguage,B BtheyB BofferB BandB BperformB BtheB BsameB
Boperations.
TheB BcallB Bstacks
LetB BusB BtakeB BsomeB BtimeB BtoB BseeB BhowB BcontrolB BgoesB BthroughB
Bfunctions.B BBelowB BisB BaB BsimpleB BprogramB BmakingB BfewB BfunctionB Bcalls:
functionB Bgreet(who)B B{
console.log("HelloB B"B B+B Bwho);
}
greet("Harry");
console.log("Bye");

TheB BgreetingsB BcallB BinfluencesB BtoB BcontrolB BtoB BjumpB BtoB BtheB BbeginningB
BofB BtheB Bfunction.B BTheB BfunctionB BcallB Bconsole.logB BgetsB BitsB BjobB BdoneB
BandB BseizeB Bcontrol,B BandB BthenB BsendB BcontrolB BbackB BtoB BtheB Bfunction.B
BTheB BfunctionB BcycleB BendsB BthereB BandB BtransfersB BbackB BtoB BtheB BplaceB
BthatB BcallsB Bit.B BTheB BflowB BofB BcontrolB BisB Bbelow:
notB BinB Bfunction
inB Bgreet
inB Bconsole.log
inB Bgreet
notB BinB Bfunction
inB Bconsole.log
notB BinB Bfunction
TheB BcomputerB BhasB BtoB BrecollectB BtheB BcontextB BinB BwhichB BtheB BcallB
sequencesB BoccurredB BbecauseB BfunctionsB BgoB BbackB BtoB BwhereB Bit'sB BcalledB
B

position.B BWhenB BConsole.logB Bcompletes,B BitB BmustB BreturnB BtoB BtheB BendB
B

ofB BtheB Bprogram.B BAB BcallB BstackB BisB BaB BplaceB BwhereB BtheB BcomputerB
B

storesB BthisB Bcontext.B BWheneverB ByouB BcallB BaB Bfunction,B BtheB BpresentB
B

contextB BsavesB BatB BtheB BtopB BofB BthisB Bstack.B BByB BtheB BtimeB BaB BfunctionB
B

goesB Bback,B BitB BeradicatesB BtheB BtopB BcontextB BandB ButilizesB BtheB BcontentB
B

forB BcontinualB Bexecution.


B

TheB BstackB BneedsB BspaceB BtoB BbeB BsavedB BintoB BwithinB BtheB BcomputerB
memory.B BTheB BbelowB BcodeB BexplainsB BthisB BbyB BqueryingB BtheB BcomputerB
B

thatB BcreatesB BzeroB BlimitationB BbetweenB BtwoB BfunctionsB BbackB BandB Bforth.
B

functionB Bchicken()B B{
returnB Begg();
}

functionB Begg()B B{
returnB Bchicken();
}

console.log(chicken()B B+B B"B BcameB Bfirst.");


//B B→B B??
OptionalB BArguments
TheB BbelowB BcodeB BfunctionsB BproperlyB BwithoutB Binterference:
functionB Bsquare(x)B B{returnB BxB B*B Bx;}
console.log(square(4,B Btrue,B B"hedgehog"));
//B B→B B16
TheB BsquareB BisB BdescribedB BwithB BjustB BoneB BparameterB BandB BweB BcallB BitB
three.B BThatB BisB BpossibleB BbecauseB BtheB BprogrammingB BlanguageB
B

disregardsB BtheB BsurplusB BargumentsB BandB BrecognizesB BtheB BsquareB BofB


B

theB BfirstB Bone.B BJavaScriptB BisB BveryB BtolerantB BaboutB BtheB BamountB BofB
B

argumentsB BbeingB BpassedB BtoB BaB Bfunction.B BTheB BgoodB BsideB BofB BthisB
B

characterB BisB BthatB BitB BenablesB BcallingB BfunctionsB BwithB BseparateB


B

numbersB BofB Barguments:


B

functionB Bminus(a,B Bb)B B{


ifB B(bB B===B Bundefined)B BreturnB B-a;
elseB BreturnB BaB B-B Bb;
}
console.log(minus(10));

//B B→B B-10


console.log(minus(10,B B5));
//B B→B B5
WhenB BanB B=B BoperatorB BisB BwrittenB BafterB BaB BparameterB BandB BanB
expression,B BtheB BexpressionB BvalueB BwillB BrestoreB BtheB Bnon-specifiedB
B

argument.B BIfB ByouB BwantB BtoB BpassB BandB BnotB BproduceB BtheB BsecondB
B

argument,B BtheB BdefaultB BbecomesB BtwoB BandB BtheB BfunctionB BactsB BlikeB BaB
B

square.
B

functionB Bpower(base,B BexponentB B=B B2)B B{


letB BresultB B=B B1;
forB B(letB BcountB B=B B0;B BcountB B<B Bexponent;B Bcount++)B B{
resultB B*=B Bbase;
}

returnB Bresult;
}
console.log(power(4));

//B B→B B16


console.log(power(2,B B6));
//B B→B B64
Closure

TheB BcapabilityB BtoB BuseB BfunctionsB BasB BvaluesB BisB BcoupledB BwithB BtheB BfactB
thatB BlocalB BbindingsB BareB BcreatedB BagainB BwheneverB ByouB BcallB BaB
B

function.B BTheB BbelowB BcodeB BdisplaysB BthisB Bexample;B BitB BdescribesB BaB
B

wrapB Bvalue,B BaB BfunctionB BthatB BdevelopsB BaB BlocalB BbindingB BandB BthenB
B

sendsB BbackB BaB BfunctionB BthatB BentersB BandB BreturnsB BtheB BlocalB Bbinding.
B

functionB BwrapValue(n)B B{
letB BlocalB B=B Bn;
returnB B()B B=>B Blocal;
}

letB Bwrap1B B=B BwrapValue(1);


letB Bwrap2B B=B BwrapValue(2);
console.log(wrap1());

//B B→B B1
console.log(wrap2());

//B B→B B2
ThisB BconceptB BisB BcalledB Bclosure.B BItB BgivesB BtheB BuserB BtheB BabilityB BtoB
referenceB BaB BparticularB BinstanceB BofB BaB BlocalB BbindingB BwithinB BaB
B

confiningB Bscope.B BAddingB BaB BfewB Bchanges,B BourB BpreviousB BexampleB BcanB
B

turnB BintoB BaB BwayB BtoB BdevelopB BfunctionsB BthatB BaccumulatesB BbyB BanB
B

arbitraryB Bamount.
B

functionB Bmultiplier(factor)B B{
returnB BnumberB B=>B BnumberB B*B Bfactor;
}

letB BtwiceB B=B Bmultiplier(2);


console.log(twice(5));

//B B→B B10


Recursion

AB BfunctionB BcanB BcallB BitselfB BbutB BshouldB BnotB BcallB BitselfB BregularlyB BtoB
avoidB BstackB Boverflow.B BRecursiveB BfunctionB BisB BaB BfunctionB BthatB BcallsB
B

itself.B BRecursionB BenablesB BfewB BfunctionsB BwrittenB BinB BseparateB Bstyles.B


B

ForB Binstance,B BtheB BbelowB BcodeB BisB BtheB BexecutionB BofB Bpower.
B

functionB Bpower(base,B Bexponent)B B{


ifB B(exponentB B==B B0)B B{
returnB B1;
}B BelseB B{
returnB BbaseB B*B Bpower(base,B BexponentB B-B B1);
}
}

console.log(power(2,B B3));
//B B→B B8
ThereB BisB BoneB BproblemB BwithB BthisB Bexecution.B BItB BisB BslowerB BcomparedB
toB BotherB BloopingB Bversions.B BUtilizingB BaB BsingleB BloopB BisB BconsideredB
B

lowB BcostB BthanB BtheB BmultipleB BcallingB BofB Bfunctions.B BAlthoughB BthatB
B

doesB BnotB BmakeB BrecursionB BanB BineffectiveB BoptionB BofB Blooping,B BfewB
B

problemsB BareB BsolvedB BwithB BrecursionB BeasierB BthanB BwithB BtheB BuseB BofB
B

loops.B BProblemsB BthatB BneedB BinspectingB BorB BprocessingB BseveralB


B

branches.B BCheckB BthisB Bout:B BweB BbeginB BfromB BnumberB B1B BandB
B

continuouslyB BaddB B5B BorB BmultiplyB BbyB B3.B BForB Binstance,B BtheB BnumberB
B

13B BcanB BbeB BobtainedB BbyB BmultiplyingB BbyB B3B BandB BtheB BadditionB BofB B5B
B
twice,B BtherebyB BweB BcannotB BattainB BtheB B15.B BTheB BcodeB BisB BtheB BrecursiveB
B

solution:
B

functionB BfindSolution(target)B B{
functionB Bfind(current,B Bhistory)B B{
ifB B(currentB B==B Btarget)B B{
returnB Bhistory;
}B BelseB BifB B(currentB B>B Btarget)B B{
returnB Bnull;
}B BelseB B{
returnB Bfind(currentB B+B B5,B B`(${history}B B+B B5)`)B B||
find(currentB B*B B3,B B`(${history}B B*B B3)`);
}
}

returnB Bfind(1,B B"1");


}
console.log(findSolution(24));

//B B→B B(((1B B*B B3)B B+B B5)B B*B B3)


TheB BinnerB BfunctionB BfindB BtakesB BtwoB Barguments,B BtheB BcurrentB BnumberB
andB BaB BstringB BthatB BdocumentsB BtheB BprocessB BofB BattainingB BthisB
B

number.B BIfB BaB BsolutionB BisB Bfound,B BitB BsendsB BbackB BaB BstringB BthatB
B

displaysB BtheB BrouteB BtoB BtheB BtargetB BandB BifB BnoB BsolutionB BisB Bfound,B BtheB
B

returnedB BvalueB BwillB BbeB Bnull.B BToB BachieveB Bthis,B BtheB BfunctionB
B

executesB BoneB BofB BthreeB Bactions.B BIfB ByourB BtargetB BisB BtheB BisB BtheB
B

currentB Bnumber,B ByouB BcanB BattainB BthatB BtargetB BbyB BusingB BtheB BcurrentB
B

historyB BsoB BitB BisB BsentB Bback.B BSometimesB BtheB BnumberB BisB BlargerB BthanB
B

theB Btarget,B BbutB ByouB BdoB BnotB BneedB BtoB BexploreB BthisB BoptionB BbecauseB
B

additionB BandB BsubtractionB BcanB BonlyB BenlargeB BtheB BnumberB BsoB BitB BisB
B
sentB BbackB BasB Bnull.B BIfB ByouB BremainB BbeneathB BtheB BtargetB Bnumber,B
B

bothB BpathsB BthatB BbeginB BtheB BcurrentB BnumberB BisB BtriedB BbyB BcallingB
B

itselfB Btwice,B BoneB BtoB BaddB BandB BtheB BotherB BtoB Bmultiply.B BIfB BtheB BfirstB
B

callB BsendsB BsomethingB BvalidB BbackB BinB Breturn,B BthenB Bgood,B BifB Bnot,B
B

returnB BtheB BsecondB Bcall,B BitB BdoesB BnotB BmatterB BwhetherB BaB BstringB BorB
B

nullB BisB Bprovided.B BBelowB BisB BanB BillustrationB BofB BhowB BfunctionsB
B

provideB Beffects.B BThisB BexampleB BsearchesB BforB BaB BremedyB BforB BtheB
B

numberB B13.
B

find(1,B B"1")
find(6,B B"(1B B+B B5)")
find(11,B B"((1B B+B B5)B B+B B5)")
find(16,B B"(((1B B+B B5)B B+B B5)B B+B B5)")
tooB Bbig
find(33,B B"(((1B B+B B5)B B+B B5)B B*B B3)")
tooB Bbig
find(18,B B"((1B B+B B5)B B*B B3)")
tooB Bbig
find(3,B B"(1B B*B B3)")
find(8,B B"((1B B*B B3)B B+B B5)")
find(13,B B"(((1B B*B B3)B B+B B5)B B+B B5)")
found!

TheB BindentationB BspecifiesB BprofoundB BofB BtheB BcallB Bstack.


Growing functions
BB

FunctionsB BcanB BbeB BintroducedB BintoB BprogramsB BinB BtwoB Bways.B BTheB BfirstB
isB BbyB BwritingB BsimilarB BcodesB BaB BlotB BofB Btimes,B BwhichB BenablesB BmoreB
B

mistakesB BwhileB BtheB BsecondB BisB BtoB BsearchB BforB BaB BfewB BfunctionalitiesB
B
thatB BhaveB BnotB BbeenB BwrittenB BandB BdeservesB BitsB BownB Bfunction.B BYouB
B

canB BbeginB BbyB BnamingB BtheB BfunctionB BandB BwriteB BtheB Bbody.B BBelowB BisB
B

anB Bexample.B BWeB BwillB BwriteB BaB BprogramB BthatB BreproduceB BtwoB
B

numbers–theB BamountB BofB BchickenB BandB BcowsB BavailableB BonB BaB Bfarm.
B

007B BCows
011B BChickens
functionB BprintFarmInventory(cows,B Bchickens)B B{
letB BcowStringB B=B BString(cows);
whileB B(cowString.lengthB B<B B3)B B{
cowStringB B=B B"0"B B+B BcowString;
}

console.log(`${cowString}B BCows`);
letB BchickenStringB B=B BString(chickens);
whileB B(chickenString.lengthB B<B B3)B B{
chickenStringB B=B B"0"B B+B BchickenString;
}

console.log(`${chickenString}B BChickens`);
}

printFarmInventory(7,B B11);
WritingB BlengthB BafterB BaB BstringB BexpressionB BdeterminesB BtheB BlengthB BofB
theB BparticularB Bstring.B BTheB BloopB BcontinuesB BtoB BaddB BzerosB BatB BtheB
B

beginningB BofB BtheB BnumberB BstringsB BuntilB BtheyB BcompriseB BofB BthreeB
B

characters.
B

HereB BisB BaB BbetterB Battempt:


functionB BprintZeroPaddedWithLabel(number,B Blabel)B B{
letB BnumberStringB B=B BString(number);
whileB B(numberString.lengthB B<B B3)B B{
numberStringB B=B B"0"B B+B BnumberString;
}

console.log(`${numberString}B B${label}`);
}

functionB BprintFarmInventory(cows,B Bchickens,B Bpigs)B B{


printZeroPaddedWithLabel(cows,B B"Cows");
printZeroPaddedWithLabel(chickens,B B"Chickens");
printZeroPaddedWithLabel(pigs,B B"Pigs");
}

printFarmInventory(7,B B11,B B3);


InsteadB BofB BtakingB BoutB BtheB BreplicatedB BpartB BofB BtheB Bprogram,B BtryB BtoB
BpickB BoutB BanB BindividualB BconceptB BwithB BtheB BfollowingB Bsteps:

functionB BzeroPad(number,B Bwidth)B B{


letB BstringB B=B BString(number);
whileB B(string.lengthB B<B Bwidth)B B{
stringB B=B B"0"B B+B Bstring;
}

returnB Bstring;
}

functionB BprintFarmInventory(cows,B Bchickens,B Bpigs)B B{


console.log(`${zeroPad(cows,B B3)}B BCows`);
console.log(`${zeroPad(chickens,B B3)}B BChickens`);
console.log(`${zeroPad(pigs,B B3)}B BPigs`);
}

printFarmInventory(7,B B16,B B3);


AB BfunctionB BcanB BalsoB BbeB BusedB BtoB BprintB BalignedB BtablesB BofB Bnumbers.
FunctionsB BandB BsideB Beffects
FunctionsB BcanB BconsistB BofB BsideB BeffectsB BandB BreturnB BaB Bvalue.B BTheyB
BdevelopB BvaluesB BthatB BintegrateB BeasilyB BinB BnewB BwaysB BmuchB BmoreB
BthanB BfunctionsB BthatB BproduceB BsideB Beffects.B BAB BpureB BfunctionB BisB BaB
BuniqueB BvalueB BmanufacturingB BfunctionB BthatB BdoesB BnotB BdependB BonB
BeitherB BcodeB BsideB Beffects.B BForB Binstance,B BitB BwillB BnotB BrecognizeB BaB
BglobalB BbindingB BwithB BaB BchangeableB Bvalue.B BItB BalsoB BconsistsB BofB BaB
BcallableB BpropertyB BtogetherB BwithB BtheB BsameB BargumentsB BandB BproducesB
BequalB Bvalue.
Summary

InB BthisB Bchapter,B ByouB BnowB BunderstandB BhowB BtoB BwriteB ByourB Bfunctions.B
BKnowingB BhowB BtoB BwriteB BtheB BfunctionB BkeywordB BandB BwhenB BtoB BuseB BanB
Bexpression,B ByouB BcanB BnowB BbuildB BaB BfunctionB Bvalue.B BWhenB ByouB BuseB BaB
BfunctionB BasB BaB Bstatement,B BitB BcanB BsetB BaB BbindingB BandB BnameB BaB
BfunctionB BtoB BbeB BitsB Bvalue.B BYouB BcanB BalsoB BuseB BarrowB BfunctionsB BtoB
BbuildB Bfunctions.
//B BDefineB BfB BtoB BholdB BaB BfunctionB Bvalue
constB BfB B=B Bfunction(a)B B{
console.log(aB B+B B2);
};

//B BDeclareB BgB BtoB BbeB BaB Bfunction


functionB Bg(a,B Bb)B B{
returnB BaB B*B BbB B*B B3.5;
}

//B BAB BlessB BverboseB BfunctionB Bvalue


letB BhB B=B BaB B=>B BaB B%B B3;
TheB BmajorB BperspectiveB BofB BunderstandingB BfunctionsB BisB BknowingB BtheB
scopes.B BEveryB BblockB BbuildsB BaB BnewB Bscope.B BParametersB BandB BbindingsB
B

setB BinB BaB BspecificB BscopeB BareB BlocalB BandB BinvisibleB BfromB BtheB Boutside.B
B

BindingsB BsetB BwithB BvarB BactB Bdifferently,B BandB BtheyB BresultB BinB BtheB
B

globalB Bscope.B BDifferentiatingB BtheB BtasksB BthatB BtheB BprogramB BexecutesB


B

intoB BvariousB BfunctionsB BisB Bimportant.B BYouB BdoB BnotB BneedB BtoB BrepeatB
B

yourselfB Boften,B BandB BfunctionsB BcanB BarrangeB BaB BprogramB BbyB


B

categorizingB BcodeB BintoB BbitsB BthatB BperformB BspecificB Bactions.


B

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BseeB BifB BaB BnumberB BisB BevenB BorB Bnot.
Solution
BB
Chapter 5: Data Structures:
BB BB BB B

BObjects and Arrays BB BB

DataB BlayoutsB BdevelopB BfromB BBooleans,B Bstrings,B BandB BnumbersB


fragments.B BSeveralB BtypesB BofB BinformationB BuseB BmoreB BthanB BoneB
B

chunk.B BObjectsB BenableB BtheB BuserB BtoB BcollateB BvaluesB BtogetherB BwithB
B

otherB BobjectsB BtoB BdevelopB BmoreB BcompoundB Blayouts.B BInB BthisB Bchapter,B
B

youB BwillB BunderstandB BtheB BconceptsB BofB BsolvingB BaB BrealB BproblemB BatB
B

hand.
B

DataB Bsets
IfB ByouB BwantB BtoB BworkB BwithB BaB BlotB BofB BdigitalB Bdata,B ByouB BmustB
representB BtheB BdigitalB BdataB BinB BtheB BmachineB Bmemory.B BForB Binstance,B
B

youB BneedB BtoB BrepresentB BaB BgroupB BofB BnumbersB BlikeB B2,B B3,B B5,B B7,B BandB
B

11.B BNowB Blet’sB BgetB BprolificB BwithB BourB BuseB BofB BstringsB BasB BstringsB BcanB
B

containB BquiteB BaB BlotB BofB Bdata.B BWeB BwillB BuseB B2B B3B B5B B7B B11B BasB BtheB
B

representation.B BJavaScriptB BprogrammingB BlanguageB BoffersB BaB BuniqueB


B

dataB BtypeB BforB BsavingB BsequencesB BofB Bvalues,B BwhichB BisB BcalledB BanB
B

array.B BWriteB BanB BarrayB BasB BaB BlistB BofB BvaluesB BwithinB BtheB BbetweenB
B

squareB Bbrackets,B BdifferentiatedB BbyB Bcommas.


B

letB BlistOfNumbersB B=B B[2,B B3,B B5,B B7,B B11];


console.log(listOfNumbers[2]);

//B B→B B5
console.log(listOfNumbers[0]);

//B B→B B2
console.log(listOfNumbers[2B B-B B1]);
//B B→B B3
TheB BnotationB BusedB BtoB BgetB BelementsB BwithinB BanB BarrayB BalsoB ButilizeB
theB BsquareB Bbrackets.B BAB BcompleteB BsquareB BbracketsB BpairB BrightB BafterB
B

anB BexpressionB BthatB BcontainsB BanotherB BexpressionB Bwithin.B BWhenB ByouB


B

startB BcountingB BelementsB BinB BanB Barray,B ByouB BbeginB BfromB BzeroB BandB
B

notB Bone.B BThereforeB BtheB


B BfirstB elementB
B isB
B redeemedB
B withB
B

listOfNumbers[0].
B

Properties

TheB BpreviousB BchaptersB BhaveB BcontainedB BexpressionsB BlikeB BtheB


myString.B BLengthB B(toB BcalculateB BtheB BlengthB BofB BaB Bstring)B BandB
B

Math.maxB B(theB BmaximumB Bfunction).B BTheseB BareB BpropertiesB BthatB BcanB


B

approachB BtheB BpropertyB Bvalues.B BVirtuallyB BallB BJavaScriptB BvaluesB


B

containB Bproperties.B BTheB BfewB BvaluesB BthatB BdoB BnotB BcontainB BpropertiesB
B

areB BnullB BandB Bundefined.B BIfB ByouB BaccessB BaB BpropertyB BwithB BaB
B

nonvalue,B BtheB BresultB BwillB BbeB BanB Berror.


B

null.length;

//B B→B BTypeError:B BnullB BhasB BnoB Bproperties


InB BJavaScript,B BtheB BtwoB BmajorB BwaysB BtoB BevaluateB BpropertiesB BareB BwithB
aB BdotB BandB BsquareB Bbrackets.B BTheB Bvalue.xB BandB Bvalue[x]B BcanB BevaluateB
B

theB BpropertyB BonB Bvalue,B BnotB BparticularlyB BtheB BsameB Bproperty.B BHowB
B

youB BuseB BxB BisB BdifferentB BfromB BhowB ByouB BuseB BaB Bdot.
B

IfB ByouB BwantB BtoB BuseB BtheB Bdot,B BtheB BtextB ByouB BinputB BafterB BtheB BdotB BisB
theB BnameB BofB BtheB Bproperty.B BAndB BifB Byou'reB BgoingB BtoB BuseB BtheB BsquareB
B

brackets,B BtheB BexpressionB BwithinB BtheB BbracketsB BisB BaccessedB BtoB


B

redeemB BtheB BpropertyB Bname.B BValue.xB BdeliversB BtheB BpropertyB BofB BvalueB
B

calledB B“x,”B BwhileB Bvalue[x]B BaccessesB BtheB BexpressionB BxB BandB ButilizeB
B

theB Bresult,B BtransformedB BintoB BaB BstringB BasB BtheB BnameB BofB BtheB
B

property.B BIfB BtheB BpropertyB ByouB BwantB BisB BnamedB Bcolor,B ByouB BshouldB
B
typeB Bvalue.color.B BYouB BcanB BwithdrawB BtheB BpropertyB BthatB BtheB BvalueB
B

calledB BwithinB BtheB BbindingB Bi,B BtypeB Bvalue[i].B BTheB BnameB BofB BpropertiesB
B

areB Bstrings,B BbutB BtheB BdotB BnotationB BperformsB BwithB BonlyB BvalidB
B

bindingB Bnames.B BThereforeB BifB ByouB BwantB BtoB BevaluateB BaB BpropertyB
B

namedB B2B BorB BJohnB BDoe,B BuseB BtheB BsquareB Bbrackets:B Bvalue[2]B BorB
B

value["JohnB BDoe"].
B

TheB BelementsB BwithinB BanB BarrayB BsaveB BasB BtheB BpropertiesB BofB BanB BarrayB
thatB ButilizeB BnumbersB BasB BpropertyB Bnames.B BAnB Barray'sB BlengthB
B

propertyB BdeterminesB BhowB BmanyB BitemsB BitB Bcontains.B BTheB BnameB BofB
B

thatB BpropertyB BisB BaB Bvalid,B BbindingB Bname.B BTypeB Barray.lengthB BtoB
B

determineB BtheB BlengthB BofB BanB Barray,B BitB BisB BmuchB BeasierB BtoB BtypeB BthanB
B

theB Barray["length"].
B

Methods

TheB BstringB BandB BarrayB BobjectsB BaccommodateB BseveralB BpropertiesB BthatB


storeB BfunctionB Bvalues.
B

letB BdohB B=B B"Doh";


console.log(typeofB Bdoh.toUpperCase);
//B B→B Bfunction
console.log(doh.toUpperCase());

//B B→B BDOH


EachB BstringB BconsistsB BofB BaB BtoUpperCaseB Bproperty.B BWhenB ByouB BcallB
thisB Bproperty,B BitB BsendsB BbackB BaB BcopyB BofB BtheB BstringB BwherebyB BallB BtheB
B

containingB
B BlettersB transformB
B BintoB Buppercase.B BAlthoughB BtheB
toUpperCaseB BdoB BnotB BgoB BthroughB BanB Bargument,B BtheB BfunctionB BcanB
B

evaluateB BtheB BstringB B"Doh,"B BwhichB BisB BtheB BpropertyB BofB BtheB BvalueB BweB
B

calledB Babove.B BPropertiesB BthatB BconsistB BofB BfunctionsB BareB BknownB BasB
B
methods.B BTheB BbelowB BexampleB BillustratesB BtwoB BmethodsB BthatB BcanB BbeB
B

usedB BtoB BinfluenceB Barrays.


B

letB BsequenceB B=B B[1,B B2,B B3];


sequence.push(4);
sequence.push(5);
console.log(sequence);

//B B→B B[1,B B2,B B3,B B4,B B5]


console.log(sequence.pop());

//B B→B B5
console.log(sequence);

//B B→B B[1,B B2,B B3,B B4]


TheB BpushB BmethodB BisB BusedB BtoB BattachB BaB BvalueB BtoB BtheB BendB BofB BanB
arrayB BwhileB BtheB BpopB BmethodB BdoesB BtheB BdirectB Bopposite.B BItB
B

eradicatesB BtheB BlastB BvalueB BwithinB BanB BarrayB BandB BsendsB BitB Bback.B
B

TheseB BareB BgenerationalB BtermsB BofB BoperationsB BonB BaB Bstack.B BAB BstackB BisB
B

aB BdataB BlayoutB BthatB BenablesB BusersB BtoB BpushB BvaluesB BinB BandB BpopB BthemB
B

outB BinB BtheB BoppositeB BdirectionB BsoB BthatB BtheB BaddedB BvalueB BwillB
B

removeB Bfirst.
B

Objects

YouB BcanB BrepresentB BaB BgroupB BofB BlogB BentriesB BasB BanB BarrayB BalthoughB
eachB BstringB BentryB BisB BrequiredB BtoB BsaveB BaB BlistB BofB BactivitiesB BasB BwellB
B

asB BaB BBooleanB BvalueB BthatB BspecifiesB BifB BJacquesB BtransformedB BtoB BaB
B

BsquirrelB BorB Bnot.B BWeB BwillB BgroupB BthisB BintoB BaB BsingleB BvalueB BandB BplaceB
BtheB BgroupedB BvaluesB BwithinB BanB BarrayB BofB BlogB Bentries.B BArbitraryB

collectionsB BofB BpropertiesB BareB BtheB BvalueB BofB BtheB BtypeB Bobject.B BWeB BwillB
B

developB BanB BobjectB ButilizingB BbracesB BasB BanB Bexpression.


B

letB Bday1B B=B B{


squirrel:B Bfalse,
events:B B["work",B B"touchedB Btree",B B"pizza",B B"running"]
};
console.log(day1.squirrel);

//B B→B Bfalse


console.log(day1.wolf);

//B B→B Bundefined


day1.wolfB B=B Bfalse;
console.log(day1.wolf);

//B B→B Bfalse


TheB BbracesB BcontainB BaB BlistB BofB BpropertiesB BdividedB BbyB Bcommas.B BEveryB
BpropertyB BcontainsB BaB BnameB BaccompaniedB BbyB BaB BvalueB BandB BaB Bcolon.B
BWhenB ByouB BwriteB BanB BobjectB BoverB BseveralB Blines,B BmakeB BsureB ByourB
BindentingB BisB BgoodB BbecauseB BitB BenablesB BbetterB Breadability.B BQuoteB
BInvalidB BbindingB BnamesB BpropertiesB BorB BvalidB BnumbersB Bshould.
letB BdescriptionsB B=B B{
work:B B"WentB BtoB Bwork,"
"touchedB Btree":B B"TouchedB BaB Btree."
};

YouB BcanB BuseB BbracesB BinB BtwoB BdifferentB BwaysB BinB BJavaScript.B BItB BisB BusedB
BatB BtheB BbeginningB BofB BaB BstatementB BandB BcanB BalsoB BbeB ButilizedB BtoB
BbeginB BaB BblockB BofB Bstatements.B BYouB BcanB BspecifyB BaB BvalueB BtoB BaB
BpropertyB BexpressionB BusingB BtheB B=B Boperator.B BItB BtakesB BtheB BplaceB BofB
BtheB BpropertyB Bvalue,B BandB BifB BitB BisB BinB Bexistence,B BitB BdevelopsB BaB BnewB
Bone.B BTheB BdeleteB BoperatorB BisB BaB BunaryB BoperatorB BthatB BeradicatesB BtheB
BpropertyB BnameB BofB BanB Bobject.B BBelowB BisB BanB Billustration:
letB BanObjectB B=B B{left:B B1,B Bright:B B2};
console.log(anObject.left);

//B B→B B1
deleteB BanObject.left;
console.log(anObject.left);

//B B→B Bundefined


console.log("left"B BinB BanObject);
//B B→B Bfalse
console.log("right"B BinB BanObject);
//B B→B Btrue
TheB BbinaryB BinB BoperationB BdeterminesB BifB BanB BobjectB BorB BstringB BcontainsB
aB BnamedB Bproperty.B BTheB BmajorB BdifferentiationB BbetweenB BspecifyingB BaB
B

propertyB BtoB BundefinedB BandB BdeletingB BitB BisB BthatB BtheB BobjectB BconsistsB
B

ofB BaB BpropertyB BandB BtheB BdeletingB BdoesB BnotB BpossessB BtheB Bproperty,B BsoB
B

theB BvalueB BreturnsB BasB Bfalse.B BToB BdetermineB BwhatB BpropertiesB


B

containedB BinB BanB BobjectB BandB BsendsB BbackB BanB BarrayB BofB BstringsB BwithB
B

propertyB BnamesB BofB BtheB Bobject.


B

console.log(Object.key({x:B B0,B By:B B0,B Bc:B B2}));


//B B→B B["x",B B"y",B B"c"]
TheB BObject.assignB BfunctionB BisB BusedB BtoB BcopyB BpropertiesB BfromB BoneB
objectB BtoB Banother.
B

letB BobjectAB B=B B{a:B B1,B Bb:B B2};


Object.assign(objectA,B B{b:B B3,B Bc:B B4});
console.log(objectA);

//B B→B B{a:B B1,B Bb:B B3,B Bc:B B4}


AnB BarrayB BisB BaB BuniqueB BobjectB BusedB BforB BsavingB BsuccessionB BofB Bthings.B
WhenB ByouB BaccessB BtheB BtypeofB B[],B BitB BprovidesB B"object."B BTheB BbelowB
B
BillustrationB BstandsB BforB BtheB BjournalB BthatB BJacquesB BstoresB BasB BanB BarrayB
BofB Bobjects.
letB BjournalB B=B B[
{events:B B["work",B B"touchedB Btree",B B"pizza",
"running",B B"television"],
squirrel:B Bfalse},
{events:B B["work",B B"iceB Bcream",B B"cauliflower",
"lasagna",B B"touchedB Btree",B B"brushedB Bteeth"],
squirrel:B Bfalse},
{events:B B["weekend",B B"cycling",B B"break",B B"peanuts",
"beer"],

squirrel:B Btrue},
/*B BandB BsoB Bon...B B*/
];
Mutability

WeB BhaveB BdiscussedB BdifferentB BvaluesB BsuchB BasB BBooleans,B Bstrings,B BandB
BnumbersB BwhoseB BvaluesB BareB BdifficultB BtoB Bchange,B BalthoughB BtheyB BcanB
BbeB BcombinedB BtoB BacquireB BnewB BvaluesB BfromB Bthem.B BObjectsB BareB
BdifferentB BfromB Bvalues,B BandB BitB BenablesB BpropertyB Bchanging;B BtheyB BcanB
BcreateB BdifferentB BcontentB BforB BaB BsingleB BobjectB BvalueB BatB BdifferentB
Btimes.B BWhenB BthereB BareB BtwoB Bnumbers,B B120B BandB B120,B BtheyB BareB
BconsideredB BtheB Bsame,B BandB BthereB BisB BaB BsimilarityB BbetweenB BsettingB
BtwoB BreferencesB BtoB BoneB BobjectB BandB BpossessingB BtwoB BseparateB BobjectsB
BcontainingB BtheB BsameB Bproperties.B BCheckB BtheB BbelowB Bcode:
letB Bobject1B B=B B{value:B B10};
letB Bobject2B B=B Bobject1;
letB Bobject3B B=B B{value:B B10};
63

console.log(object1B B==B Bobject2);


//B B→B Btrue
console.log(object1B B==B Bobject3);
//B B→B Bfalse
object1.valueB B=B B15;
console.log(object2.value);

//B B→B B15


console.log(object3.value);

//B B→B B10


TheB Bobject1B BandB Bobject2B BbindingsB BholdB BtheB BsameB Bobject,B BandB BthatB
BisB BwhyB BalteringB Bobject1B BoneB BinfluencesB BtheB BvalueB BofB Bobject2.B BTheyB

areB BidenticalB BbyB Bnature.B BTheB BbindingB Bobject3B BpointsB BtoB BaB BseparateB
B

objectB BthatB BconsistsB BofB BsimilarB BpropertiesB BasB BtheB Bobject1B BbutB BhasB BaB
B

differentB Blife.B BBindingsB BcanB BbeB BconstantB BorB Bchangeable,B BbutB BitB BdoesB
B

notB BinfluenceB BtheirB Bvalues.B BAB BconstB BbindingB BanB BobjectB BcannotB BbeB
B

transformedB BandB BrelentlesslyB BpointingB BtoB BtheB BsameB Bobject.B BItB BisB
B

theB BobjectB BcontentsB BthatB BcanB BbeB Bchanged.


B

constB BscoreB B=B B{visitors:B B0,B Bhome:B B0};


//B BThisB BisB Bokay
score.visitorsB B=B B1;
//B BThisB Bisn'tB Ballowed
scoreB B=B B{visitors:B B1,B Bhome:B B1};
WhenB BtheB BJavaScript’sB B==B BoperatorB BisB BusedB BtoB BdifferentiateB Bobjects,B
itB BusesB BtheB BidentityB BtoB BperformB BthatB Btask.B BItB BwillB BtranslateB BtrueB BifB
B
theB BobjectsB BcontainB BtheB BsameB Bvalue.B BDifferentiatingB BseveralB BobjectsB
B

willB BreturnB Bfalse,B BevenB BifB BtheirB BpropertiesB BareB Bsimilar.


B

TheB Blycanthrope'sB Blog


So,B ByouB BbeginB ByourB BJavaScriptB BinterpreterB BandB BcreatesB BtheB
environmentB ByouB BneedB BtoB BkeepB ByourB Bjournal.
B

letB BjournalB B=B B[];


functionB BaddEntry(events,B Bsquirrel)B B{
journal.push({events,B Bsquirrel});
}

InsteadB BofB BproclaimingB BpropertiesB BsuchB BasB Bevents,B BitB BsetsB BaB
propertyB Bname.
B

SoB Bthen,B BatB B10B Bp.m.B BeveryB BeveningB BorB BoccasionallyB BinB BtheB
followingB Bmorning,B Bafter
B

gettingB BdownB BfromB BtheB BtopB BshelfB BofB ByourB Bbookcase,B ByourB BdailyB
records.
B

addEntry(["work",B B"touchedB Btree",B B"pizza",B B"running",


"television"],B Bfalse);
addEntry(["work",B B"iceB Bcream",B B"cauliflower",B B"lasagna",
"touchedB Btree",B B"brushedB Bteeth"],B Bfalse);
addEntry(["weekend",B B"cycling",B B"break",B B"peanuts",
"beer"],B Btrue);
CorrelationB BisB BanB BevaluationB BofB BvulnerabilityB BbetweenB BanalyticalB
variables.B BTheyB BareB BknownB BasB BvaluesB BthatB BspanB BfromB B-1B BtoB B1.B BAnB
B

UnrelatedB BvariableB BisB BcalledB BaB BzeroB Bcorrelation.B BAB BcorrelationB BofB B1B
B

signifiesB BthatB BtheB BtwoB BareB Brelated.B BNegativeB BmeansB BthatB BtheB
B

variablesB BareB BrelatedB BperfectlyB BbutB BoppositesB BtoB BeachB Bother;B BoneB BisB
B
true,B BandB BtheB BotherB BisB Bfalse.B BToB BcalculateB BtheB BevaluationB BofB BtheB
B

correlationB BbetweenB BtwoB BBooleanB Bvalues,B ButilizeB BtheB BphiB BcoefficientB


B

(φ).B BThisB BformulaB BinputB BisB BaB BfrequencyB BtableB BholdingB BtheB BnumberB
B

ofB BtimesB BitB BnoticesB BseveralB BmixturesB BofB BtheB Bvariables.B BTheB
B

formula'sB BoutputB BwillB BbeB BaB BnumberB BbetweenB B-1B BandB B1.B BThatB BisB BtheB
B

bestB BdefinitionB BofB BaB Bcorrelation.


B

LetB BusB BuseB BtheB BeventB BifB BeatingB BpizzaB BasB BanB BexampleB BandB BinsertB BitB
intoB BaB BfrequencyB BtableB BwherebyB BeveryB BnumberB BsignifiesB BtheB BtotalB
B

ofB Btimes,B BandB BweB BusedB BtheB BcombinationB BinB BourB Bmeasurements.B BWeB
B

nameB BtheB BtableB Bn,B BandB BweB BcalculateB BφB BwithB BtheB BbelowB Bformula:
B

φB B=
n11n00B B−B Bn10n01

n1•n0•n•1n•0

TheB BnotationB Bn01B BsignifiesB BtheB BnumberB BofB BmeasurementsB BwhereB


theB BfirstB BvariableB BturnsB BfalseB B(0),B BandB BtheB BsecondB BvariableB BbecomesB
B

trueB B(1).B BTheB BpizzaB Btable,B Bn01B BisB B9.


B

TheB BvalueB Bn1•B BindicatesB BtheB BsumB BofB BallB BmeasurementsB BwhereB BtheB
BfirstB BvariableB BturnsB Btrue,B BthatB BisB B5B BinB BtheB BtableB Bexample.B BAsB BwellB
BasB Bn•0B BsuggestsB BtheB BquantityB BofB BtheB BmeasurementsB BwhereB BtheB

secondB BvariableB BbecomesB Bfalse.


B

TheB BpizzaB Btable,B BtheB BtopB BofB BtheB BdivisionB BlineB BwouldB BbeB B1×76−4×9B B=B
40,B BandB BtheB BbelowB BpartB BbelowB BwouldB BbeB BtheB BsquareB BrootB BofB
B

5×85×10×80,B BorB B√340000.B BTheB BresultB BwillB BbeB BφB B≈B B0.069,B BwhichB BisB
B

tiny.B BTherefore,B BeatingB BpizzaB BhadB BnoB BimpactB BonB Btransformations.


B

ComputingB Bcorrelation
JavaScriptB BenablesB BtheB BrepresentationB BofB BaB Btwo-by-twoB BtableB BwithB
fourB BelementB BarraysB B([76,B B9,B B4,B B1]).B BOtherB BrepresentationsB BsuchB BasB
B

anB BarrayB BholdingB BtwoB Btwo-elementB B([[76,B B9],B B[4,B B1]])B BorB BanB BobjectB
B

containingB BpropertyB BnamesB BsuchB BasB B"11"B BandB B"01",B BandB BtheB BflatB
B

array,B BwhichB BproducesB BtheB BexpressionB BthatB BaccessB BtheB BchairB Bshort.B
B

WeB BwillB BexplainB BtheB BindicesB BtoB BtheB BarrayB BasB Btwo-bitB BbinaryB
B

numbers,B BwhereB BtheB BmostB BsignificantB BdigitB BrefersB BtoB BtheB BsquirrelB
B

variableB BwhileB BtheB BleastB BsignificantB BrefersB BtoB BtheB BeventB Btable.B BForB
B

instance,B BtheB BbinaryB BnumberB B10B BrefersB BtoB BtheB B"JacquesB BdidB BturnB
B

intoB BaB Bsquirrel"B BcaseB BbutB BtheB BeventsB Bdidn’tB Bappear.B BItB BoccurredB
B

fourB BtiesB BandB BbinaryB BisB B2B BinB Bdecimal,B BtheB BnumberB BisB BstoredB BasB BanB
B

indexB B2B BofB BtheB Barray.B BThisB BfunctionB BcalculatesB BtheB BφB BcoefficientB
B

fromB BanB Barray:


B

functionB Bphi(chair)B B{
returnB B(chairB B[3]B B*B BchairB B0]B B-B BchairB B[2]B B*B BchairB B[1])B B/
Math.sqrt((chairB B[2]B B+B BchairB B[3])B B*
(chairB B[0]B B+B BchairB B[1])B B*
(chairB B[1]B B+B BchairB B[3])B B*
(chairB B[0]B B+B BchairB B[2]));
}

console.log(phi([76,B B9,B B4,B B1]));


//B B→B B0.068599434
TheB BtableB BrequiresB BtwoB BfieldsB BtoB BacquireB BfieldsB BlikeB Bn1•B BbecauseB
theB BtotalB BnumberB BofB BrowsB BandB BcolumnsB BareB BstoredB BindirectlyB BintoB
B

ourB BdataB Blayout.B BIfB ByouB BwantB BtoB BextractB BaB Btwo-by-twoB BtableB BforB BaB
B

particularB Bevent,B ByouB BmustB BloopB BacrossB BallB BtheB BentriesB BandB
B
calculateB BtheB BnumberB BofB BtimesB BtheB BeventB BhappenedB BtoB BtheB BsquirrelB
B

transformations.
B

functionB BtableFor(event,B Bjournal)B B{


letB BtableB B=B B[0,B B0,B B0,B B0];
forB B(letB BiB B=B B0;B BiB B<B Bjournal.length;B Bi++)B B{
letB BentryB B=B Bjournal[i],B BindexB B=B B0;
ifB B(entry.events.includes(event))B BindexB B+=B B1;
ifB B(entry.squirrel)B BindexB B+=B B2;
table[index]B B+=B B1;
}

returnB Btable;
}

console.log(tableFor("pizza",B BJOURNAL));
//B B→B B[76,B B9,B B4,B B1]
ArraysB BconsistsB BofB BanB BincludeB Bmethod,B BwhichB BisB BusedB BtoB BcheckB BifB BaB
setB BvalueB BexistsB BinB BtheB Barray.B BThisB BmethodB BisB BusedB BbyB BtheB
B

functionB BtoB BdecideB BifB BtheB BeventB BnameB BisB BinterestedB BtheB BstatedB
B

eventB BlistB BforB BaB BgivenB Bday.


B

Array loops
BB

TheB BtableForB BfunctionB BcontainsB BaB BloopB BlikeB Bthis:


forB B(letB BIB B=B B0;B BIB B<B BJOURNAL.length;B BI++)B B{
letB BentryB B=B BJOURNAL[i];
//B BDoB BsomethingB BwithB Bentry
}

ThisB BtypeB BofB BloopB BisB BusedB BinB Bhigh-levelB BJavaScript


ThisB BisB BhowB BtoB BwriteB BthatB BtypeB BofB BloopB BinB BmodernB BJavaScript.
forB B(entranceB BofB BJOURNAL)B B{
console.log(`${entrance.events.length}B Bevents.`);
}

WithB BaB BloopB BlikeB Bthis,B BtheB BloopB BcontinuesB BacrossB BtheB BelementsB BofB
theB BvalueB BspecifiedB BafterB Bof.B BThisB BloopB BisB BusedB BforB BstringsB BandB
B

otherB BdataB Blayouts.


B

TheB BfinalB Banalysis


AB BcorrelationB BisB BcalculatedB BforB BeveryB BtypeB BofB BeventB BthatB BhappensB
inB BtheB BdataB Bset.B BIfB ByouB BwantB BtoB BachieveB Bthat,B BsearchB BeveryB BtypeB
B

ofB Bevent.
B

functionB BjournalEvents(journal)B B{letB BeventsB B=B B[];


forB B(letB BentryB BofB Bjournal)B B{
forB B(letB BeventB BofB Bentry.events)B B{
ifB B(!events.includes(event))B B{
events.push(event);
}
}
}

returnB Bevents;
}
console.log(journalEvents(JOURNAL));

//B B→B B["carrot",B B"exercise",B B"weekend",B B"bread",B B…]


ByB BmovingB BacrossB BeveryB BeventB BandB BmakingB BadditionsB BtoB BthoseB BthatB
areB BnotB BinB BtheB BeventsB Barray,B BthisB BfunctionB BgathersB BallB BtheB BtypeB BofB
B

event.
B

AB BlotB BofB BcorrelationsB BappearB BtoB BlieB BcloseB BtoB Bzero.B BEatingB Bbread,B
carrotsB BorB BpuddingB BdoesB BnotB BactivateB BtheB Bsquirrel-lycanthropy.B BItB
B
happensB BoftenB BduringB BtheB Bweekends.B BUsingB Bthat,B BbelowB BareB BallB BtheB
B

correlations.
B

forB B(letB BeventB BofB BjournalEvents(JOURNAL))B B{


console.log(eventB B+B B":",B Bphi(tableFor(event,B BJOURNAL)));
}

//B B→B Bcarrot:B B0.0140970969


//B B→B Bexercise:B B0.0685994341
//B B→B Bweekend:B B0.1371988681
//B B→B Bbread:B B-0.0757554019
//B B→B Bpudding:B B-0.0648203724
//B BandB BsoB Bon...
letB BusB BfilterB BresultsB BtoB BdisplayB BonlyB BcorrelationsB BthatB BareB BgreaterB
thanB B0.1B BorB BlessB BthanB B-0.1.
B

forB B(letB BeventB BofB BjournalEvents(JOURNAL))B B{


letB BcorrelationB B=B Bphi(tableFor(event,B BJOURNAL));
ifB B(correlationB B>B B0.1B B||B BcorrelationB B<B B-0.1)B B{
console.log(eventB B+B B":",B Bcorrelation);
}
}

//B B→B Bweekend:B B0.1371988681


//B B→B BbrushedB Bteeth:B B-0.3805211953
//B B→B Bcandy:B B0.1296407447
//B B→B Bwork:B B-0.1371988681
//B B→B Bspaghetti:B B0.2425356250
//B B→B Breading:B B0.1106828054
//B B→B Bpeanuts:B B0.5902679812
InB BaB BcorrelationB Bfactors,B BoneB BisB BstrongerB BthanB BtheB Bother.B BEatingB
peanutsB BhasB BaB BpowerfulB BchanceB BofB BtransformingB BintoB BaB Bsquirrel,B
B

therebyB BbrushingB BtheB BteethB BhasB BaB BnotableB BnegativeB Beffect.B BHere'sB
B

something:
B

forB B(letB BentryB BofB BJOURNAL)B B{


ifB B(entry.events.includes("peanuts")B B&&
!entry.events.includes("brushedB Bteeth"))B B{
entry.events.push("peanutB Bteeth");
}
}

console.log(phi(tableFor("peanutB Bteeth",B BJOURNAL)));


//B B→B B1
FurtherB Barrayology
HereB BareB BaB BfewB BmoreB Bobject-relatedB BconceptsB ByouB BshouldB Bknow.B
WeB BbeginB BwithB BtheB BuseB BofB BsomeB BusefulB BmethodsB BofB BanB Barray.
B

TheB BaddingB BandB BremovingB BofB BmethodsB BthingsB BatB BtheB BbeginningB BofB
anB BarrayB BareB BcalledB BunshiftB BandB Bshift.
B

letB BtodoListB B=B B[];


functionB Bremember(task)B B{
todoList.push(task);
}

functionB BgetTask()B B{
returnB BtodoList.shift();
}

functionB BrememberUrgently(task)B B{
todoList.unshift(task);
}

TheB BaboveB BprogramB BorganizesB BaB BchainB BofB Btasks.B BYouB BcanB BaddB BtasksB
BtoB BtheB BendB BofB BtheB BqueueB BbyB BcallingB Bremember("groceries"),B BandB

whenB ByouB BwantB BtoB BgetB BsomethingB Bdone,B BcallB BgetTask()B BtoB BgetB B(andB
B

remove)B BitemB BfromB BtheB Bqueue.B BIfB ByouB BwantB BtoB BsearchB BforB BaB
B

particularB Bvalue,B BarraysB BsupplyB BanB BindexOfB Bmethod.B BTheB BmethodB


B

findsB BitsB BwayB BthroughB BtheB BarrayB BfromB BtheB BbeginningB BtoB BtheB BendB
B

andB BsendsB BbackB BtheB BindexB BtheB BvalueB Brequested,B BifB BitB BwasB BfoundB BitB
B

returnsB B—orB B-1B BifB BitB Bwasn’tB Bfound.B BToB BsearchB BfromB BtheB BbeginningB
B

toB BtheB Bend,B BuseB BtheB BlastIndexOfB Bmethod.


B

console.log([1,B B2,B B3,B B2,B B4].indexOf(3));


//B B→B B1
console.log([1,B B2,B B3,B B2,B B4].lastIndexOf(3));
//B B→B B3
TheB BindexOfB BandB BlastIndexOfB BtakesB BaB BvoluntaryB BargumentB BthatB
specifiesB BwhereB BtheB BsearchB Bbegins.B BAnotherB BgreatB BmethodB BisB BtheB
B

slice,B BthisB BmethodB BbeginsB BandB BendsB BtheB BindicesB BandB BsendB BbackB BanB
B

arrayB BcontainingB BthreeB Belements.B BTheB BbeginningB BisB BinclusiveB BwhileB


B

theB BendB BisB Bexclusive.


B

console.log([0,B B1,B B2,B B3,B B5].slice(2,B B4));


//B B→B B[2,B B3]
console.log([0,B B1,B B2,B B3,B B5].slice(2));
//B B→B B[2,B B3,B B5]
IfB BtheB BendB BindexB BisB BnotB Bstated,B BsliceB BtakeB BallB BtheB BelementsB BafterB
theB BstartB Bindex.B BYouB BcanB BuseB BtheB BconcatB BmethodB BtoB BglueB BarraysB
B
togetherB BtoB BproduceB BaB BnewB Barray.B BTheB BbelowB BexampleB BdisplaysB
B

concatB BandB BsliceB BinB Baction.


B

functionB Bremove(arrays,B Bindex)B B{


returnB Barray.slice(0,B Bindex)
.concat(arrays.slice(indexB B+B B1));
}

console.log(remove(["a",B B"k",B B"c",B B"f",B B"e"],B B2));


//B B→B B["a",B B"k",B B"f",B B"e"]
StringsB BandB BtheirB Bproperties
DuringB BtheB BstringB BvalueB Bchapter,B BweB BdiscussedB BlengthB BandB
BtoUpperCaseB BbutB BifB ByouB BwantB BtoB BaddB BaB BnewB Bproperty,B BitB BdoesB BnotB

stick.
B

letB BkimB B=B B"Kim";


kim.ageB B=B B88;
console.log(kim.age);

//B B→B Bundefined


AllB BstringsB BvalueB BcontainsB BaB BfewB Bmethods.B BSomeB BareB BtheB BsliceB BandB
indexOfB BwhichB BhaveB BaB BsimilarB BappearanceB BofB BarrayB BmethodsB BasB
B

wellB BasB BtheB Bname.


B

console.log("coconuts”.B BSlice(4,B B7));


//B B→B Bnut
console.log("coconut”.indexOf("u"));

//B B→B B5
AB Bstring’sB BindexOfB BcanB BlookB BforB BaB BstringB BholdingB BmoreB BthanB BoneB
character,B BwhileB BtheB BcorrespondingB BarrayB BmethodB BsearchB BforB BaB
B

singleB Belement.
B
console.log("oneB BtwoB Bthree".indexOf("ee"));
//B B→B B11
TheB BtrimB BmethodB BeradicatesB BwhitespaceB BfromB BtheB BbeginningB BtoB BtheB
endB BofB BaB Bstring.
B

console.log("B BokayB B\nB B".trim());


//B B→B Bokay
TheB BzeroPadB BfunctionB BcanB BalsoB BbeB BcalledB BaB BpadStart,B BitB BtakesB BtheB
preferredB BpaddingB BandB BlengthB BcharacterB BasB Barguments.
B

console.log(String(6).padStart(3,B B"0"));
//B B→B B006
YouB BcanB BbreakB BaB BstringB BonB BeveryB BdevelopmentB BofB BanotherB BstringB
withB BsplitB BandB BthenB BjoinB BthemB BtogetherB BwithB Bjoin.
B

letB BsentenceB B=B B"SecretarybirdsB BspecializeB BinB Bstomping";


letB BwordsB B=B Bsentence.split("B B");
console.log(words);

//B B→B B["Secretarybirds",B B"specialize",B B"in",B B"stomping"]


console.log(words.join(".B B"));
//B B→B BSecretarybirds.B Bspecialize.B Bin.B Bstomping
YouB BcanB BuseB BtheB BrepeatB BmethodB BtoB BrepeatB BaB Bstring,B BwhichB
developsB BaB BnewB BstringB BholdingB BseveralB BcopiesB BofB BtheB BoriginalB
B

stringB BattachedB Btogether.


B

console.log("LA".repeat(3));

//B B→B BLALALA


IfB ByouB BwantB BtoB BaccessB BindividualB BcharactersB BinB BaB Bstring.B BlookB
below:
B

letB BstringB B=B B"ABC";


console.log(string.length);

//B B→B B3
console.log(string[1]);

//B B→B Bb
RestB Bparameters
ItB BisB BimportantB BforB BaB BfunctionB BtoB BreceiveB BanyB BnumberB BofB
arguments.B BIfB ByouB BwantB BtoB BwriteB BsuchB BaB Bfunction,B BaddB BthreeB BdotsB
B

beforeB BtheB BlastB BparameterB BofB BtheB Bfunction.


B

functionB BmaxB B(...numbers)B B{


letB BresultB B=B B-Infinity;
forB B(letB BnumberB BofB Bnumbers)B B{
ifB B(numberB B>B Bresult)B BresultB B=B Bnumber;
}

returnB Bresult;
}

console.log(max(4,B B1,B B9,B B-2));


//B B→B B9
WhenB ByouB BcallB BaB Bfunction,B BtheB BrestB BofB BtheB BparametersB BbelongsB BtoB
anB BarrayB BholdingB BtheB BrestB BofB BtheB Barguments.B BYouB BcanB BalsoB ButilizeB
B

theB BthreeB BdotB BnotationB BtoB BcallB BfunctionsB BwithinB BanB BarrayB BofB
B

arguments.
B

letB BnumbersB B=B B[5,B B1,B B7];


console.log(max(...numbers));

//B B→B B7
SpreadB BtheB BarrayB BoutB BintoB BaB BfunctionB Bcall,B BpassB BtheB BelementB
differentB Barguments,B BlikeB BmaxB B(9,B B...numbers,B B2).B BTheB BSquareB
B
bracketB BarrayB BnotationB BenablesB BtheB Btriple-dotB BoperatorB BbringB
B

anotherB BarrayB BintoB BaB BnewB Barray.


B

letB BwordsB B=B B["never",B B"fully"];


console.log(["will",B B...words,B B"understand"]);
//B B→B B["will",B B"never",B B"fully",B B"understand"]
TheB BMathB Bobjects
TheB BMathB BobjectB BisB ButilizedB BasB BvesselB BtoB BcollateB BaB BlotB BofB BsimilarB
functionality.B BItB BproducesB BaB BnamespaceB BtoB BenableB BvaluesB BaB
B

functionsB BandB BfunctionsB BwithoutB BglobalB Bbindings.B BThisB BisB BtheB BoldB
B

wayB BtoB BwriteB BtheB BconstantB BvalueB BnameB BinB BallB Bcaps.
B

functionB BrandomPointOnCircle(radius)B B{
letB BangleB B=B BMath.random()B B*B B2B B*B BMath.PI;
returnB B{x:B BradiusB B*B BMath.cos(angle),
y:B BradiusB B*B BMath.sin(angle)};
}
console.log(randomPointOnCircle(2));

//B B→B B{x:B B0.3667,B By:B B1.966}


TheB BmathB BfunctionB BsendsB BbackB BaB BnewB BpseudoB BrandomB BnumberB
betweenB BzeroB BandB BoneB BwheneverB ByouB BcallB Bit.
B

console.log(Math.random());

//B B→B B0.36993729369714856


75
console.log(Math.random());

//B B→B B0.727367032552138


console.log(Math.random());

//B B→B B0.40180766698904335


WhenB ByouB BneedB BaB BwholeB BrandomB BnumberB BandB BnotB BtheB BfractionalB
one,B ByouB BcanB ButilizeB BtheB BMath.floorB BonB BtheB BoutcomeB BofB BtheB
B

Math.random.
B

console.log(Math.floor(Math.random()B B*B B10));


//B B→B B2
TheB BrandomB BnumberB BisB BmultipliedB BbyB B10B BandB BoutputsB BaB BnumberB
greaterB BthanB BorB BequalB BtoB B0B BandB BbelowB B10.B BRememberB BtheB
B

Math.floorB BroundsB Bdown,B BtheB BoutputB BwillB BbeB BanyB BnumberB BfromB B0B
B

throughB B9.B BTheB BmathB BobjectB BcontainsB BseveralB BfunctionsB BlikeB BtheB
B

Math.ceil,B BwhichB BroundsB BupB BtoB BaB BwholeB Bnumber,B BandB BtheB
B

Math.round,B BwhichB BroundsB BupB BtoB BtheB BnearestB BwholeB Bnumber,B BandB
B

Math.abs,B BthisB BfunctionB BtakesB BtheB BentireB BvalueB BofB BaB Bnumber.
B

Destructuring

Let’sB BuseB BtheB BphiB BfunctionB BaB BlittleB Bbit.


functionB Bphi(chair)B B{
returnB B(table[3]B B*B Bchair[0]B B-B Btable[2]B B*B Bchair[1])B B/
Math.sqrt((chairB B[2]B B+B BchairB B[3])B B*
(table[0]B B+B BchairB B[1])B B*
(table[1]B B+B BchairB B[3])B B*
(table[0]B B+B BchairB B[2]));
}

OneB BofB BtheB BfewB BreasonsB BthisB BfunctionB BisB BhardB BtoB BreadB BisB BbecauseB
thereB BisB BaB BbindingB BdirectedB BtoB BtheB Barray,B BbutB BweB BwantB BbindingsB
B

forB BtheB BelementsB BofB BtheB Barray,B BthatB Bis,B BletB Bn00B B=B Btable[0]B BandB BsoB
B

on.B BAlthough,B BthereB BisB BaB BbetterB BwayB BtoB BgetB BthisB BdoneB BinB
B

JavaScript.
B

functionB Bphi([n00,B Bn01,B Bn10,B Bn11])B B{


returnB B(n11B B*B Bn00B B-B Bn10B B*B Bn01)B B/
Math.sqrt((n10B B+B Bn11)B B*B B(n00B B+B Bn01)B B*
(n01B B+B Bn11)B B*B B(n00B B+B Bn10));
}

ThisB BfunctionB BalsoB BperformsB BbrilliantlyB BwithB BtheB BbindingsB BdevelopedB


byB BtheB Bleft,B Bvar,B BorB Bconst.B BIfB ByourB BpreferredB BbindingB BvalueB BisB BanB
B

array,B ButilizeB BtheB BsquareB BbracketsB BtoB BcheckB BforB BtheB BvalueB BofB BitsB
B

bindingB Bcontents.B BUseB BtheB BsameB BconceptB BforB Bobjects,B ButilizeB BtheB
B

bracesB BandB BnotB BtheB BsquareB Bbrackets.


B

letB B{name}B B=B B{name:B B"Faraji",B Bage:B B23};


console.log(name);

//B B→B BFaraji


JSON

JSONB BrepresentsB BJavaScriptB BObjectB BNotationB BandB BitB BisB ButilizedB BasB BaB
communicationB BformatB BandB BdataB BstorageB BforB BtheB Bweb.B BJSONB BisB
B

veryB BsimilarB BtoB BJavaScriptB BinB BitsB BwritingB BstyleB BofB BarraysB BandB
B

object,B BalthoughB BthereB BareB Brestrictions.B BItsB BpropertyB BnamesB BshouldB


B

beB BenclosedB BwithinB BdoubleB Bquotes,B BitB BallowsB BonlyB BsimpleB BdataB
B

expressions,B BbindingB Betc.B BJSONB BdoB BnotB BallowB Bcomments.


B

HereB BisB BaB BsampleB BofB BaB BjournalB BentryB BrepresentedB BasB BJSONB Bdata:
{

"squirrel":B Bfalse,
"events":B B["work",B B"touchedB Btree",B B"pizza",B B"running"]
}

JavaScriptB BconsistsB BofB BtheB BfunctionsB BJSON.stringifyB BandB BJSON.parseB


toB BtransformB BdataB BtoB BandB BfromB BthisB Bformat.B BJSON.stringifyB BtakesB BaB
B
JavaScriptB BvalueB BandB BsendsB BbackB BaB BJSON-encodedB BstringB BwhileB
B

JSON.parseB BtakesB BaB BstringB BandB BtransformsB BitB BtoB BitsB BencodedB Bvalue.
B

letB BstringB B=B BJSON.stringify({squirrel:B Bfalse,


events:B B["weekend"]});
console.log(string);

//B B→B B{"squirrel":false,"events":["weekend"]}


console.log(JSON.parse(string).events);

//B B→B B["weekend"]


ReversingB BanB Barray
ArraysB BconsistB BofB BtheB BreverseB Bmethod,B BwhichB BisB BusedB BtoB BchangeB BanB
arrayB BbyB BreversingB BtheB BorderB BthatB BitsB BelementsB Bdisplay.
B

Summary

WeB BcoveredB BtheB BobjectsB BandB BarraysB BinB BthisB Bchapter,B BandB BtheyB
createB BwaysB BtoB BcategorizeB BvariousB BvaluesB BinB BaB BsingleB Bvalue.B
B

Fancifully,B BthisB BenablesB ByouB BtoB BinsertB BseveralB BassociatedB BitemsB BinB BaB
B

bagB BandB BmoveB BaboutB BwithB BtheB Bbag,B BratherB BthanB BenclosingB ByourB
B

armsB BaroundB BeveryB BsingularB BthingB BandB BtryingB BtoB BkeepB BthemB
B

differently.B BAB BlotB BofB BvaluesB BinB BJavaScriptB BcontainB Bproperties,B BtheB
B

inconsistencyB BbeingB BundefinedB BandB Bnull.B BYouB BcanB BaccessB BpropertiesB


B

usingB BtheB Bvalue.propB BorB Bvalue["prop"].B BYouB BcanB BuseB BnamesB BforB
B

objectsB BpropertiesB BandB BsaveB BaB BdefinedB BsetB BofB Bthem.B BArrays,B BasB
B

wellB BcontainB BdifferentB BamountsB BofB BsimilarB BfancifulB BvaluesB BandB


B

utilizeB BtheB BnumbersB B(beginningB BfromB B0)B BasB BtheB Bproperty’sB Bnames.B
B

ArraysB BcontainB BfewB BsetsB BofB Bproperties,B BwhichB BareB BtheB BlengthB BandB
B

severalB Bmethods.B BMethodsB BareB BfunctionsB BthatB BresideB BwithinB


B

propertiesB BandB BbehaveB BonB BtheB BvalueB BtheyB BareB BitsB Bproperty.B BYouB
B
canB BloopB BacrossB BarraysB BthroughB BaB BuniqueB BtypeB BofB BforB Bloop—forB
B

(theB BletB BelementB BofB BanB Barray).


B

Exercise

WriteB BaB BJavaScriptB BfunctionB BtoB BobtainB BtheB BfirstB BitemB BinB BanB Barray.B
SettingB BaB BparameterB B'n'B BwillB BsendB BbackB BtheB BfirstB B'n'B BelementsB BofB
B

theB Barray.
B

Data:

console.log(array_Clone([1,B B2,B B4,B B0]));


console.log(array_Clone([1,B B2,B B[4,B B0]]));
[1,B B2,B B4,B B0]
[1,B B2,B B[4,B B0]]
Solutions
Chapter 6: Higher-Order BB BB B

B Functions
AB BlargeB BprogramB BtakesB BtimeB BtoB BdevelopB BandB BproducesB BaB BlotB BofB
spaceB BforB BbugsB BtoB Bhide,B BwhichB BinB BturnB BmakesB BthemB BhardB BtoB Bfind.B
B

HereB BareB BexamplesB BofB BtwoB BlargeB Bprograms:


B

TheB BfirstB BisB Bself-contained,B BandB BtheB BstatementB BisB BsixB BlinesB Blong.
letB BtotalB B=B B0,B BcountB B=B B1;
whileB B(countB B<=B B10)B B{
totalB B+=B Bcount;
countB B+=B B1;
}
console.log(total);

TheB BsecondB BdependsB BonB BtwoB BexternalB Bfunctions,B BandB BtheB BstatementB
isB BoneB BlineB Blong.
B

console.log(sum(range(1,B B10)));
Abstraction

WhenB BitB BcomesB BtoB BJavaScriptB BprogrammingB Blanguage,B Bvocabulary’sB


useB BtheB BtermB Babstraction.B BAbstractionB BisB BusedB BtoB BhideB BdetailsB BandB
B

givesB BtheB BuserB BtheB BcapabilityB BtoB BtalkB BaboutB BproblemsB BonB BaB BhigherB
B

level.B BLetB BusB BdifferentiateB BtwoB BrecipesB BforB BpeaB Bsoup.B BFirst:
B

PerB Bperson,B BplaceB B1B BcupB BofB BdriedB BpeasB BwithinB BaB Bcontainer.B BPutB
enoughB BwaterB BtoB BcoverB BtheB Bpeas,B BletB BitB BsoakB BforB BaboutB B12B Bhours.B
B

RemoveB BitB BfromB BtheB BwaterB BandB BplaceB BitB BinB BaB BpotB BusedB BforB
B

cookingB BwithB BtheB BadditionB BofB BwaterB BfourB BcupsB BofB BwaterB B(4B Bcups).B
B
LetB BitB BboilB BforB BaboutB BtwoB Bhours,B Bper-personB BholdB BhalfB BofB BanB
B

onion,B BsliceB BitB BusingB BaB Bknife,B BandB BpourB BitB BintoB BtheB Bpeas,B BletB BitB
B

prepareB BforB B10B Bminutes.


B

ThenB BtheB BsecondB Brecipe


PerB Bperson:B BHalfB BanB Bonion,B BaB BstalkB BofB Bcelery,B B1B BcupB BdriedB BsplitB
peas,B BandB BaB Bcarrot.
B

DipB BtheB BpeasB BintoB BtheB BwaterB BforB BaboutB B12B Bhours.B BBoilB BitB BforB BaboutB
2B BhoursB BinB BwaterB B(4B Bcups),B BattachB BandB BsliceB Bvegetables.B BCookB BitB
B

forB B10B Bminutes.


B

TheB BcomputerB BperformsB BtasksB BoneB BbyB Bone,B BfromB BblindB BtoB Bhigh-
levelB Bconcepts.
AbstractingB Brepetition
PlainB BfunctionsB BareB BusedB BtoB BcreateB Babstractions.B BItB BisB BhabitualB BforB
aB BprogramB BtoB BrepeatB BaB BparticularB BfunctionB BaB BspecifiedB BamountB BofB
B

time.B ByouB BcanB BachieveB BthatB BwithB BaB BloopB BlikeB Bthis:
B

83

forB B(letB BiB B=B B0;B BiB B<B B10;B Bi++)B B{


console.log(i);
}

HereB BweB BwriteB BaB BfunctionB BthatB BcallsB Bconsole.logB BNB Btimes.
functionB BrepeatLog(n)B B{
forB B(letB BIB B=B B0;B BIB B<B Bn;B BI++)B B{
console.log(I);
}
}

IfB ByouB BwantB BtoB BperformB BaB BtaskB BdifferentB BfromB BloggingB BinB Bnumbers,B
youB BcanB BrollB BactionB BasB BaB BfunctionB Bvalue.
B
functionB Brepeat(n,B Baction)B B{
forB B(letB BIB B=B B0;B BIB B<B Bn;B BI++)B B{
action(i);
}
}

repeat(3,B Bconsole.log);
//B B→B B0
//B B→B B1
//B B→B B2
SometimesB ByouB BdoB BnotB BneedB BtoB BrollB BinB BaB BpredefinedB BfunctionB BtoB
BrepeatB BinB BaB Bloop,B BcreateB BaB BfunctionB BvalueB BasB BanB Balternative:
letB BlabelsB B=B B[];
repeat(5,B BiB B=>B B{
labels.push(`UnitB B${iB B+B B1}`);
});
console.log(labels);

//B B→B B["UnitB B1",B B"UnitB B2",B B"UnitB B3",B B"UnitB B4",B B"UnitB B5"]
ThisB BmethodB BlayoutB BlooksB BsimilarB BtoB BaB Bloop;B BitB BdefinesB BtheB BtypeB BofB
BloopB BandB BthenB BproduceB BaB Bbody.B BAlthoughB BtheB BbodyB BisB BwrittenB BinB
BfunctionB BenclosedB BinB BparenthesesB BofB BtheB BcallB BtoB Brepeat.
Higher-orderB Bfunctions
Higher-orderB BfunctionsB BareB BfunctionsB BthatB BworkB BonB BotherB BfunctionsB
BwhetherB BbyB BargumentsB BorB BbyB BsendingB BthemB Bback.B BThisB BtypeB BofB
BfunctionB BenablesB BuserB BtoB BabstractB BoverB Bactions.B BForB Binstance,B ByouB
BhaveB BaB BfunctionB BthatB BcanB BproduceB Bfunctions
functionB BgreaterThan(n)B B{
returnB BmB B=>B BmB B>B Bn;
}

letB BgreaterThan10B B=B BgreaterThan(10);


console.log(greaterThan10(11));

//B B→B Btrue


YouB BcanB BalsoB BhaveB BfunctionsB BthatB BcanB BtransformB BotherB Bfunctions.
functionB Bnoisy(f)B B{
returnB B(...args)B B=>B B{
console.log("callingB Bwith",B Bargs);
letB BresultB B=B Bf(...args);
console.log("calledB Bwith",B Bargs,B B",B Breturned",B Bresult);
returnB Bresult;
};
}

noisy(Math.min)(3,B B2,B B1);


//B B→B BcallingB BwithB B[3,B B2,B B1]
//B B→B BcalledB BwithB B[3,B B2,B B1],B BreturnedB B1
YouB BcanB BasB BwellB BwriteB BfunctionsB BthatB BproduceB BnewB BsetB BofB BcontrolB
Bflow.
functionB Bunless(test,B Bthen)B B{
ifB B(!test)B Bthen();
}
85

repeat(3,B BnB B=>B B{


unless(nB B%B B2B B==B B1,B B()B B=>B B{
console.log(n,B B"isB Beven");
});
});

//B B→B B0B BisB Beven


//B B→B B2B BisB Beven
ThisB BmethodB BisB BaB Bbuilt-inB BarrayB Bmethod,B BforEach,B BthatB BproduceB BaB
BloopB BsimilarB BtoB BtheB Bfor/ofB BloopB BasB BaB Bhigher-orderB Bfunction.
["A",B B"B"].forEach(lB B=>B Bconsole.log(l));
//B B→B BA
//B B→B BB
FilteringB Barrays
ToB BsearchB BforB BtheB BscriptB BinB BaB BdataB Bset,B BuseB BtheB BfollowingB Bfunction.B
BThisB BfunctionB BhelpsB BtoB BfilterB BoutB BelementB BthatB BfailedB BaB BtestB BinB BanB
Barray.
functionB Bfilter(array,B Btest)B B{
letB BpassedB B=B B[];
forB B(letB BelementB BofB Barray)B B{
ifB B(test(element))B B{
passed.push(element);
}
}

returnB Bpassed;
}

console.log(filter(SCRIPTS,B BscriptB B=>B Bscript.living));


//B B→B B[{name:B B"Adlam",B B…},B B…]
ThisB BfunctionB ButilizesB BtheB BargumentB BcalledB Btest,B BaB BfunctionB Bvalue,B
BtoB BcoverB BaB BgapB BduringB BtheB Bcalculation.B BItB BdeterminesB BwhichB
elementB BtoB Breceive.
B

Transforming with mapBB BB

TheB BmapB BmethodB BchangesB BanB BarrayB BbyB BsettingB BaB BfunctionB BtoB BeachB
andB BeveryB BofB BitsB BelementsB BandB BcreatingB BaB BnewB BarrayB BfromB BtheB
B

returnedB Bvalues.B BTheB BnewB BarrayB BconsistsB BofB BtheB BsameB BlengthB BwithB
B

theB BinputB BarrayB BbutB BwillB BmapB BoutB BitsB BcontentB BtoB BaB BrenewedB BforB
B

byB BtheB Bfunction.


B

functionB Bmap(array,B Btransform)B B{


letB BmappedB B=B B[];
forB B(letB BelementB BofB Barray)B B{
mapped.push(transform(element));
}

returnB Bmapped;
}

letB BrtlScriptsB B=B BSCRIPTS.filter(sB B=>B Bs.directionB B==B B"rtl");


console.log(map(rtlScripts,B BsB B=>B Bs.name));
//B B→B B["Adlam",B B"Arabic",B B"ImperialB BAramaic",B B…]
LikeB BforEachB BandB Bfilter.
SummarizingB BwithB Breduce
WhenB ByouB BaddB BupB Bnumbers,B BbeginB BwithB BzeroB BandB BaddB BtheB BforeachB
elementB BtoB BtheB Bsum.B BTheB BparameterB BtoB BreduceB BareB BmapB BfunctionB
B

combinationB BandB BbeginB BaB Bvalue.B BThisB BfunctionB BisB BmuchB BeasierB BtoB
B

understandB BthanB BtheB BfilterB BandB Bmap.B BItB BisB Bbelow:


B

functionB Breduce(array,B Bcombine,B Bbegin)B B{


letB BcurrentB B=B Bbegin;
forB B(letB BitemsB BofB Barrays)B B{
existingB B=B Bcombine(existing,B Belement);
}

returnB Bexisting;
}

console.log(reduce([0,1,B B2,B B3,B B4],B B(a,B Bb)B B=>B BaB B+B Bb,B B0));
//B B→B B10
ThisB BfunctionB BisB BsimilarB BtoB BtheB BstandardB BarrayB BmethodB BreduceB BandB
BattachesB BmoreB Bcomfort.
console.log([1,B B2,B B3,B B4].reduce((a,B Bb)B B=>B BaB B+B Bb));
//B B→B B10
IfB ByouB BwantB BtoB ButilizeB BreduceB BtoB BsearchB BforB BtheB BscriptB BwithB BtheB
BmoreB Bcharacters,B BwriteB BitB BlikeB Bthis:
functionB BcharacterCount(script)B B{
returnB Bscript.ranges.reduce((count,B B[from,B Bto])B B=>B B{
returnB BcountB B+B B(toB B-B Bfrom);
},B B0);
}

console.log(SCRIPTS.reduce((a,B Bb)B B=>B B{


returnB BcharacterCount(a)B B<B BcharacterCount(b)?B Bb:B Ba;
}));

//B B→B B{name:B B"Han",B B…}


Composability

TakeB BsomeB BtimeB BtoB BthinkB BaboutB BhowB BlongB BourB BlistB BofB BcodeB BwouldB
BhaveB BbeenB BwithoutB BtheB Bhigher-orderB Bfunctions.
letB BbiggestB B=B Bnull;
forB B(letB BscriptB BofB BSCRIPTS)B B{
ifB B(biggestB B==B BnullB B||
characterCount(biggest)B B<B BcharacterCount(script))B B{
biggestB B=B Bscript;
}
}
console.log(biggest);

//B B→B B{name:B B"Han",B B…}


YouB BcanB BuseB BtheB Bhigh-orderB BfunctionsB BwhenB ByouB BwantB BtoB BcomposeB
operations.B BForB Binstance,B BhereB BisB BaB BlineB BofB BcodeB BthatB BsearchesB BforB
B

theB BaverageB ByearB BforB BlivingB BandB BdeadB BinB Bhumans’B BscriptsB BinB BtheB
B

dataB Bset.
B

functionB Baverage(array)B B{
returnB Barray.reduce((a,B Bb)B B=>B BaB B+B Bb)B B/B Barray.length;
}
console.log(Math.round(average(

SCRIPTS.filter(sB B=>B Bs.living).map(sB B=>B Bs.year))));


//B B→B B1165
console.log(Math.round(average(

SCRIPTS.filter(sB B=>B B!s.living).map(sB B=>B Bs.year))));


//B B→B B204
TheB BblockB BofB BcodeB BdisplaysB BthatB BtheB BdeathB BscriptB BisB BolderB BthanB
theB BlivingB Bones.
B

Let’sB BbeginB BwithB BtheB BentireB Bscript,B BfilterB BoutB BtheB BdeadB B(orB Bliving),B
eradicateB BtheirB Byears,B BaverageB BthemB BandB BcompleteB BtheB Bresult.B BYouB
B

canB BasB BwellB BwriteB BtheseB BcalculationsB BasB BaB BbigB Bloop:
B

letB BtotalB B=B B0,B BcountB B=B B0;


forB B(letB BscriptB BofB BSCRIPTS)B B{
ifB B(script.living)B B{
totalB B+=B Bscript.year;
countB B+=B B1;
}
}

console.log(Math.round(totalB B/B Bcount));


//B B→B B1165
OurB BtwoB BexamplesB BareB BnotB Bidentical,B BtheB BfirstB BcreatesB BnewB BarraysB
whenB BadministeringB BtheB BmapB BandB BfilterB BwhileB BtheB BsecondB BcalculateB
B

numbersB Bonly.
B

Strings and character codes


BB BB BB

OneB BofB BtheB BsignificantB BuseB BofB BdataB BsetB BisB BtoB BfindB BoutB BwhatB BscriptB
aB BblockB BofB BtextB BisB Busing.B BBelowB BisB BaB BprogramB BthatB BperformsB BthatB
B

task.
B

EveryB BscriptB BcontainsB BanB BarrayB BofB BcharacterB BcodeB BrangesB BrelatedB
withB Bit.B BSo,B BifB ByouB BareB BgivenB BaB BcharacterB Bcode,B ButilizeB BthisB
B

functionB BtoB BsearchB BforB BtheB BequivalentB BscriptB B(ifB Bavailable):


B

functionB BcharacterScript(code)B B{
forB B(letB BscriptB BofB BSCRIPTS)B B{
ifB B(script.ranges.some(([from,B Bto])B B=>B B{
returnB BcodeB B>=B BfromB B&&B BcodeB B<B Bto;
}))B B{
returnB Bscript;
}
}

returnB Bnull;
}
console.log(characterScript(121));

//B B→B B{name:B B"Latin",B B…}


AnotherB Bhigh-orderB BfunctionB BisB BtheB BsameB Bmethod.B BThisB BmethodB
getsB BaB BtestB BfunctionB BandB BdetermineB BifB BthatB BfunctionB BsendsB BbackB
B

trueB BforB BanyB BcomponentB BinB BtheB Barray.


B

ThereB BareB BsomeB BoperationsB BonB BJavaScriptB BstringsB BlikeB BsecuringB


theirB BlengthB BusingB BtheB BlengthB BpropertyB BandB BevaluatingB BtheirB
B

contentsB BthroughB BtheB BsquareB Bbrackets.


B

//B BTwoB BemojiB Bcharacters,B BhorseB BandB Bshoe


letB BhorseShoeB B=B B" 🐴👟";
console.log(horseShoe.length);

//B B→B B4
console.log(horseShoe[0]);

//B B→B B(InvalidB Bhalf-character)


console.log(horseShoe.charCodeAt(0));

//B B→B B55357B B(CodeB BofB BtheB Bhalf-character)


console.log(horseShoe.codePointAt(0));

//B B→B B128052B B(ActualB BcodeB BforB BhorseB Bemoji)


JavaScript’sB BcharCodeAtB BmethodB BoffersB BaB BfullB BUnicodeB Bcharacter.B
ThisB BmethodB BisB BusedB BtoB BtakeB BcharactersB BfromB BaB Bstring.B BAlthoughB
B

theB BargumentB BsentB BtoB BcodePointAtB BremainsB BanB BindexB BintoB BtheB
B

successionB BofB BcodeB Bunits.B BIfB ByouB BuseB BtheB BcodePointAtB BtoB BloopB
B

acrossB BaB Bstring,B BitB BproducesB BrealB BcharactersB BandB BnotB BcodeB Bunits.
🌹🐉";
B

letB BroseDragonB B=B B"


forB B(letB BcharB BofB BroseDragon)B B{
console.log(char);
🌹
}

//B B→B B
// → 🐉
BB BB

RecognizingB Btext
YouB BhaveB BtheB BcharacterB BScriptB BfunctionB BandB BaB BwayB BtoB BloopB BacrossB
charactersB Bcorrectly,B BnowB BcalculateB BtheB BcharactersB BeachB BscriptB
B

owns.B BTheB BbelowB BcountingB BabstractionB BisB BusedB Bhere:


B

functionB BcountBy(items,B BgroupName)B B{


letB BcountsB B=B B[];
forB B(letB BitemB BofB Bitems)B B{
letB BnameB B=B BgroupName(item);
letB BknownB B=B Bcounts.findIndex(cB B=>B Bc.numberB B==B Bname);
ifB B(knownB B==B B-1)B B{
counts.push({nunber,B Bcount:B B0});
}B BelseB B{
counts[know].count++;
}
}

returnB Bcounts;
}

console.log(countBy([0,1,B B2,B B3,B B4,B B5],B BnB B=>B BnB B>B B2));
//B B→B B[{number:B Bfalse,B Bcount:B B2},B B{number:B Btrue,B Bcount:B B3}]
TheB BcountByB BfunctionB BanticipatesB BaB BcollectionB B(aB BgroupB BofB
numbers,B BelementB BorB BanythingB BthatB ByouB BcanB BloopB BoverB BwithB
B

for/of)B BandB BaB BfunctionB BthatB BcalculatesB BaB BgroupB BnameB BforB BaB
B

specifiedB Belement.B BItB BsendsB BbackB BaB BlistB BofB Bobjects.B BEachB BofB BtheB
B
objectsB BnamesB BaB BgroupB BandB BdeterminesB BtheB BnumberB BofB BelementsB
B

containedB BinB BtheB Bgroup.


B

TheB BmethodB BfindIndexB BisB BsimilarB BtoB BindexOf.B BThisB BmethodB BisB BusedB
toB BsearchB BforB BtheB BfirstB BvalueB BforB BwhichB BtheB BstatedB BfunctionB BsendsB
B

backB BtrueB BandB BreturnsB B-1B BwhenB BzeroB BelementsB BisB Bfound.B BYouB BcanB
B

useB BtheB BcountByB BtoB BdetermineB BwhichB BscriptB BisB ButilizedB BinB BaB BblockB
B

ofB Btext.
B

functionB BtextScripts(text)B B{
letB BscriptsB B=B BcountBy(text,B BcharB B=>B B{
letB BscriptB B=B BcharacterScript(char.codePointAt(0));
returnB Bscript?B Bscript.nameB B:B B"none";
}).filter(({name})B B=>B BnameB B!=B B"none");
letB BtotalB B=B Bscripts.reduce((n,B B{count})B B=>B BnB B+B Bcount,B B0);
ifB B(totalB B==B B0)B BreturnB B"NoB BscriptsB Bfound";
returnB Bscripts.map(({name,B Bcount})B B=>B B{
returnB B`${Math.round(countB B*B B100B B/B Btotal)}%B B${name}`;
}).join(",B B");
}

console.log(textScripts(' 英 国 的 狗 说 "woof",B B 俄罗斯的狗


说"тяв"'));
//B B→B B61%B BHan,B B22%B BLatin,B B17%B BCyrillic
TheB BfunctionB BcalculatesB BtheB BcharactersB BbyB BnameB BthroughB BtheB BuseB
ofB BcharacterScriptB BtoB BattachB BaB BnameB BandB BreturningB BbackB BtoB BtheB
B

stringB B"none"B BforB BcharactersB BwithoutB BanyB Bscript.B BIfB ByouB BwantB BtoB
B

calculateB Bpercentages,B ByouB BneedB BtoB BdetermineB BtheB BtotalB BamountB BofB
B

charactersB BbelongingB BtoB BaB BscriptB BthatB BtheB BreduceB BmethodB BcanB
B
reduce.B BIfB BitB BfindsB BzeroB Bcharacters,B BtheB BfunctionB BsendsB BbackB BtheB
B

"none"B Bstring.
B

Summary

HavingB BtheB BabilityB BtoB BsendB BfunctionB BvaluesB BtoB BseveralB BfunctionsB BisB
anB BessentialB BaspectB BofB BJavaScript.B BItB BenablesB BwritingB BfunctionsB BthatB
B

imitateB BcomputationsB BwithB B“gaps”B BbetweenB Bthem.B BTheB BcodeB BthatB


B

declaresB BtheseB BfunctionsB BcanB BcontainB BtheB BgapsB BbyB BgivingB BfunctionB
B

values.B BArraysB BprovideB BseveralB BimportantB Bhigher-orderB Bmethods.B


B

UseB BforEachB BtoB BloopB BacrossB BelementsB BwithinB BanB Barray.B BUseB BtheB
B

BfilterB BmethodB BtoB BsendB BbackB BaB BnewB BarrayB BthatB BhasB BelementsB BthatB
BconveyB BtheB BpredicateB Bfunction.B BChangingB BanB BarrayB BbyB BsettingB BeachB

itemB BthroughB BaB BfunctionB BusingB BtheB Bmap.B BUseB BreduceB BtoB BmergeB
B

everyB BcomponentB BofB BanB BarrayB BtoB BanB BindividualB Bvalue.


B

Exercises

IllustrateB BaB BJavaScriptB BfunctionB BthatB BtakesB BanB BarrayB BofB BnumbersB
savedB BandB BsearchB BforB BtheB Bsecond-lowestB BandB BsecondB BhighestB
B

numbers.
B

Solution
Chapter 7: The Secret Life
BB BB BB BB BB

of Objects
BB

WhenB BitB BcomesB BtoB BProgramingB Blanguages,B BthereB BisB BaB BsetB BtechniqueB
thatB ButilizesB BobjectsB BasB
B B aB fundamentalB
B ideaB
B ofB
B programB
B

organization,B
B andB
B BtheyB areB
B BcalledB theB
B object-orientedB
B

programming.B BItsB BconceptB BwillB BbeB BexplainedB BfurtherB BinB BthisB


B

chapter.
B

Encapsulation

TheB BprimaryB BimportanceB BofB Bobject-orientedB BprogrammingB BisB BtoB


breakB BprogramsB BintoB BlittleB BpiecesB BandB BmakesB BsureB BeachB BpieceB
B

managesB BitsB Bsection.B BSeveralB BfragmentsB BofB BsimilarB BprogramsB


B

communicateB BwithB BeachB BotherB BusingB Binterfaces,B BaB BrestrictedB BsetB BofB
B

functionsB BorB BbindingB BthatB BproduceB BessentialB BfunctionalityB BonB BaB


B

higherB Blevel,B BhidingB BtheB BspecificB Bexecution.B BIllustrateB BthisB BtypeB BofB
B

programB BpiecesB BthroughB Bobjects,B BandB BtheirB BlayoutB BcontainsB BaB


B

particularB BsetB BofB BpropertiesB BandB Bmethods.B BPropertiesB BwithinB BtheB


B

layoutB BareB BpublicB BwhileB BtheB BouterB BcodeB BisB Bprivate.B BDefineB BtheB
B

accessibleB BlayoutB BinB BcommentsB BorB Bdocumentation.B BItB BregularlyB BusesB


B

theB BunderscoreB B(_)B BcharacterB BatB BtheB BbeginningB BofB BpropertyB BnamesB
B

toB BsignifyB BprivateB Bproperties.B BMeanwhile,B BdivingB BlayoutsB BfromB


B

executionB BisB BcalledB Bencapsulation.


B

Methods

MethodsB BareB BpropertiesB BthatB BgraspB BfunctionB Bvalues.


letB BrabbitB B=B B{};
rabbit.speakB B=B Bfunction(line)B B{
console.log(`TheB BrabbitB BsaysB B'${line}'`);
};

rabbit.speak("I'mB Balive.");
//B B→B BTheB BrabbitB BsaysB B'I'mB Balive.'
WhenB ByouB BcallB BaB BfunctionB BasB BaB Bmethod,B BtheB BbindingB BcallsB BitB BinB BitsB
BbodyB BandB BdirectB BtheB BobjectB BitB BwasB BcalledB Bon.
functionB Bspeak(line)B B{
console.log(`TheB B${this.type}B BrabbitB BsaysB B'${line}'`);
}

letB BwhiteRabbitB B=B B{type:B B"white",B Bspeak};


letB BhungryRabbitB B=B B{type:B B"hungry",B Bspeak};
whiteRabbit.speak("OhB BmyB Bwhiskers,"B B+B B"howB BlateB Bit'sB Bgetting!");
//B B→B BTheB BwhiteB BrabbitB BsaysB B'OhB BmyB Bwhiskers,B Bhow
//B BlateB Bit'sB Bgetting!'
HungryRabbit.speak("IB BcouldB BuseB BaB BcarrotB BrightB Bnow.");
//B B→B BTheB BhungryB BrabbitB BsaysB B'IB BcouldB BuseB BaB BcarrotB BrightB Bnow.'
ArrowB BfunctionsB BareB BdoB BnotB BbindB BtheirB Bown.B BYouB BcanB BwriteB BtheB
BfollowingB Bcode:
functionB Bnormal()B B{
console.log(this.coords.map(nB B=>B BnB B/B Bthis.length));
}

normal.call({coords:B B[0,B B2,B B3],B Blength:B B5});


//B B→B B[0,B B0.4,B B0.6]
Prototypes

KeepB BanB BeyeB BoutB BonB Bthis.


letB BemptyB B=B B{};
console.log(empty.toString);

//B B→B BfunctionB BtoString()…{}


console.log(empty.toString());

//B B→B B[objectB BObject]


AB BpropertyB BisB BpulledB BoutB BofB BanB BemptyB Bobject.B BAB BlotB BofB BJavaScriptB
objectsB BconsistsB BofB BaB Bprototype.B BThisB BisB BanB BobjectB BusedB BasB BanB
B

alternativeB BsourceB BofB Bproperties.B BTherefore,B BtheB BprototypeB BofB BthatB


B

emptyB BobjectB BisB BtheB BinheritedB Bprototype,B BtheB BObject.prototype.


B

console.log(Object.getPrototypeOf({})B B==
Object.prototype);

//B B→B Btrue


console.log(Object.getPrototypeOf(Object.prototype));

//B B→B Bnull


Object.getPrototypeOfB BsendsB BbackB BtheB BprototypeB BofB BanB Bobject.B BThisB
prototypeB BproducesB BsomeB BmethodB BthatB BdisplaysB BinB BeveryB BobjectB
B

likeB BtoStringB BthatB BtransformsB BanB BobjectB BtoB BaB BstringB Bexecution.
B

AB BlotB BofB BobjectsB BdoB BnotB BcontainB BObject.prototypeB BasB BtheirB


prototypeB BbutB BuseB BanotherB BobjectB BthatB BproducesB BaB BseparateB BsetB BofB
B

defaultB Bproperties;
B

FunctionsB BacquiresB BfromB BFunction.prototype,B BandB BarraysB BacquiresB


fromB BArray
B

.prototype.

console.log(Object.getPrototypeOf(Math.max)B B==
Function.prototype);

//B B→B Btrue


console.log(Object.getPrototypeOf([])B B==
Array.prototype);

//B B→B Btrue


ThisB BtypeB BofB BprototypeB BobjectB BcontainsB BaB Bprototype,B BtheB
BObject.prototype,B BsoB BthatB BitB BcanB BcreateB BmethodsB BsuchB BasB BtoStringB
Bindirectly.B BUseB BtheB BObject.createB BtoB BbuildB BanB BobjectB BwithB BaB
BparticularB Bprototype.
letB BprotoRabbitB B=B B{
speak(line)B B{
console.log(`TheB B${this.type}B BrabbitB BsaysB B'${line}'`);
}
};

letB BkillerRabbitB B=B BObject.create(protoRabbit);


killerRabbit.typeB B=B B"killer";
killerRabbit.speak("SKREEEE!");

//B B→B BTheB BkillerB BrabbitB BsaysB B'SKREEEE!


TheyB Bspeak(line)B BpropertyB BinB BanB BobjectB BexpressionB BproducesB BaB
BpropertyB BcalledB BspeakB BandB BsetB BaB BfunctionB BasB BitsB Bvalue.B BItB BisB BaB
BshorthandB BwayB BofB BdescribingB BaB Bmethod.
TheB B“proto”B BrabbitB BisB BaB BcontainerB BforB BallB Bproperties.
Classes

JavaScript’sB BprototypeB BsystemB BcanB BbeB BdescribedB BasB BsubsidiaryB BonB BanB
Bobject-orientedB BmethodB BcalledB Bclasses.B BAB BclassB BdescribesB BanB BobjectB
Btype'sB Bshape,B BitsB BpropertiesB BandB Bmethods.B BPrototypesB BareB BusedB BtoB
BdescribeB BpropertiesB BwherebyB BeveryB BinstanceB BshareB BsimilarB BvaluesB
BsuchB BasB Bmethods.B BIfB ByouB BwantB BtoB BbuildB BanB BinstanceB BofB BaB BsetB Bclass,B
BcreateB BanB BobjectB BthatB BreceivesB BfromB BtheB BnormalB BPrototype.B BMakeB
BsureB BitB BcontainsB BpropertiesB BthatB BshouldB BbeB BincludedB BinB BtheB
BinstanceB BofB BthisB Bclass.B BBelowB BisB BtheB BconstructorB Bfunction.
functionB BmakeRabbit(type)B B{
letB BrabbitB B=B BObject.create(protoRabbit);
rabbit.typeB B=B Btype;
returnB Brabbit;
}

JavaScriptB BoffersB BaB BwayB BtoB BmakeB BdescribingB BthisB BfunctionB


Beffortlessly.B BSetB BtheB BkeywordB BatB BtheB BfrontB BofB BaB BfunctionB Bcall.B BTheB
BprototypeB BobjectB ButilizedB BduringB BtheB BconstructionB BofB BobjectsB BisB
BattainedB BbyB BfetchingB BtheB BprototypeB BpropertyB BofB BtheB BconstructorB

Bfunction.
functionB BRabbit(type)B B{
this.typeB B=B Btype;
}

Rabbit.prototype.speakB B=B Bfunction(line)B B{


console.log(`TheB B${this.type}B BrabbitB BsaysB B'${line}'`);
};

letB BweirdRabbitB B=B BnewB BRabbit("weird");


Function.prototypeB BisB BtheB BprototypeB BofB BaB Bconstructor.B BItsB BprototypeB
BpropertyB BgraspsB BtheB BprototypeB ButilizedB BforB BinstancesB BbuiltB BthroughB
Bit.
console.log(Object.getPrototypeOf(Rabbit)B B==
Function.prototype);

//B B→B Btrue


console.log(Object.getPrototypeOf(weirdRabbit)B B==
Rabbit.prototype);
//B B→B Btrue
ClassB Bnotation
JavaScriptB BclassesB BareB BconstructorB BfunctionsB BwithB BaB BprototypeB
property.B BBelowB BisB BaB Bsample:
B

classB BRabbitB B{
constructor(type)B B{
this.typeB B=B Btype;
}

speak(line)B B{
console.log(`TheB B${this.type}B BrabbitB BsaysB B'${line}'`);
}
}

letB BkillerRabbitB B=B BnewB BRabbit("killer");


letB BblackRabbitB B=B BnewB BRabbit("black");
TheB BclassB BkeywordB BbeginsB BwithB BaB BclassB Bdeclaration,B BwhichB BenablesB
youB BtoB BdescribeB BaB BconstructorB BandB BaB BsetB BofB BmethodsB BinB BaB
B

particularB Bplace.B BClassB BdeclarationsB BenablesB Bmethods,B BpropertiesB


B

thatB BgraspB BfunctionsB BtoB BbeB BincludedB BinB BtheB Bprototype.B BWhenB ByouB
B

useB BanB Bexpression,B BitB BdoesB BnotB BdescribeB BaB BbindingB BburB BprovidesB
B

theB BconstructorB BasB BaB Bvalue.B BYouB BcanB BexcludeB BtheB BclassB BnameB BinB
B

anB Bexpression.
B

letB BobjectB B=B BnewB BclassB B{getWord()B B{B BreturnB B"hello";B B}B B};
console.log(object.getWord());

//B B→B Bhello


OverridingB BderivedB Bproperties
WhenB BaB BpropertyB BisB BaddedB BtoB BanB Bobject,B BeitherB BavailableB BinB BtheB
prototypeB BorB Bnot,B BtheB BpropertyB BaddsB BtoB BtheB Bobject.B BIfB BthereB BwasB
B

anB BassignedB BpropertyB BwithB BsimilarB BnamesB BinB BtheB Bprototype,B BitB
B

doesB BnotB BinfluenceB BtheB Bobject.


B

Rabbit.prototype.teethB B=B B"small";


console.log(killerRabbit.teeth);

//B B→B Bsmall


killerRabbit.teethB B=B B"long,B Bsharp,B BandB Bbloody";
console.log(killerRabbit.teeth);

//B B→B Blong,B Bsharp,B BandB Bbloody


console.log(blackRabbit.teeth);

//B B→B Bsmall


console.log(Rabbit.prototype.teeth);

//B B→B Bsmall


OverridingB BpropertiesB BisB BusedB BtoB BbestowB BaB BstandardB BfunctionB BandB
arrayB BprototypesB BaB BseparateB BtoStringB Bmethod.
B

console.log(Array.prototype.toStringB B==
Object.prototype.toString);

//B B→B Bfalse


console.log([1,B B3].toString());
//B B→B B1,3
CallingB BtoStringB BonB BanB BarrayB BbestowsB BaB BresultB BthatB BisB BlikenedB BtoB
calling.B Bjoin(",")B BonB Bit.B BItB BplacesB BaB BcommaB BbetweenB BtheB BvaluesB
B

containedB BinB BtheB Barray.B BIfB ByouB BcallB BObject.prototype.toStringB BtoB BanB
B

array,B BitB BprovidesB BaB BseparateB Bstring.


B

console.log(Object.prototype.toString.call([1,B B3]));
//B B→B B[objectB BArray]
Maps

AB BmapB BisB BaB BdataB BlayoutB BthatB BconnectB BvaluesB BwithB BotherB Bvalues.B BIfB
ByouB BwantB BtoB BmapB BnamesB BtoB Bages,B BwriteB ByourB BcodeB BlikeB Bthis:
letB BagesB B=B B{
Boris:B B39,
Liang:B B22,
Júlia:B B62
};

console.log(`JuliaB BisB B${ages["Julia"]}`);


//B B→B BJuliaB BisB B62
console.log("IsB BJack'sB BageB Bknown?",B B"Jack"B BinB Bages);
//B B→B BIsB BJack'sB BageB Bknown?B Bfalse
console.log("IsB BtoString'sB BageB Bknown?",B B"toString"B BinB Bages);
//B B→B BIsB BtoString'sB BageB Bknown?B Btrue
ObjectB BpropertyB BnamesB BshouldB BbeB BinB Bstrings.B BIfB ByouB BwantB BaB BmapB
BthatB BtheB BkeysB BcannotB BbeB BtransformedB BtoB Bstrings,B BdoB BnotB BuseB
BobjectB BasB BaB Bmap.B BJavaScriptB BcontainsB BaB BclassB BcalledB Bmap.B BItB BsavesB
BmappingB BandB BenablesB BdifferentB BtypesB BofB Bkeys.
letB BagesB B=B BnewB BMap();
ages.set("Boris",B B39);
ages.set("Liang",B B22);
ages.set("Júlia",B B62);
console.log(`JúliaB BisB B${ages.get("Júlia")}`);
//B B→B BJúliaB BisB B62
console.log("IsB BJack'sB BageB Bknown?",B Bages.has("Jack"));
//B B→B BIsB BJack'sB BageB Bknown?B Bfalse
console.log(ages.has("toString"));

//B B→B Bfalse


TheB BmethodsB Bget,B Bset,B BandB BhasB BareB BbodiesB BofB BtheB BlayoutB BofB BtheB
BmapB Bobject.B BTheB BObject.keysB BsendsB BbackB BanB Bobject’sB BownB BkeysB
Bonly.B BYouB BcanB BuseB BtheB BhasOwnPropertyB BmethodB BasB BanB Boption.
console.log({x:B B1}.hasOwnProperty("x"));
//B B→B Btrue
console.log({x:B B1}.hasOwnProperty("toString"));
//B B→B Bfalse
Polymorphism

WhenB BaB BstringB BfunctionB BisB BcalledB BonB BanB Bobject,B BtheB BtoStringB
BmethodB BisB BcalledB BonB BthatB BobjectB BinB BorderB BtoB BbuildB BaB BsignificantB
BstringB BfromB Bit.B BYouB BcanB BdefineB ByourB BownB BversionB BofB BtoStringB BsoB
BthatB BtheyB BcanB BbuildB BaB BstringB BthatB BconsistsB BofB BmoreB BimportantB BdataB
BmoreB BthanB BtheB B"[objectB BObject]".B BBelowB BisB BanB Billustration:
Rabbit.prototype.toStringB B=B Bfunction()B B{
returnB B`aB B${this.type}B Brabbit`;
};
console.log(String(blackRabbit));

//B B→B BaB BblackB Brabbit


WhenB BaB BlineB BofB BcodeB BisB BwrittenB BtoB BfunctionB BwithB BobjectsB BthatB BhaveB
BaB BspecificB BlayoutB BisB BcalledB Bpolymorphism.B BPolymorphicB BcodeB BcanB
BfunctionB BproperlyB BwithB BvaluesB BofB BseveralB Bshapes.
Symbols

SymbolsB BareB BuniqueB BvaluesB BbuiltB BwithB BtheB BSymbolB BfunctionB BwhichB
BcannotB BbeB BbuiltB Btwice.
letB BsymB B=B BSymbol("name");
console.log(symB B==B BSymbol("name"));
//B B→B Bfalse
Rabbit.prototype[sym]B B=B B55;
console.log(blackRabbit[sym]);

//B B→B B55


TheB BstringB BpassedB BtoB BtheB BsymbolB BisB BattachedB BwhenB ByouB BtransformB
BitB BtoB BaB Bstring.B BTheyB BareB BdistinctiveB BandB BfunctionsB BasB BpropertyB
Bnames.
constB BtoStringSymbolB B=B BSymbol("toString");
Array.prototype[toStringSymbol]B B=B Bfunction()B B{
returnB B`${this.length}B BcmB BofB BblueB Byarn`;
};

console.log([1,B B2].toString());
//B B→B B1,2
console.log([1,B B2][toStringSymbol]());
//B B→B B2B BcmB BofB BblueB Byarn
YouB BcanB BattachB BtheB BsymbolB BpropertiesB BinB BobjectB BclassesB BandB
BexpressionsB BthroughB BtheB BuseB BofB BsquareB BbracketsB BsurroundingB BtheB
BpropertyB Bname.B BBelowB BweB BreferB BtoB BaB BbindingB BstoringB BtheB Bsymbol.
letB BstringObjectB B=B B{
[toStringSymbol]()B B{B BreturnB B"aB BjuteB Brope";B B}
};
console.log(stringObject[toStringSymbol]());

//B B→B BaB BjuteB Bropes


TheB BiteratorB Binterfaces
TheB BstatedB BobjectB BtoB BaB Bfor/ofB BloopB BisB Biterable.B BThisB BmeansB BthatB BitB
consistsB BofB BaB BnamedB BmethodB BwithB BtheB BSymbol.iteratorB BsymbolB
B

whenB BtheB BpropertyB BisB Bcalled.B BTheB BmethodB BsendsB BbackB BanB BobjectB
B

thatB BproducesB BaB BsecondB Blayout.B BItB BcontainsB BaB BnextB BmethodB BthatB
B

sendsB BbackB BtheB BfollowingB Bresult.B BTheB BresultB BisB BanB BobjectB BwithB BaB
B

valueB BpropertyB BthatB BproducesB BtheB BnextB Bvalue,B BSymbol.iteratorB BcanB


B

beB BaddedB BtoB BseveralB Bobjects.B BCheckoutB BthisB Blayout:


B

letB BokIteratorB B=B B"OK"[Symbol.iterator]();


console.log(okIterator.next());

//B B→B B{value:B B"O",B Bdone:B Bfalse}


console.log(okIterator.next());

//B B→B B{value:B B"K",B Bdone:B Bfalse}


console.log(okIterator.next());

//B B→B B{value:B Bundefined,B Bdone:B Btrue}


Let’sB BimplementB BanB BiterableB BdataB Bstructure.B BWe’llB BbuildB BaB BmatrixB
class,B Bacting
B

asB BaB Btwo-dimensionalB BarrayB BclassB BMatrixB B{


constructor(width,B Bheight,B BelementB B=B B(x,B By)B B=>B Bundefined)B B{
this.widthB B=B Bwidth;
this.heightB B=B Bheight;
this.contentB B=B B[];
forB B(letB ByB B=B B0;B ByB B<B Bheight;B By++)B B{
forB B(letB BxB B=B B0;B BxB B<B Bwidth;B Bx++)B B{
this.content[yB B*B BwidthB B+B Bx]B B=B Belement(x,B By);
}
}
}
get(x,B By)B B{
returnB Bthis.content[yB B*B Bthis.widthB B+B Bx];
}

set(x,B By,B Bvalue)B B{


this.content[yB B*B Bthis.widthB B+B Bx]B B=B Bvalue;
}
}

TheB BcontentB BofB BtheB BclassB BisB BsavedB BinB BanB BindividualB BarrayB BofB BwidthB
× heightB Belements.B BTheseB BelementsB BareB BsavedB BrowB BafterB Brow.B BTheB
B BB

constructorB BfunctionB BgetsB BaB Bwidth,B Bheight,B BandB BanB BadditionalB


B

elementB Bfunction,B BwhichB BisB BusedB BtoB BsetB BtheB BinitialB Bvalues.B BUseB BtheB
B

BgetB BmethodB BandB BsetB BmethodB BtoB BrecoverB BandB BupdateB BelementsB
BwithinB BtheB Bmatrix.B BBelowB BisB BtheB BlayoutB BofB BobjectsB BwithB Bx,B By,B BandB

valueB Bproperties.
B

classB BMatrixIteratorB B{
constructor(matrix)B B{
this.xB B=B B0;
this.yB B=B B0;
this.matrixB B=B Bmatrix;
}

next()B B{
ifB B(this.yB B==B Bthis.matrix.height)B BreturnB B{done:B Btrue};
letB BvalueB B=B B{x:B Bthis.x,
y:B Bthis.y,
value:B Bthis.matrix.get(this.x,B Bthis.y)};
this.x++;
ifB B(this.xB B==B Bthis.matrix.width)B B{
this.xB B=B B0;
this.y++;
}

returnB B{value,B Bdone:B Bfalse};


}
}

BelowB BisB BanB BillustrationB BofB BanB BiterableB BMatrixB Bclass:


Matrix.prototype[Symbol.iterator]B B=B Bfunction()B B{
returnB BnewB BMatrixIterator(this);
};

WeB BcanB BnowB BloopB BoverB BaB BmatrixB BwithB Bfor/of.


letB BmatrixB B=B BnewB BMatrix(2,B B2,B B(x,B By)B B=>B B`valueB B${x},${y}`);
forB B(letB B{x,B By,B Bvalue}B BofB Bmatrix)B B{
console.log(x,B By,B Bvalue);
}

//B B→B B0B B0B BvalueB B0,0


//B B→B B1B B0B BvalueB B1,0
//B B→B B0B B1B BvalueB B0,1
//B B→B B1B B1B BvalueB B1,1
Statics, getters, and setters
BB BB BB

LayoutsB BconsistsB BofB Bmethods,B BbutB ByouB BcanB BalsoB BattachB BpropertiesB
BthatB BstoresB BvaluesB BwithB BnoB BfunctionB BlikeB BaB BMapB BobjectB BcontainingB
BaB BsizeB BpropertyB BthatB BdeterminesB BhowB BmanyB BkeysB BareB BsavedB BinB
Bthem.B BAnB BassessedB BpropertyB BcanB BhideB BaB BmethodB Bcall.B BThoseB
BmethodsB BareB BcalledB Bgetters,B BandB ByouB BcanB BdescribeB BthemB BbyB
BwritingB B"get"B BatB BtheB BbeginningB BofB BtheB BmethodB BnameB BinB BaB BclassB
BdeclarationB BorB BanB BobjectB Bexpression.
letB BvaryingSizeB B=B B{
getB Bsize()B B{
returnB BMath.floor(Math.random()B B*B B100);
}
};
console.log(varyingSize.size);

//B B→B B73


console.log(varyingSize.size);

//B B→B B49


WhenB ByouB BwantB BtoB BuseB BanB Bobject’sB BsizeB Bproperty,B ByouB BcallB BtheB
BassociatedB Bmethod.B BYouB BcanB BperformB BaB BsimilarB BtaskB BwhenB ByouB BaB
BpropertyB BusingB BaB Bsetter.
classB BTemperatureB B{
constructor(celsius)B B{
this.celsiusB B=B Bcelsius;
}

getB Bfahrenheit()B B{
returnB Bthis.celsiusB B*B B1.8B B+B B32;
}

setB Bfahrenheit(value)B B{
this.celsiusB B=B B(valueB B-B B32)B B/B B1.8;
}

staticB BfromFahrenheit(value)B B{
returnB BnewB BTemperature((valueB B-B B32)B B/B B1.8);
}
}

letB BtempB B=B BnewB BTemperature(22);


console.log(temp.fahrenheit);

//B B→B B71.6


temp.fahrenheitB B=B B86;
console.log(temp.celsius);

//B B→B B30


TheB BTemperatureB BclassB BenableB ByouB BtoB BreadB BandB BwriteB BtheB
temperatureB BinB BdegreesB BCelsiusB BorB BdegreesB BFahrenheit,B BbutB BitB BsavesB
B

onlyB BCelsiusB BandB BtransformB BtoB BandB BfromB BCelsiusB BinB BtheB BFahrenheitB
B

getterB BandB Bsetter.B BWithinB BaB BclassB Bdeclaration,B BmethodsB BthatB BareB
B

staticB BwrittenB BbeforeB BtheirB BnamesB BareB BsavedB BonB BtheB Bconstructor.B
B

So,B ByouB BcanB BwriteB BTemperature.fromFahrenheit(100)B BtoB BbuildB BaB


B

temperatureB BthroughB BdegreesB BFahrenheit.


B

Inheritance

SomeB BmatricesB BareB Bsymmetric.B BWhenB ByouB BreflectB BaB BsymmetricB


matrixB BthroughB BitsB Btop-left-to-bottom-rightB Bdiagonal,B BitB BdoesB BnotB
B

Bchange.B BTheB BvalueB BsetB BatB Bx,yB BremainsB BtheB BsameB BasB BtheB By,x.B BUseB
BtheB BJavaScript’sB BprototypeB BsystemB BtoB BbuildB BaB BnewB Bclass,B BtheB

prototypeB BforB BtheB BnewB BclassB BisB BacquiredB BfromB BtheB BoldB BprototypeB
B

butB BsetsB BaB BnewB BdefinitionB BforB BtheB Bmethod.B BThisB BisB BcalledB
B

inheritanceB BinB Bobject-orientedB BprogrammingB Bterms.B BBelowB BisB BanB


B

illustration:
B

classB BSymmetricMatrixB BextendsB BMatrixB B{


constructor(size,B BelementB B=B B(x,B By)B B=>B Bundefined)B B{
super(size,B Bsize,B B(x,B By)B B=>B B{
ifB B(xB B<B By)B BreturnB Belement(y,B Bx);
elseB BreturnB Belement(x,B By);
});
}

set(x,B By,B Bvalue)B B{


super.set(x,B By,B Bvalue);
ifB B(xB B!=B By)B B{
super.set(y,B Bx,B Bvalue);
}
}
}

letB BmatrixB B=B BnewB BSymmetricMatrix(5,B B(x,B By)B B=>B B`${x},${y}`);


console.log(matrix.get(2,B B3));
//B B→B B3,2
TheB BinstanceofB Boperator
ItB BisB BimportantB BtoB BknowB BifB BanB BobjectB BwasB BgottenB BfromB BaB BparticularB
Binstanceof.
console.log(

newB BSymmetricMatrix(2)B BinstanceofB BSymmetricMatrix);


//B B→B Btrue
console.log(newB BSymmetricMatrix(2)B BinstanceofB BMatrix);
//B B→B Btrue
console.log(newB BMatrix(2,B B2)B BinstanceofB BSymmetricMatrix);
//B B→B Bfalse
console.log([1]B BinstanceofB BArray);
//B B→B Btrue
TheB BoperatorB BwillB BscanB BthroughB BtheB BtypesB BthatB BwereB Binherited.B
Therefore,B BaB BSymmetricMatrixB BisB BanB BinstanceB BofB BMatrix.B BYouB BcanB
B

alsoB BapplyB BthisB BmethodB BtoB BstandardB BconstructorsB BlikeB BArray.


B

Summary

InB BthisB Bchapter,B BweB BrealizeB BthatB BobjectsB BcanB BperformB BmoreB BthanB
holdingB BtheirB Bproperties.B BTheyB BconsistB BofB BprototypesB BthatB BareB
B

objectsB BasB Bwell.B BTheyB BbehaveB BlikeB BtheyB BcontainB BpropertiesB BthatB
B

theyB BdoB BnotB BprovideB BasB BlongB BasB BtheB BprototypeB BhasB BthatB Bproperty.B
B

SimpleB BobjectsB BuseB BtheB BObject.B BPrototypeB BtoB BrepresentB BtheirB


B

prototype.B BWeB BtalkedB BaboutB BConstructorsB Btoo,B BandB BtheyB BareB


B

functionsB BthatB BtheirB BnamesB BoftenB BbeginB BwithB BaB BcapitalB Bletter,B BandB
B

usedB BwithB BtheB BnewB BoperatorB BtoB BbuildB BnewB Bobjects.B BTheB BnewB
B

object’sB BprototypeB BwouldB BbeB BtheB BobjectB BwithinB BtheB BprototypeB


B

propertyB BofB BtheB Bconstructor.B BAB BclassB BnotationB BoffersB BaB BwayB BtoB
B

describeB BaB BconstructorB BandB BitsB Bprototype.B BWeB BalsoB BtouchedB BtheB
B

Getters,B Bsetters,B BandB BstaticsB BandB BtheB BinstanceofB Boperator.


B

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BcreateB BanB Barray,B BthroughB BanB
iteratorB BfunctionB BandB BaB BprimaryB BseedB Bvalue.
B

Solution
Chapter 8: A Robot BB BB BB

InB BthisB Bchapter,B BthereB BwillB BbeB BworkB BonB BaB BrobotB Bprogram,B BaB BshortB
programB BthatB BexecutesB BaB BtaskB BinB BaB BvirtualB Bworld.B BWeB BwillB BbeB
B

usingB BaB BmailB BdeliveryB BrobotB BreceivingB BandB BdeliveringB Bparcels.


B

MeadowB Bfield
TheB BMeadowB BfieldB BvillageB BisB BaB BsmallB BoneB BconsistingB BofB B14B BroadsB
andB B11B Bplaces.B BBelowB BisB BanB BillustrationB BwithB BanB BarrayB BofB Broads:
B

constB BroadsB B=B B[


"Alice'sB BHouse-Bob'sB BHouse",B B"Alice'sB BHouse-Cabin",
"Alice'sB BHouse-PostB BOffice",B B"Bob'sB BHouse-TownB BHall",
"Daria'sB BHouse-Ernie'sB BHouse",B B"Daria'sB BHouse-TownB BHall",
"Ernie'sB BHouse-Grete'sB BHouse",B B"Grete'sB BHouse-Farm",
"Grete'sB BHouse-Shop",B B"Marketplace-Farm",
"Marketplace-PostB BOffice",B B"Marketplace-Shop",
"Marketplace-TownB BHall",B B"Shop-TownB BHall"
]

TheB BvillageB BroadsB BcreateB BaB Bgraph.B BAB BgraphB BisB BaB BgroupB BofB BpointsB
(villageB Bplaces)B BwithB BlinesB BdividingB BthemB B(roads).B BTheB BgraphB BisB BtheB
B

worldB BwhereB BourB BrobotB BwalksB Bthrough.B BNowB BletB BusB BtransformB BourB
B

listB BtoB BaB BdataB BlayoutB BthatB BeachB BplaceB BdecidesB BwhereB ByouB Bcan.
B

functionB BbuildGraph(border)B B{
letB BgraphB B=B BObject.create(Null);
functionB BaddBorders(from,B Bto)B B{
ifB B(graph[from]B B==B Bnull)B B{
graph[from]B B=B B[to];
}B BelseB B{
graph[from].push(to);
}
}

forB B(letB B[from,B Bto]B BofB Bborders.map(rB B=>B Br.split("-")))B B{


addEdge(from,B Bto);
addEdge(to,B Bfrom);
}

returnB Bgraph;
}

constB BroadGraphB B=B BbuildGraph(roads);


GivenB BanB BarrayB BofB Bedges,B BbuildGraphB BcreatesB BaB BmapB BobjectB Bthat,B
forB BeachB Bnode,B BsavesB BaB BconnectedB BnodeB BofB BanB Barray.B BItB ButilizesB
B

theB BsplitB BmethodB BtoB BgoB BthroughB BtheB BroadB Bstrings,B BthatB BcontainsB
B

theB BformB B"Start-End",B BtoB Btwo-elementB BarraysB BwithinB BtheB BstartB BandB
B

endB BasB BdifferentB Bstrings.


B

The task
BB

OurB BrobotB BwillB BwalkB BacrossB BtheB Bvillage.B BThereB BareB BdifferentB BparcelsB
inB BseveralB Bplaces.B BTheB BrobotB BreceivesB BaB BparcelB BwhenB BitB BarrivesB
B

andB BdeliversB BthemB BwhenB BitB BgetsB BtoB BtheirB Bdestination.B BWhenB BallB
B

tasksB BhaveB BallB BbeenB Bexecuted,B BallB BparcelsB BmustB BbeB Bdelivered.B BIfB
B

youB BwantB BtoB BreplicateB BthisB Bprocess,B BdescribeB BaB BvirtualB BworldB BthatB
B

canB BdefineB Bit.B BThisB BmethodB BrevealsB BtheB BrobotB BlocationB BasB BwellB BasB
B

theB Bparcels.B BLetB BusB BbringB BdownB BtheB Bvillage'sB BstateB BtoB BaB BspecificB
B

setB BofB BvaluesB BthatB BdescribesB Bit.


B

classB BVillageStateB B{
constructor(place,B Bparcels)B B{
this.placeB B=B Bplace;
this.parcelsB B=B Bparcels;
}

move(destination)B B{
ifB B(!roadGraph[this.place].includes(destination))B B{
returnB Bthis;
}B BelseB B{
letB BparcelsB B=B Bthis.parcels.map(pB B=>B B{
ifB B(p.placeB B!=B Bthis.place)B BreturnB Bp;
returnB B{place:B Bdestination,B Baddress:B Bp.address};
}).filter(pB B=>B Bp.placeB B!=B Bp.address);
returnB BnewB BVillageState(destination,B Bparcels);
}
}
}

TheB BmoveB BmethodB BisB BtheB BactionB Bcenter.B BItB BexaminesB BifB BaB BpathB
BleadsB BfromB BoneB BplaceB BtoB Banother,B BifB BnotB BtheB BoldB BstateB BisB BreturnedB
BbecauseB BtheB BmoveB BisB BnotB Bvalid.B BThenB BitB BbuildsB BaB BnewB BstateB BwithB
BtheB BdestinationB BasB BtheB Brobot’sB BnewB BplaceB BasB BwellB BasB BbuildingB BaB
BnewB BsetB BofB Bparcels.B BTheB BcallB BtoB BmapB BhandlesB BtheB BmovementB BandB
BtheB BcallB BtoB BfilterB BhandlesB Bdelivering.

letB BfirstB B=B BnewB BVillageState(


"PostB BOffice",
[{place:B B"PostB BOffice",B Baddress:B B"Alice'sB BHouse"}]
);
letB BnextB B=B Bfirst.move("Alice'sB BHouse");
console.log(next.place);

//B B→B BAlice'sB BHouse


console.log(next.parcels);

//B B→B B[]


console.log(first.place);

//B B→B BPostB BOffice


PersistentB Bdata
UnchangeableB BdataB BlayoutsB BareB BcalledB BimmutableB BorB Bpersistent.B
TheyB BactB BlikeB BstringsB BandB Bnumbers.B BInB BJavaScript,B ByouB BcanB BchangeB
B

almostB Beverything.B BThereB BisB BaB BfunctionB BnamedB BObject.freezeB BthatB


B

transformsB BanB BobjectB BsoB BthatB BitB BdisregardsB BwritingB BtoB BitsB
B

properties.
B

letB BobjectB B=B BObject.freeze({value:B B5});


object.valueB B=B B10;
console.log(object.value);

//B B→B B5
Simulation

AB BdeliveryB BrobotB BtakesB BaB BgoodB BglanceB BatB BtheB BworldB BandB
determinesB BwhatB BdirectionB BitB BmovesB Bto.B BTherefore,B BaB BrobotB BisB BaB
B

functionB BwhichB BtakesB BaB BVillageStateB BobjectB BandB BsendB BbackB BtheB
B

nameB BofB BaB BnearbyB Bplace.B BTheB BrobotB BsendsB BbackB BanB BobjectB
B

consistingB BofB BitsB BintendedB BdirectionB BandB BaB BmemoryB BvalueB BreturnedB
B

theB BnextB BtimeB ByouB BcallB Bit.


B

functionB BrunRobot(state,B Brobot,B Bmemory)B B{


forB B(letB BturnB B=B B0;;B Bturn++)B B{
ifB B(state.parcels.lengthB B==B B0)B B{
console.log(`DoneB BinB B${turn}B Bturns`);
break;
}

letB BactionB B=B Brobot(state,B Bmemory);


stateB B=B Bstate.move(action.direction);
memoryB B=B Baction.memory;
console.log(`MovedB BtoB B${action.direction}`);
}
}

TheB BrobotB BcanB BwalkB BthroughB BinB BdifferentB BdirectionsB BatB BeveryB Bturn.B
ItB BcanB BrunB BintoB BallB BparcelsB BandB BthenB BgetB BtoB BitsB BdeliveryB Bpoint.B
B

BelowB BisB BanB Bexample:


B

functionB BrandomPick(array)B B{
letB BchoiceB B=B BMath.floor(Math.random()B B*B Barray.length);
returnB Barray[choice];
}

functionB BrandomRobot(state)B B{
returnB B{direction:B BrandomPick(roadGraph[state.place])};
}

IfB ByouB BwantB BtoB BtestB BthisB BuniqueB Brobot,B BcreateB BaB BnewB BstateB BwithB
fewB Bparcels.
B

VillageState.randomB B=B Bfunction(parcelCountB B=B B5)B B{


letB BparcelsB B=B B[];
forB B(letB BiB B=B B0;B BiB B<B BparcelCount;B Bi++)B B{
letB BaddressB B=B BrandomPick(Object.keys(roadGraph));
letB Bplace;
doB B{
placeB B=B BrandomPick(Object.keys(roadGraph));
}B BwhileB B(placeB B==B Baddress);
parcels.push({place,B Baddress});
}

returnB BnewB BVillageState("PostB BOffice",B Bparcels);


};

TheB BdoB BloopB BcontinuesB BtoB BselectB BnewB BplacesB BwhenB BitB BgetsB BaB
BcorrectB Baddress.
Let’sB BstartB BupB BaB BvirtualB Bworld.
runRobot(VillageState.random(),B BrandomRobot);
//B B→B BAdvancesB BtoB BMarketplace
//B B→B BAdvancesB BtoB BTownB BHall
//B B→…
//B B→B BRunB BinB B63B Bturns
ItB BtakesB BtheB BrobotB BtooB BmanyB BturnsB BtoB BtransportB BtheB BparcelsB
BbecauseB BthereB BwasB BnoB BplanB Bahead.
TheB BmailB Btruck'sB Broute
IfB ByouB BsearchB BaB BrouteB BthatB BgoesB BthroughB BallB BtheB BplacesB BinB BtheB
Bvillage,B BthatB BcouldB BrunB BtwiceB BbyB BtheB Brobot,B BbutB BthereB BisB BaB
BguaranteeB BitB BwillB BrunB Bit.B BBelowB BisB BanB Bexample:
(startingB BfromB BtheB BpostB Boffice):
constB BmailRouteB B=B B[
"Alice'sB BHouse,"B B"Cabin,"B B"Alice'sB BHouse,"B B"Bob'sB BHouse,"
"TownB BHall,"B B"Daria'sB BHouse,"B B"Ernie'sB BHouse,"
"Grete'sB BHouse",B B"Shop",B B"Grete'sB BHouse",B B"Farm",
"Marketplace,"B B"PostB BOffice"
];

ToB BuseB BtheB Broute,B ByouB BneedB BtoB ButilizeB BtheB BrobotB Bmemory.B BTheB
BrestB BofB BtheB BrobotB BrouteB BisB BstoredB BinB BitsB BmemoryB BandB BdispatchesB
BtheB BfirstB BelementB BatB BeveryB Bturn.
functionB BrouteRobot(state,B Bmemory)B B{
ifB B(memory.lengthB B==B B0)B B{
memoryB B=B BmailRoutes;
}

returnB B{direction:B Bmemory[0],B Bmemory:B Bmemory.slice(01)};


}

TheB BrobotB BisB BfasterB Bnow.B BItB BtakesB BaB BmaximumB BofB B26B BturnsB B(twiceB
BtheB B13-stepB Broute)B BbutB BmoreB BoftenB Bless.
Pathfinding

AnB BinterestingB BapproachB BisB BtoB BdevelopB BroutesB BfromB BtheB BstartingB
Bpoint,B BandB BinspectB BeveryB BavailableB BplaceB BthatB BhasB BnotB BbeenB BvisitedB
BuntilB BitB BattainsB BitsB Bgoal.B BTheB BbelowB BillustrationB BexplainsB Bthat:
functionB BfindRoute(graph,B Bfrom,B Bto)B B{
letB BworkB B=B B[{at:B Bfrom,B Broute:B B[]}];
forB B(letB BiB B=B B0;B BiB B<B Bwork.length;B Bi++)B B{
letB B{at,B Broute}B B=B Bwork[i];
forB B(letB BlocationB BofB Bgraph[at])B B{
ifB B(placeB B==B Bto)B BreturnB Broute.concat(location);
ifB B(!work.some(wB B=>B Bw.atB B==B Blocation))B B{
work.push({at:B Bplace,B Broute:B Broute.concat(location)});
}
}
}
}

TheB BfunctionB BsavesB BaB BworkB Blist.B BThisB BisB BanB BarrayB BofB BplacesB BthatB
willB BbeB BinspectedB Bnext,B BtogetherB BwithB BtheB Broute.B BItB BbeginsB BwithB BanB
B

emptyB BrouteB BandB BtheB BstartB Bposition.B BEveryB BlocationB BcanB BbeB
B

touchedB BfromB BeveryB Blocation,B BaB BrouteB BcanB BalsoB BbeB BfoundB BbetweenB
B

twoB BpointsB BthereforeB BtheB BrouteB BwillB BnotB Bfail.


B

functionB BgoalOrientedRobot({location,B Bparcel},B Broutes)B B{


ifB B(route.lengthB B==B B0)B B{
letB BparcelB B=B Bparcel[0];
ifB B(parcel.locationB B!=B Bplace)B B{
routeB B=B BfindRoute(roadGraph,B Blocation,B Bparcel.place);
}B BelseB B{
routeB B=B BfindRoute(roadGrap
h,B Blocation,B Bparcel.address);
}
}

returnB B{direction:B Broutes[0],B Bmemory:B Broute.slice(1)};


}
Summary

InB BthisB BchapterB BweB BtouchedB BonB BrobotsB BusingB BJavaScript.B BWeB BgotB BtoB
theB BMeadowB BfieldB BvillageB BwhereB BweB BtalkedB BaboutB BaB BvillageB BwithB
B

11B BplacesB BandB B14B Broads,B BthenB BweB BmovedB BtoB BtheB BPersistentB Bdata,B
B

wherebyB BDataB BstructuresB BbehaveB BlikeB BstringsB BandB BdoB BnotB Bchange.B
B

SimulationB BenablesB ByouB BtoB BpassB BmemoryB BtoB BrobotsB BandB BletB BthemB
B

toB BsendB BbackB BaB BnewB Bmemory.


B
Exercise

WriteB BaB BstraightforwardB BJavaScriptB BprogramB BtoB BconnectB BeveryB


elementB BinB BtheB BbelowB BarrayB BintoB BaB Bstring.
B

"Red,B BGreen,B BWhite,B BBlack"


"Red,B BGreen,B BWhite,B BBlack"
"Red+Green+White+Black"
Solution

BB
Chapter 9: Bugs and Errors
BB BB BB BB

ComputerB BprogramB BflawsB BareB BcalledB Bbugs,B BtheB BmistakesB BmadeB BbyB BaB
computerB Bprogram.
B

StrictB Bmode
YouB BcanB ButilizeB BJavaScriptB BinB BaB BstrictB Bmode.B BThisB BcanB BbeB BachievedB
byB BaddingB BtheB BstringB B"useB Bstrict"B BrightB BatB BtheB BtopB BofB BaB Bfile.B
B

BelowB BisB BanB Billustration:


B

functionB BcanYouSpotTheProblem()B B{
"useB Bstrict";
forB B(counterB B=B B0;B BcounterB B<B B10;B Bcounter++)B B{
console.log("HappyB Bhappy");
}
}
canYouSpotTheProblem();

//B B→B BReferenceError:B BcounterB BisB BnotB Bdefined


UseB BtheB BbelowB BcodeB BwhenB ByouB BwantB BtoB BcallB BaB BconstructorB BfunctionB
omittingB BtheB BnewB BkeywordB BsoB BitB Bdoesn’tB BintroduceB BaB BnewlyB
B

createdB Bobject:
B

functionB BPerson(name)B B{this.nameB B=B Bname;}


letB BFerdinandB B=B BPerson("Ferdinand");B B//B Boops
console.log(name);

//B B→B BFerdinand


TheB BfakeB BcallB BtoB BPersonB BflourishedB BbutB BsendsB BbackB BanB BundefinedB
valueB BandB BbuiltsB BtheB BglobalB BbindingB Bname.B BInB BstrictB Bmode,B BuseB
B
B"useB Bstrict";
functionB BPerson(name)B B{this.nameB B=B Bname;}
letB BFerdinandB B=B BPerson("Ferdinand");B B//B BforgotB Bnew
//B B→B BTypeError:B BCannotB BsetB BpropertyB B'name'B BofB Bundefined
TheB BquicklyB BindicatesB BthatB BweB BhaveB BaB Bproblem.B BThat'sB Bgood.B
BConstructorsB BbuiltB BwithB BtheB BclassB BnotationB BregularlyB BcomplainsB
BwhenB ByouB BcallB BthemB BwithoutB BtheB Bnew.B BStrictB BmodeB BdoesB BnotB BallowB
BsettingB BfunctionB BmultipleB BcharactersB BwithB BsimilarB BnameB BandB
BeradicatesB BsomeB BlanguageB Bproblems.
Testing

YouB BcanB BuseB BthisB BfunctionB BtoB BsearchB BforB BmistakesB BinB BaB Bprogram.B BItB
BisB BachievedB BbyB BrunningB BoverB BandB BoverB Bagain.B BTheB BcomputerB BisB
BexcellentB BinB BrepetitiveB Btasks.B BThisB BprocessB BisB BcalledB BAutomatedB
Btesting.B BItB BentailsB BwritingB BaB BprogramB BthatB BtestsB BanotherB Bprogram.B
BTestsB BregularlyB BgoB BthroughB BsmallB BlabeledB BprogramsB BthatB BdetermineB
BsomeB BpartB BofB ByourB Bcode.B BForB Binstance,B BletB BusB BcreateB BaB BsetB BofB BtestsB
BforB BtheB BtoUpperCaseB Bmethod.B BBelowB BisB BanB Billustration:
functionB Btest(label,B Bbody)B B{
ifB B(!body())B Bconsole.log(`Failed:B B${label}`);
}

test("convertB BLatinB BtextB BtoB Buppercase",B B()B B=>B B{


returnB B"hello".toUpperCase()B B==B B"HELLO";
});

test("convertB BGreekB BtextB BtoB Buppercase",B B()B B=>B B{


returnB B"Χαίρετε".toUpperCase()B B==B B"ΧΑΊΡΕΤΕ";
});

test("don'tB BconvertB Bcase-lessB Bcharacters",B B()B B=>B B{


returnB B"߈࠶ࢎఆ௷".toUpperCase()B B==B B"߈࠶ࢎఆ௷";
131
});
Debugging

WhenB BaB BprogramB BdisplaysB BanB Berror,B BtheB BnextB BthingB BisB BtoB
BdetermineB BtheB BproblemB BandB BgetB BitB Bfixed.B BTheB BerrorB BmessageB BwillB
BpointB BdirectlyB BatB BaB BparticularB BlineB BinB ByourB BblockB BofB Bcode.B BTakeB BaB
BlookB BatB BtheB BerrorB Bdescription,B BandB ByouB BwillB BfindB BtheB BproblematicB
Bline.B BThisB BexampleB BprogramB BtriesB BtoB BtransformB BaB BwholeB BnumberB
BintoB BaB BstringB BwithinB BsetB BbaseB B(decimal,B Bbinary,B BandB BsoB Bon)B BbyB
BcontinuouslyB BselectingB BoutB BtheB BlastB BdigitB BandB BdividingB BtheB BnumberB
BtoB BeradicateB BtheB Bdigit.
functionB BnumberToString(n,B BbaseB B=B B10)B B{
letB BresultB B=B B"",B BsignB B=B B"";
ifB B(nB B<B B0)B B{
signB B=B B"-";
nB B=B B-n;
}

doB B{
resultB B=B BString(nB B%B Bbase)B B+B Bresult;
nB B/=B Bbase;
}B BwhileB B(nB B>B B0);
returnB BsignB B+B Bresult;
}

console.log(numberToString(13,B B10));
//B B→B B1.5e-3231.3e-3221.3e-3211.3e-3201.3e-3191.3e…-3181.3
AddingB BsomeB Bconsole.logB BcallsB BintoB BtheB BprogramB BisB BanB BexcellentB
pathB BtoB BtakeB BifB ByouB BwantB BtoB BacquireB BadditionalB BinformationB BaboutB
B

theB Bexecution.B BWeB BwantB BnB BtoB BgetB BtheB BvaluesB B13,B B1,B BandB BthenB B0.B
B

WeB BshouldB BstateB BtheB BvalueB BatB BtheB BbeginningB BofB BtheB Bloop'
B

13
1.3
0.13
0.013…
1.5e-323

DividingB B13B BbyB BwillB BnotB BprovideB BaB BwholeB Bnumber.B BInsteadB BofB BnB B/=B
base,B BwhatB BweB BwantB BisB BnB B=B BMath.floor(nB B/B Bbase)B BsoB BthatB BtheB
B

numberB BcanB BbeB B“shifted”B BtoB BtheB Bright.


B

AnotherB BgreatB BwayB BtoB BspecifyB BaB BbreakpointB BisB BtoB BinsertB BaB BdebuggerB
statementB B(keyword)B BintoB ByourB Bprogram.B BIfB BtheB BdeveloperB BtoolsB
B

willB BpickB BitB BupB BandB BpauseB BtheB BprogramB BanytimeB BitB BgetsB BtoB BthatB
B

statementB BifB ByourB BbrowserB BisB Bactive.


B

Exceptions

WhenB BaB BfunctionB BisB BcannotB BgoB Bfurther,B BtheB BexceptionB BhandlingB BisB
theB BplaceB BthatB BunderstandsB BhowB BtoB BfixB BthatB Bproblem.B BExceptionsB
B

areB BaB BtoolB BthatB BenablesB BaB BblockB BofB BcodeB BthatB BrunsB BintoB BdifficultiesB
B

toB BthrowB BanB Bexception,B BandB BanB BexceptionB BcouldB BbeB BanyB Bvalue.B
B

YouB BcanB BintentionallyB BcreateB BproblemsB BwithinB ByourB BlineB BofB BcodeB
B

toB BcatchB BtheB BexceptionB BduringB BitsB BzoomingB BdownB BtheB BprocessB BsoB
B

thatB ByouB BcanB BuseB BitB BtoB BsolveB BtheB BproblemB BandB BcontinueB ByourB
B

work.
B

Here’sB BanB Bexample:


functionB BpromptDirection(question)B B{
letB BresultB B=B Bprompt(question);
ifB B(result.toLowerCase()B B==B B"left")B BreturnB B"L";
ifB B(result.toLowerCase()B B==B B"right")B BreturnB B"R";
throwB BnewB BError("InvalidB Bdirection:B B"B B+B Bresult);
}

functionB Blook()B B{
ifB B(promptDirection("WhichB Bway?")B B==B B"L")B B{
returnB B"aB Bhouse";
}B BelseB B{
returnB B"twoB BangryB Bbears";
135
}
}

tryB B{
console.log("YouB Bsee",B Blook());
}B BcatchB B(error)B B{
console.log("SomethingB BwentB Bwrong:B B"B B+B Berror);
}

RaiseB BanB BexceptionB BbyB BusingB BtheB BthrowB Bkeyword.


CleaningB BupB BafterB Bexceptions
AnB Bexception’sB BeffectB BisB BaB BdifferentB BtypeB BofB BcontrolB Bflow.B BThisB
indicatesB BthatB ByourB BcodeB BcanB BhaveB BdifferentB BsideB Beffects,B BbutB BanB
B

exceptionB BcouldB BstopB BthemB BfromB Bhappening.B BBelowB BisB BsomeB BbadB
B

bankingB Bcode:
B

constB BaccountsB B=B B{


a:B B100,
b:B B0,
c:B B20
};

functionB BgetAccount()B B{
letB BaccountNameB B=B Bprompt("EnterB BanB BaccountB Bname");
ifB B(!accounts.hasOwnProperty(accountName))B B{
throwB BnewB BError(`NoB BsuchB Baccount:B B${accountName}`);
}

returnB BaccountName;
}

functionB Btransfer(from,B Bamount)B B{


ifB B(accounts[from]B B<B Bamount)B Breturn;
accounts[from]B B-=B Bamount;
accounts[getAccount()]B B+=B Bamount;
}

TheB BtransferB BfunctionB BisB BusedB BtoB BsendB BaB BparticularB BsumB BofB BmoneyB
BfromB BaB BstatedB BaccountB BtoB Banother,B BasB BwellB BasB BdemandingB BforB BtheB
BnameB BofB BtheB BotherB Baccount.B BIfB ByouB BinputB BaB BwrongB BaccountB Bname,B
BgetAccountB BoutputsB BanB Bexception.B BIfB BtheB BmoneyB BhasB BbeenB BsentB
BfromB BtheB BfirstB BaccountB BandB BthenB BtheB BprogramB BoutputsB BanB
BexceptionB BbeforeB BitB BgetsB BtheB BmoneyB BtransferredB BintoB BtheB BotherB
Baccount,B BtheB BmoneyB BwillB Bdisappear.B BSolveB BthisB Bproblem,B ButilizeB BtheB
BfinallyB BblockB Bcode.B BThisB BisB BillustratedB Bbelow:

functionB Btransfer(from,B Bamount)B B{


ifB B(accounts[from]B B<B Bamount)B Breturn;
letB BprogressB B=B B0;
tryB B{
accounts[from]B B-=B Bamount;
progressB B=B B1;
accounts[getAccount()]B B+=B Bamount;
progressB B=B B2;
}B BfinallyB B{
ifB B(progressB B==B B1)B B{
accounts[from]B B+=B Bamount;
}
}
}

SelectiveB Bcatching
WhenB BanB BexceptionB BmakesB BitB BtoB BtheB BbottomB BofB BaB BblockB BofB BcodeB
BwithoutB Berrors,B BitB BisB BhandledB BbyB BtheB Benvironment.B BInvalidB BusesB

suchB BasB BinspectingB BupB BaB BpropertyB BonB Bnull,B BcitingB BaB BnonexistentB
B

binding,B BorB BcallingB BaB Bnon-functionB BwillB BresultB BinB BraisedB Bexceptions.B
B

TheseB BexceptionsB BcanB BbeB Bcaught.B BJavaScriptB BdoesB BnotB BsupportB


B

selectiveB BcatchingB BofB Bexceptions.B BBelowB BisB BanB BexampleB BthatB BtriesB
B

toB BcontinueB BcallingB BpromptDirectionB BuntilB BitB BprovidesB BaB BvalidB


B

answer:
B

forB B(;;)B B{
tryB B{
letB BdirB B=B BpromtDirection("Where?");B B//B B←B Btypo!
console.log("YouB BselectB B",B Bdir);
break;

}B BcatchB B(e)B B{
console.log("InvalidB Bdirection.B BTryB Bagain.");
}
}

TheB BforB B(;;)B BconstructB BisB BusedB BtoB BbuildB BaB BloopB BthatB BcannotB BbeB
BterminatedB BonB BitsB Bown.B BYouB BcanB BbreakB BoutB BofB BtheB BloopB BwhenB ByouB

haveB BaB BvalidB Bdirection,B BbutB BaB BmisspelledB BpromptDirectionB BwillB


B

outputB BanB BundefinedB BvariableB Berror.B BIfB ByouB BwantB BtoB BcatchB BaB
B

particularB BtypeB BofB Bexception,B BcheckB BinB BtheB BcatchB BblockB BifB BtheB
B

exceptionB ByouB BhaveB BisB BtheB BsameB BoneB ByouB BwantB BandB BrethrowB Bit.B
B

Let’sB BdescribeB BaB BnewB BkindB BofB BerrorB BandB ButilizeB BinstanceB BofB BtoB
B

recognizeB Bit.
B

classB BInputErrorB BextendsB BErrorB B{}


functionB BpromptDirection(question)B B{
letB BresultB B=B Bprompt(question);
ifB B(result.toLowerCase()B B==B B"left")B BreturnB B"L";
ifB B(result.toLowerCase()B B==B B"right")B BreturnB B"R";
throwB BnewB BInputError("InvalidB Bdirection:B B"B B+B Bresult);
}

TheB BnewB BerrorB BclassB BprolongsB Berror.B BItB BdoesB BnotB BdescribeB BitsB BownB
constructor,B BitB BinheritsB BtheB BErrorB Bconstructor,B BwhichB BanticipatesB BaB
B

stringB BmessageB BthatB BweB BcanB BrecognizeB BitB Bwith.


B

NowB BtheB BloopB BcanB BcatchB BtheseB BmoreB Bcarefully.


forB B(;;)B B{
tryB B{
letB BdirB B=B BpromptDirection("Where?");
console.log("YouB BchoseB B",B Bdir);
break;

}B BcatchB B(e)B B{
ifB B(eB BinstanceofB BInputError)B B{
console.log("InvalidB Bdirection.B BTryB Bagain.");
}B BelseB B{
throwB Be;
}
}
}
Summary

ThisB BchapterB BdealsB BwithB Bdebugging.B BAnB BessentialB BpartB BofB


programmingB BisB BidentifyingB BandB BfixingB Bbugs.B BSometimes,B ByouB BcanB
B

solveB BproblemsB Blocally.B BYouB BcanB BtrackB BthemB BwithB BspecialB BreturnB
B

valuesB BorB BtheB BuseB BofB Bexceptions.


B

Exercise

FixB BtheB BbelowB BbrokenB BcodeB BandB BindicateB BtheB Bproblem:


for(varB BI=0;B BIB B>B B5;B BI++){
console.log(i)
}
Solution

ProblemB B–B BIncorrectB BconditionB BwithinB BtheB Bloop.


Chapter 10: Regular Expressions
BB BB BB

ProgrammingB BconceptsB BandB BtoolsB BadvancesB BinB BaB BdisorganizedB Bway,B


butB BitsB BsuccessB BindicatesB BanB BexcellentB BpieceB BofB Btechnology.B BInB BthisB
B

chapter,B BweB BwillB BdiscussB BregularB Bexpressions.B BTheyB BareB BusedB BtoB
B

defineB BpatternsB BwithinB BaB BstringB Bdata.B BTheyB BcreateB BaB Bsmall,B
B

differentB BlanguageB BthatB BconsistsB BofB BJavaScriptB BasB BwellB BasB BotherB
B

languages.
B

CreatingB BaB BregularB Bexpression


AB BregularB BexpressionB BisB BconstructedB BwithB BtheB BRegExpB BconstructorB
orB BwrittenB BasB BaB BstrictB BvalueB BbyB BsurroundingB BaB BpatternB BinB Bforward-
B

slashB B(/)B Bcharacters.


letB Bre1B B=B BnewB BRegExp("ABC");
letB Bre2B B=B B/ABC/;
TheseB BtwoB BregularB BexpressionB BobjectsB BstandB BforB BtheB BsameB Bpattern.B
WhenB ButilizingB BtheB BRegExpB Bconstructor,B BwriteB BtheB BpatternB BasB BaB
B

normalB BstringB BsoB BthatB BtheB BrulesB BapplyB BforB Bbackslashes.


B

TheB BsecondB BnotationB BinfluenceB BbackslashesB Bdifferently,B BfirstB BputB BaB


backslashB BbeforeB BanyB BforwardB BslashB BbecauseB BtheB BpatternB BdisplaysB
B

betweenB BslashB Bcharacters.


B

TestingB BforB Bmatches


RegularB BexpressionB BobjectsB BcontainB BseveralB Bmethods,B BoneB BofB BwhichB
isB BtheB Btest.B BWhenB ByouB BpassB BaB Bstring,B BitB BreturnsB BaB BBooleanB
B

determiningB BifB BaB BstringB BcontainsB BaB BmatchB BofB BtheB BpatternB BinB BtheB
B

expression.
B

console.log(/abc/.test("abcde"));
//B B→B Btrue
console.log(/abc/.test("abxde"));

//B B→B Bfalse


AB BregularB BexpressionB BcontainsB BonlyB Bnon-specialB BcharactersB BthatB
representB BtheB BsuccessionB BofB Bcharacters.B BIfB BABCB BpapersB BanywhereB BinB
B

theB Bstring,B BweB BareB BrunningB BaB Btest,B BtheB BtestB BwillB BreturnB Btrue.
B

Sets of characters
BB BB

RegularB BexpressionsB BenableB BusB BtoB BindicateB BdifficultB Bpatterns.B BIfB ByouB
wantB BtoB BequalB BanyB BnumberB BinB BaB BregularB Bexpression,B BplaceB BaB BsetB
B

ofB
B charactersB
B Bin-betweenB BsquareB Bbrackets.B BTheB followingB
B

expressionsB BequalB BeveryB BstringB BwithinB BaB Bdigit:


B

console.log(/[0123456789]/.test("inB B1992"));
//B B→B Btrue
console.log(/[0-9]/.test("inB B1992"));
//B B→B Btrue
AB BhyphenB B(-)B BbetweenB BtwoB BcharactersB BinsideB BsquareB BbracketsB BisB
usedB BtoB BspecifyB BaB BscopeB BofB BcharactersB BthatB BtheB Bcharacter’sB
B

UnicodeB BnumbersB BdecideB BtheB Bcommand.B BCharactersB BfromB B0B BtoB B9B
B

stayB BnextB BtoB BeachB BotherB BinB BthisB BcommandB B(codesB B48B BtoB B57),B BsoB B[0-
B

9]B BwrappingB BthemB BallB BandB BequalsB BanyB Bdigit.B BCommonB BcharacterB
groupsB BcontainB BindividualB BshortcutsB Bbuilt-in.
B

DigitsB BareB BpartB BofB Bthem:B B\dB BmeansB BtheB BexactB BthingB BasB B[0-9].
\dB BAnyB BcharacterB Bdigit
\wB BanB BalphanumericB BcharacterB B(“wordB Bcharacter”)
\sB BAnyB BwhitespaceB BcharacterB B(space,B Btabs,B Bnewline,B BandB Bsimilar)
\DB BAB BcharacterB BwhichB BisB BnotB BaB Bdigit
\WB BAB BnonalphanumericB Bcharacter
\SB BAB BnonwhitespaceB Bcharacter
.B BAnyB BcharacterB BwithoutB BforB Bnewline
So,B BmatchB BaB BdateB BandB BtimeB BformatB BlikeB B01-30-2003B B15:20B BwithB BtheB
expressionB Bbelow:
B

letB BdateTimeB B=B B/\d\d-\d\d-\d\d\d\dB B\d\d:\d\d/;


console.log(dateTime.test("01-30-2003B B15:20"));
//B B→B Btrue
console.log(dateTime.test("30-jan-2003B B15:20"));
//B B→B Bfalse
TheseB BbackslashB BcodesB BareB BalsoB ButilizedB BwithinB BtheB BsquareB Bbrackets.B
ForB Binstance,B B[\d.]B BindicatesB BanyB BdigitB BorB BperiodicB BcharacterB BbutB
B

theB BperiodB BhasB BnoB BmeaningB BasB BwellB BasB BotherB BuniqueB Bcharacters,B
B

likeB B+.
B

letB BnotBinaryB B=B B/[^01]/;


console.log(notBinary.test("1100100010100110"));

//B B→B Bfalse


console.log(notBinary.test("1100100010200110"));

//B B→B Btrue


RepeatingB BpartsB BofB BaB Bpattern
NowB ByouB BhaveB BaB BperfectB BunderstandingB BofB BhowB BtoB BequalB BsingleB
digits.B BIfB ByouB BwantB BtoB BmatchB BaB BwholeB BnumberB BorB BaB BsuccessionB BofB
B

moreB Bdigits,B BplaceB BaB BplusB BsignB B(+)B BimmediatelyB BafterB BanB BinputB BinB
B

aB BregularB Bexpression.B BThisB BsignifiesB BthatB BtheB BelementB BcouldB BrepeatB


B

moreB BthanB Bonce,B B/\d+/B BequalsB BoneB BorB Bmore-digitB Bcharacters.


B

console.log(/'\d+'/.test("'123'"));
//B B→B Btrue
console.log(/'\d+'/.test("''"));

//B B→B Bfalse


console.log(/'\d*'/.test("'123'"));

//B B→B Btrue


console.log(/'\d*'/.test("''"));

//B B→B Btrue


TheB BstarB B(*)B BenablesB BtheB BpatternB BtoB BequalB Bzero.B BInB BtheB BbelowB
example,B BtheB BuB BcharacterB BisB BpermittedB BtoB Brise,B BbutB BtheB BpatternB BisB
B

alsoB BequalB BwhenB BitB BisB BnotB Bfound.


B

letB BneighborB B=B B/neighbour/;


console.log(neighbor.test("neighbour"));

//B B→B Btrue


console.log(neighbor.test("neighbor"));

//B B→B Btrue


ToB BdetermineB BifB BaB BpatternB BshouldB BexecuteB BaB BcertainB BnumberB BofB
times,B ButilizeB BtheB Bbraces,B BinsertingB B{4}B BafterB BanB Belement.B BIfB ByouB
B

wantB BitB BtoB BexecuteB BpreciselyB BfourB Btimes,B BdefineB BaB BrangeB BlikeB Bthis:
B

{2,4}B BsignifiesB BthatB BtheB BelementB BmustB BexecuteB BtwiceB BandB BatB BmostB
fourB Btimes.B BBelowB BisB BanotherB BpatternB BofB BtheB BdateB BandB BtimeB
B

pattern,B BwhichB BenablesB BbothB BsingleB BandB Bdouble-digitB Bdays,B BmonthsB


B

andB Bhours.
B

letB BdateTimeB B=B B/\d{01,2}-\d{1,2}-\d{4}B B\d{1,2}:\d{2}/;


console.log(dateTime.test("01-30-2003B B8:45"));
//B B→B Btrue
GroupingB Bsubexpressions
IfB ByouB BwantB BtoB BUtilizeB BanB BoperatorB BlikeB B*B BorB B+B BonB BoneB BorB BmoreB
elementB Bconcurrently,B BuseB BtheB Bparentheses.B BSomeB BpartsB BofB BaB
B

regularB Bexpression,B BwhichB BisB BcitedB BinB Bparentheses,B BcountsB BasB BanB
B

individualB BelementB BasB BlongB BasB BtheB BoperatorsB BareB Bconcerned.


B

letB BcartoonCryingB B=B B/boo+(hoo+)+/i;


console.log(cartoonCrying.test("Boohoooohoohooo"));

//B B→B Btrue


TheB BfirstB BandB BsecondB B+B BcharactersB BonlyB BapplyB BtoB BtheB BsecondB BinB
booB BandB Bhoo.B BTheB BthirdB B+B BindicatesB BtoB BtheB BentireB BgroupB B(hoo+),B
B

equalingB BoneB BorB BmoreB BsuccessionsB BlikeB Bthat.B BTheB BIB BendingB BtheB
B

firstB BexpressionB BinB BtheB BexampleB BisB BusedB BforB BcaseB Binsensitive,B
B

enablingB BitB BtoB BequalB BtheB BuppercaseB BBB BinB BtheB BinputB Bstring.B
B

AlthoughB BtheB BpatternB BisB BentirelyB Blowercase.


B

MatchesB BandB Bgroups


TheB BtestB BmethodB BisB BtheB BbestB BwayB BtoB BequalB BaB BregularB Bexpression,B BitB
determinesB BifB BitB BmatchesB Bonly.B BRegularB BexpressionsB BcontainB BanB
B

execB B(execute)B Bmethod,B BwhichB BwillB BoutputB BnullB BifB BitB BcouldB BfindB BaB
B

matchB BandB BsendsB BbackB BanB BobjectB BcontainingB BdataB BaboutB BtheB Bmatch.
B

letB BmatchB B=B B/\d+/.exec("oneB BtwoB B100");


console.log(match);

//B B→B B["100"]


console.log(match.index);

//B B→B B8
AB BsentB BbackB BobjectB BfromB BexecB BcontainsB BanB BindexB Bproperty,B BwhichB
determineB BwhatB BpartB BofB BtheB BstringB BtheB BthrivingB BmatchB Bstarts.B
B

BelowB BisB BtheB BsuccessionB BofB BdigitsB Bneeded:


B

StringB BvaluesB BcontainB BaB BmatchB BmethodB BthatB BbehavesB Bsimilarly.


console.log("oneB BtwoB B100".match(/\d+/));
//B B→B B["100"]
WhenB BtheB BregularB BexpressionB BholdsB BsubexpressionsB BcollatedB BwithB
parentheses,B BtheB BmatchingB BtextB BwillB BdisplayB BinB BtheB Barray.B BTheB
B

wholeB BmatchB BisB BtheB Bfirst,B BtheB BnextB BisB BtheB BmatchedB BpartB BbyB BtheB
B

firstB Bgroup,B BandB BthenB BtheB BfollowingB Bgroup,B Betc.


B

letB BquotedTextB B=B B/'([^']*)'/;


console.log(quotedText.exec("sheB BsaidB B'hello'"));
//B B→B B["'hello'",B B"hello"]
WhenB BaB BgroupB BwasB BnotB BfinishB BbeingB BmatchedB B(ifB BitB BcontainsB BaB
questionB Bmark),B BitB BoutputsB Bundefined.B BWhenB ByouB BmatchB BaB BgroupB
B

severalB Btimes,B BonlyB BtheB BlastB BmatchB BfinishesB BinB BtheB Barray.
B

console.log(/bad(ly)?/.exec("bad"));

//B B→B B["bad",B Bundefined]


console.log(/(\d)+/.exec("123"));

//B B→B B["123",B B"3"]


TheB BDateB Bclasses
JavaScriptB BconsistsB BofB BaB BstandardB BclassB BthatB BrepresentB Bdates;B BitB BisB
calledB BDate.B BIfB ByouB BwantB BtoB BbuildB BaB BdateB BobjectB ButilizingB Bnew,B
B

firstB BgetB BtheB BcurrentB BtimeB BandB Bdate.


B

console.log(newB BDate());
//B B→B BMonB BNovB B11B B2023B B16:19:11B BGMT+0100B B(CET)
YouB BcanB BasB BwellB BBuildB BanB BobjectB BforB BaB BparticularB Btime.
console.log(newB BDate(2008,B B11,B B8));
//B B→B BWedB BDecB B08B B2008B B00:00:00B BGMT+0100B B(CET)
console.log(newB BDate(2008,B B11,B B9,B B12,B B59,B B59,B B999));
//B B→B BWedB BDecB B08B B2009B B12:59:59B BGMT+0100B B(CET)
YouB BshouldB BfollowB BtheB BJavaScriptB BdateB BnamingB BconventionB BwhereB
monthB BnumbersB BbeginB BatB BzeroB B(therefore,B BDecemberB BisB B11),B BandB
B

dayB BnumbersB BbeginB BatB B1.


B

TheB Bhours,B Bminutes,B Bseconds,B BandB BmillisecondsB BargumentsB BareB


voluntaryB BandB BrecognizedB BasB BzeroB BwhenB BnotB Bspecified.B BTimestampsB
B

areB BsavedB BasB BtheB BnumberB BofB BmillisecondsB BinB BtheB BUTCB BtimeB Bzone.B
B

FollowingB BbyB BaB BconventionB BsetB BbyB B“UnixB Btime”.


B

console.log(newB BDate(2016,B B11,B B14).getTimes());


//B B→B B1445677600000
console.log(newB BDate(1445677600000));
//B B→MonB BDecB B11B B2008B B00:01:00B BGMT+0100B B(CET)
WhenB BtheB BDateB BconstructorB BisB BsetB BaB BsingleB Bargument,B BtheB
argumentB BisB BrecognizedB BasB BaB BmillisecondB Bcount.B BDetermineB BtheB
B

currentB BmillisecondB BcountB BbyB BbuildingB BaB BnewB BDateB BobjectB BandB BcallB
B

getTimeB BonB BitB BorB BuseB BtheB BDate.nowB Bfunction.B BDateB BobjectsB BproduceB
B

BmethodsB BsuchB BlikeB BgetDate,B BgetHours,B BgetFullYear,B BgetMonth,B


BgetMinutes,B BandB BgetSecondsB BtoB BretrieveB BtheirB Bcomponents.

functionB BgetDate(strings)B B{
letB B[_,B Bmonth,B Bday,B Byear]B B=
/(\d{01,2})-(\d{01,2})-(\d{4})/.exec(strings);

returnB BtheB BnewB BDate(year,B BmonthB B-B B1,B Bday);


}
console.log(getDate("1-30-2003"));

//B B→B BThursdayB BJanB B30B B2003B B00:00:00B BGMT+0100B B(CET)


String and Word boundaries
BB BB BB
YouB BcanB BensureB BthatB BtheB BmatchB BspansB BtheB BentireB BstringB BbyB BaddingB
theB BmarkersB B^B BandB B$.B BTheB BcaretB BequalsB BtheB BbeginningB BofB BtheB
B

inputB Bstring,B BwhileB BtheB BdollarB BsignB BequalsB BtheB Bend.B BTherefore,B
B

/^\d+$/B BmatchesB BaB BstringB BcontinuingB BmultipleB BorB BoneB Bdigits,B B/^!B B/B
B

matchesB BanyB BstringB BthatB BbeginsB BwithB BanB BexclamationB Bmark,B BandB
B

/x^/B BmatchesB BnoB Bstring.B BIfB ByouB BwantB BtheB BdateB BtoB BbeginB BandB BendB
B

onB BaB BboundaryB Bword,B ButilizeB BtheB BmarkerB B\b.B BAB BwordB BboundaryB
B

canB BbeginB BorB BfinishB BstringsB BcontainingB BaB BwordB BcharacterB B(\w)B BonB
B

oneB BsideB BandB BaB BnonwordB BcharacterB BonB BtheB Bother.


B

console.log(/cat/.test("concatenate"));

//B B→B Btrue


console.log(/\bcat\b/.test("concatenate"));

//B B→B Bfalse


ChoiceB Bpatterns
IfB ByouB BwantB BtoB BknowB BifB BchunkB BofB BtextB BconsistsB BofB BaB BnumberB BandB
followedB BbyB BwordsB BsuchB BasB Bchicken,B Bpig,B BorB Bcow,B Blet’sB BwriteB BthreeB
B

regularB BexpressionsB BandB BtestB Bthem.B BWeB ButilizeB BtheB BpipeB BcharacterB
B

(|)B BtoB BmarkB BaB BchoiceB BbetweenB BtheB BpatternB BtoB BtheB BleftB BandB Bright:
B

letB BanimalCountB B=B B/\b\d+B B(pig|cows|chicken)s?\b/;


console.log(animalCount.test("15B Bpigs"));
150

//B B→B Btrue


console.log(animalCount.test("15B Bpigchickens"));
//B B→B Bfalse
TheB BreplaceB Bmethod
StringB BvaluesB BcontainsB BaB BreplaceB Bmethod,B BwhichB BisB BusedB BtoB BrestoreB
partB BofB BtheB BstringB BwithB BanotherB Bone.
B
console.log("papa".replace("p",B B"m"));
//B B→B Bmapa
TheB BfirstB BargumentB BcanB BequallyB BbeB BaB BregularB Bexpression.B BItB
replacesB BtheB BfirstB BmatchB BofB BtheB BregularB Bexpression.B BIfB ByouB BaddB BaB
B

gB BoptionB B(forB Bglobal)B BtoB BtheB Bexpression,B BeveryB BmatchB BcontainedB BinB
B

theB BstringB BisB Breplaced,B BandB BnotB BfirstB Bonly.


B

console.log("Borobudur".replace(/[ou]/,B B"a"));
//B B→B BBarobudur
console.log("Borobudur".replace(/[ou]/g,B B"a"));
//B B→B BBarabadar
TheB BmajorB BimportanceB BofB ButilizingB BregularB BexpressionsB BwithB BreplaceB
isB BbecauseB BitB BrefersB BtoB BmatchedB BgroupsB BinB BtheB BreplacementB Bstring.B
B

ForB Binstance,B ByouB BhaveB BaB BlargeB BstringB BconsistingB BofB Bpeople'sB Bname,B
B

oneB BnameB BperB Bline,B BusingB BtheB BformatB BLastname,B BFirstname.B BYouB
B

canB BasB BwellB BchangeB BandB BremoveB BtheseB Bnames,B BeradicateB BtheB
B

commaB BtoB BgetB BaB BFirstnameB BLastnameB Bformat,B BandB ButilizeB BtheB
B

followingB Bcode:
B

console.log(

"Liskov,B BBarbara\nMcCarthy,B BJohn\nWadler,B BPhilip"


.replace(/(\w+),B B(\w+)/g,B B"$2B B$1"));
//B B→B BBarbaraB BLiskov
//B BJohnB BMcCarthy
//B BPhilipB BOaks
TheB B$1B BandB B$2B BcontainedB BinB BtheB BreplacementB BstringB BreferB BtoB BtheB
groupB BinB BparenthesesB BinB Bpattern.B B$1B BisB BrestoredB BbyB BtheB Btext,B
B

whichB BmatchesB BopposingB BtheB BfirstB Bgroup,B B$2B BupB BtoB B$9.B BEachB BandB
B
everyB BmatchB BcanB BbeB BreferredB BtoB BwithB B$&.B BYouB BcanB BpassB BaB
B

functionB BinsteadB BofB BaB BstringB BasB BtheB BsecondB BargumentB BtoB Brestore.B
B

ForB BeachB Breplacement,B BtheB BfunctionB BisB BcalledB BwithB BtheB BmatchedB
B

groupB BasB Barguments,B BandB BincludeB BtheB BreturnB BvalueB BintoB BtheB BnewB
B

string.B BBelowB BisB BanB Bexample:


B

letB BsB B=B B"theB BciaB BandB Bfbi";


console.log(s.replaces(/\b(fbi|cia)\b/g,

strB B=>B Bstr.toUpperCase()));


//B B→B BtheB BCIAB BandB BFBI
Here’sB BaB BmoreB BinterestingB Bone:
letB BstockB B=B B"1B Blemon,B B2B Bcabbages,B BandB B101B Beggs";
functionB BminusOne(match,B Bamount,B Bunits)B B{
amountB B=B BNumber(amount)B B-B B1;
ifB B(amountB B==B B1)B B{//B BJustB BoneB Bleft,B BremoveB BtheB B's'
unitB B=B Bunit.slice(0,B Bunit.lengthB B-B B1);
}B BelseB BifB B(amountB B==B B0)B B{
amountB B=B B"no";
}

returnB BamountB B+B B"B B"B B+B Bunits;


}

console.log(stock.replaces(/(\d+)B B(\w+)/g,B BminusOne));


//B B→B BnoB Blemon,B B1B Bcabbage,B BandB B100B Beggs
Greed

YouB BcanB BuseB BreplaceB BtoB BwriteB BaB BfunctionB BthatB BeradicatesB BallB
commentsB BfromB BaB BblockB BofB BJavaScriptB Bcode.B BLookB Bbelow:
B

functionB BstripComments(code)B B{
returnB Bcode.replace(/\/\/.*|\/\*[^]*\*\//g,B B"");
}

console.log(stripComments("1B B+B B/*B B2B B*/3"));


//B B→B B1B B+B B3
155

console.log(stripComments("xB B=B B10;//B Bten!"));


//B B→B BxB B=B B10;
console.log(stripComments("1B B/*B BaB B*/+/*B BbB B*/B B1"));
//B B→B B1B B1
TheB BsectionB BbeforeB BtheB BorB BoperatorB BmatchesB BtwoB BslashB BcharactersB
accompaniedB BwithB BanyB BnumberB BthatB BisB BnotB BaB BnewlineB Bcharacter.B
B

UseB B[^]B BtoB BmatchB BanyB Bcharacter.


B

RepetitiveB BOperatorsB B(+,B B*,B BandB B{})B BareB BcalledB BgreedyB BwhichB BmeansB
theyB BmatchB BandB BtheyB BcanB BalsoB Bbacktrack.B BIfB BaB BquestionB BmarkB BisB
B

placedB BafterB BthemB B(+?,B B*?,B B??,B B{}?),B BtheB BgreedB BdisappearsB BandB
B

beginB BmatchingB BnoB BmatterB BhowB Bsmall.B BTheB BsmallestB BstretchB BofB
B

charactersB BwhichB BbringsB BaB B*/,B BisB BtheB BstarB Bmatch.B BItB BabsorbsB BoneB
B

blockB BcommentB Bonly.


B

functionB BstripComments(code)B B{
returnB Bcode.replace(/\/\/.*|\/\*[^]*?\*\//g,B B"");
}

console.log(stripComments("1B B/*B BaB B*/+/*B BbB B*/B B1"));


//B B→B B1B B+B B1
Dynamically creating RegExp objects
BB BB BB

ThereB BareB BfewB BinstancesB BwherebyB ByouB BwouldB BnotB BunderstandB BtheB
specificB BpatternB ByouB BshouldB BmatchB BagainstB BwhenB ByourB BcodeB BisB
B
beingB Bwritten.B BIfB ByouB BwantB BtoB BsearchB BforB BtheB BuserB BnameB BinB BaB
B

chunkB BofB BtextB BandB BwrapB BitB BinB BunderscoreB BcharactersB BtoB BmakeB BitB
B

unique.B BButB ByouB BcanB BcreateB BaB BstringB BandB ButilizeB BtheB BRegExpB
B

constructor.B BBelowB BisB BanB Bexample:


B

letB BnameB B=B B"harry";


letB BtextB B=B B"HarryB BisB BaB BsuspiciousB Bcharacter.";
letB BregexpB B=B BnewB BRegExp("\\b("B B+B BnameB B+B B")\\b",B B"gi");
console.log(text.replace(regexp,B B"_$1_"));
//B B→B B_Harry_B BisB BaB BsuspiciousB Bcharacter.
IfB ByouB BwantB BtoB BbuildB BtheB B\bB BboundaryB Bmarkers,B ButilizeB BtheB BtwoB
backslashesB BbecauseB ByouB BwouldB BwriteB BthemB BinB BaB BnormalB Bstring.B
B

TheB BsecondB BargumentB BtoB BtheB BRegExpB BconstructorB BconsistsB BofB BtheB
B

optionsB BneededB BforB BtheB BregularB Bexpression.B BTheB B"gi"B BrepresentB


B

globalB BandB BcaseB Binsensitive.B BBelowB BisB BanB Bexample:


B

letB BnameB B=B B"dea+hl[]rd";


letB BtextB B=B B"ThisB Bdea+hl[]rdB BguyB BisB BsuperB Bannoying.";
letB BescapedB B=B Bname.replace(/[\\[.+*?(){|^$]/g,B B"\\$&");
letB BregexpB B=B BnewB BRegExp("\\b"B B+B BescapedB B+B B"\\b",B B"gi");
console.log(text.replace(regexp,B B"_$&_"));
//B B→B BThisB B_dea+hl[]rd_B BguyB BisB BveryB Bannoying.
TheB BsearchB Bmethod
YouB BcannotB BcallB BtheB BindexOfB BmethodB BonB BstringsB BaB BregularB
expression.B BYouB BcanB BalsoB BuseB BanotherB Bmethod,B BsearchB BwherebyB
B

youB BcanB BcallB BtheB BindexOfB BmethodB BaB BregularB Bexpression,B BandB BitB
B

sendsB BbackB BtheB BfirstB BindexB BwhereB BitB BseesB BtheB BexpressionB BandB
B

whenB BitB BdoesB BnotB BseeB BitB BreturnsB B-1.


B
console.log("B Bword".search(/\S/));
//B B→B B2
console.log("B B".search(/\S/));
//B B→B B-1
TheB BlastIndexB Bproperty
TheB BexecB BmethodB BdoesB BnotB BproduceB BaB BbetterB BwayB BtoB BbeginB BtheB
searchB BfromB BaB BstatedB BpositionB BinB BtheB Bstring.B BRegularB BexpressionB
B

objectsB BcontainB Bproperties.B BOneB BofB BtheB BpropertiesB BisB BcalledB Bsource,B
B

andB BitB BconsistsB BofB BtheB BstringB BthatB BbuiltB BtheB Bexpression.B BlastIndexB
B

isB BanotherB Bproperty,B BandB BitB BinfluencesB BsomeB BsmallB Bcircumstances,B


B

whereB BtheB BnextB BmatchB BwillB Bbegin.B BTheB BregularB BexpressionB BmustB
B

containB BtheB BglobalB B(g)B BorB BstickyB B(y)B Boption,B BandB BtheB BmatchB BwillB
B

occurB BusingB BtheB BexecB Bmethod.B BIllustrationB Bbelow:


B

letB BpatternB B=B B/y/g;


pattern.lastIndexB B=B B3;
letB BmatchB B=B Bpattern.exec("xyzzy");
console.log(match.index);

//B B→B B4
console.log(pattern.lastIndex);

//B B→B B5
TheB BdissimilarityB BbetweenB BtheB BglobalB BandB BtheB BstickyB BoptionsB BisB
that,B BwhenB ByouB BenableB Bsticky,B BtheB BmatchB BsucceedsB BifB BitB BbeginsB BatB
B

lastIndex,B BwhileB BwithB Bglobal,B BitB BwillB BfindB BaB BpositionB BforB BtheB BmatchB
B

canB Bbegin.
B

letB BglobalB B=B B/ABC/g;


console.log(global.exec("XYZB BABC"));
//B B→B B["ABC"]
letB BstickyB B=B B/ABC/y;
console.log(sticky.exec("XYZB BABC"));
//B B→B Bnull
IfB ByouB BareB ButilizingB BaB BsharedB BregularB BexpressionB BvalueB BforB BseveralB
execB Bcalls,B BproblemsB BwillB BoccurB BwithB BtheB BautomaticB BupdatesB BtoB BtheB
B

lastIndexB Bproperty.
B

letB BdigitB B=B B/\d/g;


console.log(digit.exec("itB BisB BhereB B:B B1"));
//B B→B B["1"]
console.log(digit.exec("andB Bnow:B B1"));
//B B→B Bnull
TheB BglobalB BoptionB BalsoB BtransformsB BtheB BconceptB BtheB BmatchB BmethodB
onB BstringsB Bworks.
B

LoopingB BoverB Bmatches


TheB BbestB BthingB BtoB BdoB BisB BtoB BscanB BacrossB BallB BeventsB BofB BaB BpatternB BinB
aB BstringB BgivingB BaccessB BtoB BtheB BmatchB BobjectB BinB BtheB BloopB Bbody.B BUseB
B

theB BlastIndexB BandB BexecB BtoB BachieveB Bthis.


B

LetB BinputB B=B B"AB BstringB BwithB BthreeB BnumbersB BinB Bit...B B42B BandB B88.";
letB BnumberB B=B B/\b\d+\b/g;
letB Bmatch;
whileB B(matchB B=B Bnumber.exec(input))B B{
console.log("Found",B Bmatch[0],B B"at",B Bmatch.index);
}

//B B→B BFoundB B3B BatB B14


//B BFoundB B42B BatB B33
//B BFoundB B88B BatB B40
TheB BassignmentB BexpressionB BvalueB B(=)B BisB BtheB BspecifiedB Bvalue.B BSoB
utilizingB BmatchB B=B Bnumber.ExecB B(input)B BasB BtheB BconditionB BwithinB BtheB
B

whileB Bstatement,B BtheB BmatchB BisB BweB BexecuteB BtheB BmatchB BatB BtheB
B

beginningB BofB BeveryB Biteration,B BstoreB BtheB BresultB BwithinB BaB Bbinding,B
B

andB BstopB BloopingB BwhenB BmatchesB BcanB BnoB BlongerB Bfind.


B

ParsingB BanB BINIB Bfile


Searchengine=https://duckduckgo.com/?q=$1
spitefulness=9.7

;B BcommentsB BareB BprecededB BbyB BaB Bsemicolon


;B BeachB BsectionB BconcernsB BanB BindividualB Benemy
[larry]

fullname=LarryB BDoe
type=kindergartenB Bbully
website=http://www.google.com/google/
[davaeorn]
fullname=Davaeorn

type=evilB Bwitch
outputdir=/home/margin/enemy/davaeorn

TheB BrulesB BforB BthisB BformatB B(whichB BisB BaB BgenerallyB BusedB Bformat,B
usuallyB Bcalled
B

anB BINIB Bfile)B Bis:


·B BIgnoreB BblankB BlinesB BandB BlinesB BbeginningB BwithB Bsemicolons.
·B BLinesB BenclosedB BinB B[and]B BbeginB BaB BnewB Bsection.
·B BLinesB BconsistingB BofB BanB BalphanumericB BidentifierB BaccompaniedB BbyB BaB
=B BcharacterB BattachB BaB BsettingB BtoB BtheB BcurrentB Bsection.
B
·B BEverythingB BelseB BisB Binvalid.
OurB BmissionB BhereB BisB BtoB BchangeB BaB BstringB BlikeB BthisB BtoB BanB Bobject,B
BwhichB BpropertiesB BuseB BstringB BtoB BstoreB BsettingsB BthatB BareB BwrittenB
BbeforeB BtheB BsubobjectsB BforB BsectionsB BandB BtheB BfirstB BsectionB Bheader.B
BTheB BsubobjectsB BholdB BthatB Bsection’sB Bsettings.B BUseB BaB BcarriageB BreturnB
BcharacterB BfollowedB BbyB BaB BnewlineB B("\r\n")B BinsteadB BofB BaB BnewlineB
BcharacterB BtoB BdifferentiateB Blines.B BThisB BwillB BmakeB BtheB BsplitB BmethodB
BenableB BaB BregularB BexpressionB BasB BitsB Bargument,B ByouB BcanB ButilizeB BaB
BregularB BexpressionB BlikeB B/\r?\n/B BtoB BdivideB BitB BinB BaB BwayB BthatB BenablesB
BbothB B"\n"B BandB B"\r\n"B BbetweenB Blines.
functionB BparseINI(string)B B{
//B BBeginB BwithB BanB BobjectB BtoB BholdB BtheB Btop-levelB Bfields
letB BresultB B=B B{};
letB BsectionB B=B Bresult;
string.split(/\r?\n/).forEach(lineB B=>B B{
letB Bmatch;
ifB B(matchB B=B Bline.match(/^(\w+)=(.*)$/))B B{
section[match[1]]B B=B Bmatch[2];
}B BelseB BifB B(matchB B=B Bline.match(/^\[(.*)\]$/))B B{
sectionB B=B Bresult[match[1]]B B=B B{};
}B BelseB BifB B(!B B/^\s*(;.*)?$/.test(line))B B{
throwB BnewB BError("LineB B'"B B+B BlineB B+B B"'B BInvalid.");
}
});

returnB Bresult;
}
console.log(parseINI(`
name=Vasilis
[address]
city=Tessaloniki`));

//B B→B B{name:B B"Vasilis",B Baddress:B B{city:B B"Tessaloniki"}}


TheB BcodeB BadvancesB BoverB BtheB BfileB BlinesB BandB BcreateB BupB BanB Bobject.B
PropertiesB BatB BtheB BtopB BareB BsavedB BstraightB BintoB BthatB Bobject,B BwherebyB
B

propertiesB BcanB BbeB BfoundB BinB BsectionsB BareB BsavedB BinB BaB BdifferentB
B

sectionB Bobject.B BTheB BsectionB BbindingB BpointsB BtoB BtheB BobjectB BforB BtheB
B

existingB Bsection.B BThereB BareB BtwoB BtypesB BofB BimportantB Blines—sectionB


B

headersB BorB BpropertyB Blines.B BIfB BaB BlineB BisB BalwaysB Bproperty,B BitB BisB
B

savedB BinB BtheB BexistingB Bsection.B BIfB BitB BisB BaB BsectionB Bheader,B BbuildB BaB
B

newB BsectionB Bobject,B BandB BsetB BsectionB BtoB Bit.


B

TheB BpatternB BifB B(matchB B=B Bstring.match())B BisB BidenticalB BtoB BtheB BtrickB BofB
utilizingB BanB BassignmentB BasB BtheB BconditionB BforB BaB Bwhile.
B

InternationalB Bcharacters
BecauseB BofB BJavaScript’sB BinitialB BsimplisticB BimplementationB BandB BthatB
thisB BapproachB BsetB BinB BstoneB BasB BstandardB Bbehavior,B BJavaScript’sB
B

regularB BexpressionsB BareB BsomewhatB BdumbB BaboutB BcharactersB BthatB


B

don’tB BshowB BinB BtheB BEnglishB Blanguage.B BForB Binstance,B BinB BJavaScript,B
B

BregularB Bexpressions,B BaB B“wordB Bcharacter”B BisB BjustB BoneB BofB BtheB B26B
BcharactersB BinB BtheB BLatinB BalphabetB B(lowercaseB BorB Buppercase),B BdecimalB

digits,B BandB BtheB BunderscoreB Bcharacter.B BCharactersB BlikeB BéB BorB Bß,B BareB
B

wordB Bcharacters,B BtheyB BwillB BnotB BmatchB B\w,B BwillB BmatchB BuppercaseB
B

\W,B BtheB BnonwordB Bcategory.B BItB BindicatesB BthatB BcharactersB BcomposedB


B

ofB BtwoB BcodeB Bunits.


B

console.log(/ 🍎{3}/.test("🍎🍎🍎"));
//B B→B Bfalse
🌹>"));
console.log(/<.>/.test("<

//B B→B Bfalse


console.log(/<.>/u.test("< 🌹>"));
//B B→B Btrue
TheB BidentifiedB BproblemB BhereB BisB BthatB B 🍎 in the first line is being
BB BB BB BB BB B B B

managedB BasB BtwoB BcodeB Bunits,B BandB BtheB B{3}B BsectionB BisB BusedB BtoB BtheB
B

secondB BoneB Bonly.B BTheB BdotB BalsoB BmatchesB BaB BsingleB BcodeB Bunit.B BAddB BuB
B

optionB B(forB BUnicode)B BtoB ByourB BregularB BexpressionB BsoB BthatB BitB
B

managesB BthatB BcharactersB Bproperly.B BTheB BwrongB BbehaviorB BremainB BsetB


B

asB BtheB Bdefault,B Bunfortunately,B BbecauseB BtransformingB BthatB BcouldB


B

createB BproblemsB BforB BcurrentB BcodeB BthatB BdependsB BonB Bit.


B

YouB BcanB BuseB B\pB BinB BaB BregularB BexpressionB BtoB BmatchB BeveryB BcharacterB
thatB BUnicodeB BstandardB BgivesB BaB BsetB Bproperty.
B

console.log(/\p{Script=Greek}/u.test("α"));

//B B→B Btrue


console.log(/\p{Script=Arabic}/u.test("α"));

//B B→B Bfalse


console.log(/\p{Alphabetic}/u.test("α"));

//B B→B Btrue


console.log(/\p{Alphabetic}/u.test("!"));

//B B→B Bfalse


UnicodeB BdescribesB BaB BnumberB BofB BimportantB Bproperties,B BalthoughB
searchingB BforB BtheB BoneB BthatB ByouB BneedB BmayB BnotB BalwaysB BbeB Btrivial.
B

Summary

WeB BfocusedB BonB BregularB BexpressionsB BinB BthisB Bchapter.B BAnB BobjectB BthatB
standsB BforB BpatternsB BinB BstringsB BisB BaB BregularB Bexpression.B BTheyB
B
consistB BofB BtheirB BlanguageB BandB ButilizeB BitB BforB BtheB BexhibitionB BofB
B

theseB Bpatterns.
B

/ABC/B BAB BsuccessionB BofB Bcharacters


/[abc]/B BCharacterB BfromB BaB BrangeB BofB Bcharacters
/[^abc]/B BAnyB BcharacterB BabsentB BinB BaB BrangeB BofB Bcharacters
/B B[0-9]/B BAnyB BcharacterB BwithinB BaB BsetB BofB Bcharacters
/x+/B BOneB BorB BmoreB BeventsB BofB BtheB BpatternB Bx
/x+?B B/B BOneB BorB BmoreB Bevents,B Bnongreedy
/x*/B BZeroB BorB BmoreB Bevents
/x?B B/B BZeroB BorB BoneB Bevents
/xB B{2,4}/B BTwoB BtoB BfourB Bevents
/(ABC)/B BAB Bgroup
/a|b|c/B BAnyB BoneB BofB BvariousB Bpatterns
/\d/B BAnyB BdigitB Bcharacter
/\w/B BAnB BwordB Bcharacter
/\s/B BAnyB BwhitespaceB Bcharacter
/.B B/B BAnyB BcharacterB BexcludingB Bnewlines
/\b/B BAB BwordB Bboundary
/^/B BBeginningB BofB Binput
/$/B BEndB BofB Binput
AB BregularB BexpressionB BconsistsB BofB BaB BmethodB BtestB BtoB BcheckB BifB BaB BsetB
stringB BmatchesB Bit.B BItB BalsoB BcontainsB BanB BexecB Bmethod,B BwherebyB
B

whenB BitB BfindsB BaB Bmatch,B BitB BsendsB BbackB BanB BarrayB BhavingB BeveryB
B

matchedB Bgroup.B BThisB BtypeB BofB BarrayB BcontainsB BanB BindexB BpropertyB
B

thatB BspecifiesB BwhereB BtheB BmatchB Bstarted.B BStringsB BuseB BaB BmatchingB
B
methodB BtoB BmatchB BthemB BinB BoppositionB BtoB BaB BregularB BexpressionB BasB
B

wellB BasB BaB BsearchB BmethodB BtoB BfindB Bone,B BsendingB BbackB BonlyB BtheB
B

beginningB BpositionB BofB BtheB Bmatch.


B

Exercise

WriteB BaB BJavaScriptB BprogramB BworkingB BasB BaB BtrimB BfunctionB B(string)B
utilizingB BregularB Bexpression.
B
Solution
Chapter 11: Modules BB BB

ThisB BparticularB BprogramB BhasB BaB BsimpleB Blayout.B BItB BisB BveryB BtoB BexplainB
itsB Bconcept,B BandB BeveryB BpartB BplaysB BaB BpreciseB Brole.B BTheB BorganizingB
B

andB BmaintainingB BofB BtheB BlayoutB BcanB BbeB BmuchB BmoreB Bwork,B BbutB BitB
B

eventuallyB BpaysB BoffB BtheB BnextB BtimeB BsomeoneB BusesB BtheB BprogramB BinB
B

theB Bfuture.B BTherefore,B ByouB BcanB BbeB BintriguedB BtoB BneglectB BitB BandB
B

enableB BtheB BprogramB BpartsB BtoB BbecomeB Bintermixed,B BwhichB BwillB


B

createB BtwoB BpracticalB Bissues.B BFirst,B BwhenB BeverythingB BtouchesB


B

everythingB Belse,B BitB BisB BhardB BtoB BlookB BatB BanyB BsetB BpieceB BinB Bseparation.B
B

YouB BwillB BhaveB BtoB BcreateB BaB BcomprehensiveB BunderstandingB BofB BtheB
B

fullB Bprogram.B BSecond,B BusingB BanyB BofB BtheB BfunctionalityB BfromB BtheB
B

programB BinB BdifferentB Bsituations,B ByouB BcanB BrewriteB BitB BinsteadB BofB
B

disengagingB BitB BfromB BtheB Bcontext.


B

Modules

AB BModuleB BisB BaB BtypeB BofB BprogramB BthatB BdeterminesB BwhichB BpiecesB BitB
shouldB BdependB BonB BandB BwhatB BfunctionalityB BshouldB BitB BproduceB BforB
B

otherB BpiecesB BtoB Butilize.B BByB BputtingB BaB BlimitB BonB BtheB BwaysB BmodulesB
B

communicateB BwithB BoneB Banother,B BtheB BsystemB BisB BidenticalB BtoB BLEGO,B
B

whereB BpiecesB BcommunicateB BusingB BstraightforwardB Bconnectors,B BandB


B

notB BlikeB BmudB BwhereB BtheB BentireB BpiecesB BmixB BwithB Beverything.B
B

DependenciesB BareB BtheB BrelationshipsB BbetweenB Bmodules.B BWhenB BaB


B

moduleB BwantsB BaB BpieceB BfromB BanotherB Bmodule,B BitB BdependsB BonB BthatB
B

module.B BTheB BmoduleB BitselfB BillustratesB BthisB Bfact,B BandB BitB BisB BusedB BtoB
B

determineB BwhichB BotherB BmodulesB BshouldB BbeB BavailableB BtoB BuseB BaB
B

BstatedB BmoduleB BandB BtoB BloadB BdependenciesB Bautomatically.B BEveryB


BmoduleB BneedsB BitsB BscopeB BtoB BseparateB BitselfB BfromB BotherB Bmodules.
Packages

OneB BsignificantB BbenefitB BofB BbuildingB BaB BprogramB BoutB BofB BdifferentB
pieces,B BandB BbeingB BableB BtoB BlaunchB BthoseB BpiecesB Bindividually,B BisB BthatB
B

youB BcanB BapplyB BtheB BsameB BpieceB BinB BseparateB Bprograms.B BWhenB BtheB
B

duplicationB BofB BcodeB Bbegins,B BtheB BpackageB BcomesB BinB BtoB Bplay.B BAB
B

packageB BisB BaB BblockB BofB BcodeB BthatB BcanB BbeB Bshared.B BItB BmayB BconsistB BofB
B

oneB BorB BmoreB BmodulesB BandB BholdsB BinformationB BaboutB BtheB BotherB
B

dependingB
B Bpackages.B BPackagesB alsoB
B containB
B BdocumentationB
describingB BitsB BfunctionsB BsoB BthatB BpeopleB BwhoB Bdidn’tB BwriteB BitB BcanB
B

utilizeB Bit.B BWhenB BaB BproblemB BoccursB BinB BaB Bpackage,B BorB ByouB BaddB BaB
B

newB Bfeature,B BtheB BpackageB BupdatesB Bautomatically.B BNowB BprogramsB


B

dependingB BonB BitsB BupgradesB BtoB BtheB BlatestB Bversion.B BWorkingB BlikeB
B

this,B ByouB BneedB Binfrastructure.B BAB BplaceB BtoB BsaveB BandB BsearchB BforB
B

packagesB BandB BanB BeasyB BwayB BtoB BupgradeB BandB BinstallB Bthem.B BWhenB BitB
B

comesB BtoB BJavaScript,B BNPMB BprovidesB Bsupport.B B


B

DivideB BNPMB BintoB BtwoB Bthings:B BanB BonlineB BserviceB BwhereB ByouB BcanB
uploadB BandB BdownloadB BpackagesB BandB BaB BprogramB BthatB BhandlesB BtheB
B

installationB BandB Bmanagement.B BAlmostB BeveryB BcodeB BonB BNPMB BisB


B

licensed.
B

ImprovisedB Bmodules
BeforeB BtheB ByearB B2015,B BtheB BJavaScriptB BlanguageB BdidB BnotB BcontainB BanyB
built-inB BmoduleB Bsystem,B BbutB BpeopleB BhaveB BbeenB BcreatingB BlargeB
B

systemsB BusingB BJavaScriptB BforB BoverB BaB BdecadeB Bnow,B BandB BtheyB
B

requiredB Bmodules.B BTheyB BdevelopedB BtheirB BmoduleB BsystemsB BandB


B

integratedB BthemB BintoB BtheB Blanguage.B BYouB BcanB ButilizeB BJavaScriptB


B

BfunctionsB BtoB BbuildB BlocalB BscopesB BandB BobjectsB BtoB BstandB BforB BmoduleB
Blayouts.B BUseB BthisB BmoduleB BtoB BoverB BbetweenB BdayB BnamesB BandB

numbers.B BItsB BlayoutB BcontainsB BtheB BweekDay.B BNameB BandB BweekDay.


B
.number,B BandB BitB BhidesB BitsB BlocalB BbindingB BnamesB BinsideB BtheB BscopeB BofB
BaB Bfunction
TheB BexpressionB BisB BcalledB BuponB Bimmediately.
constB BweekDayB B=B Bfunction()B B{
constB BnamesB B=B B["Sunday",B B"Monday",B B"Tuesday",B B"Wednesday",
"Thursday",B B"Friday",B B"Saturday"];
returnB B{
name(number)B B{returnB Bnames[number];},
number(name)B B{returnB Bnames.indexOf(name);}
};
}();
console.log(weekDay.name(weekDay.number("Sunday")));

//B B→B BSunday


ThisB BstyleB BofB BmodulesB BdoesB BnotB BproclaimB Bdependencies.B BTheyB BplaceB
BtheB BlayoutB BintoB BtheB BglobalB Bscope.B BThisB BstyleB BofB BmodulesB BprovidesB
BisolationB BtoB BaB BcertainB Bdegree,B butB
B BitB doesB
B notB
B BdeclareB
Bdependencies.B BInstead,B BitB BjustB BputsB BitsB BinterfaceB BintoB BtheB BglobalB
BscopeB BandB BawaitsB BitsB Bdependencies,B BifB BthereB BisB Bany,B BtoB BdoB BtheB
Bsame.
Evaluating data as code
BB BB BB

ThereB BareB BdifferentB BtypesB BofB BwaysB BtoB BtakeB BdataB BandB BlaunchB BitB BasB
BpartB BofB BtheB BexistingB Bprogram.B BTheB BbestB BwayB BisB BtoB ButilizeB BtheB
BuniqueB BoperatorB Beval,B BwhichB BaffectsB BaB BstringB BinB BtheB BexistingB Bscope.
constB BxB B=B B1;
functionB BevalAndReturnX(code)B B{
eval(code);
returnB Bx;
}

console.log(evalAndReturnX("varB BxB B=B B2"));


//B B→B B2
console.log(x);

//B B→B B1
AB BlessB BcomplicatedB BwayB BtoB BexplainB BdataB BasB BcodeB BisB BusingB BtheB
FunctionB Bconstructor.B BItB BtakesB BtwoB BtypesB BofB Bargument,B BaB BstringB
B

withB BaB Bcomma,B BdividedB BlistB BofB BargumentB BnamesB BandB BaB BstringB BwithB
B

theB BbodyB Bfunction.B BItB BenclosesB BtheB BcodeB BinB BaB BfunctionB BvalueB BtoB
B

enableB BitB BgetB BitsB BownB Bscope.


B

letB BplusOneB B=B BFunction("n",B B"returnB BnB B+B B1;");


console.log(plusOne(4));

//B B→B B5
YouB BcanB BencloseB BtheB Bmodule'sB BcodeB BinB BaB BfunctionB BandB ButilizeB BthatB
sameB BfunctionB BscopeB BasB BaB BmoduleB Bscope.
B

CommonJS

TheB BcommonB BapproachB BusedB BtoB BgobbleB BonB BJavaScriptB BmodulesB BisB
theB BCommonJSB Bmodules.B BNode.jsB BusesB BthisB BapproachB BasB BwellB BasB BaB
B

lotB BofB BpackagesB BonB BNPM.B BTheB BmajorB BideaB BinB BCommonJSB BmodulesB
B

BisB BtheB BfunctionB BnamedB Brequire.B BIfB ByouB BcallB BthisB BtogetherB BwithB BtheB
Bdependency'sB BmoduleB Bname,B BitB BloadsB BtheB BmoduleB BandB BsendsB BbackB

itsB Binterface.B BTheB BloaderB BcoversB BtheB BmoduleB BcodeB BwithinB BaB
B

function,B BandB BmodulesB BhaveB BtheirB BlocalB BscopeB Bautomatically.B BYouB


B

canB BcallB BrequireB BtoB BseeB BtheirB BdependenciesB BandB BplaceB BtheirB BlayoutB
B

inB BtheB BobjectB BthatB BexportsB Bthem.B BThisB BexampleB BmoduleB BgivesB BaB
B

date-formattingB Bfunction.B BItB ButilizesB BtwoB BpackagesB BfromB BNPM,B BtheB


B
BordinalB BtoB BtransformB BnumbersB BtoB BstringsB BlikeB B"1st"B BandB B"2nd",B
BandB Bdate-namesB BtoB BobtainB BtheB BEnglishB BnamesB BforB BmonthsB BandB
Bweekdays.B BItB BexportsB BaB BsingleB Bfunction,B BformatDate,B BthatB BtakesB BaB
BtemplateB BstringB BandB BaB BDateB Bobject.B BTheB BtemplateB BstringB BcouldB
BcontainB BcodesB BthatB BcontrolB BtheB Bformat,B BsuchB BasB BYYYYB B(theB BfullB
Byear)B BandB BDoB BforB BtheB BordinalB BdayB BofB BtheB Bmonth.B BYouB BcanB BsetB BaB
BstringB BtoB BitB BlikeB B"MMMMB BDoB BYYYY"B BtoB BgetB BoutputB BlikeB B“DecemberB
B2nd,B B2013”.
constB BordinalB B=B Brequire("ordinal");
constB B{days,B Bmonths}B B=B Brequire("date-names");
exports.formatDateB B=B Bfunction(date,B Bformat)B B{
returnB Bformat.replace(/YYYY|M(MMM)?|Do?|dddd/g,B BtagB B=>B B{
ifB B(tagB B==B B"YYYY")B BreturnB Bdate.getFullYear();
ifB B(tagB B==B B"M")B BreturnB Bdate.getMonth();
ifB B(tagB B==B B"MMMM")B BreturnB Bmonths[date.getMonth()];
ifB B(tagB B==B B"D")B BreturnB Bdate.getDate();
ifB B(tagB B==B B"Do")B BreturnB Bordinal(date.getDate());
ifB B(tagB B==B B"dddd")B BreturnB Bdays[date.getDay()];
});
};

TheB BlayoutB BofB BtheB BordinalB BisB BaB BsingleB Bfunction,B BwherebyB BtheB Bdate-
namesB BexportsB BanB BobjectB BthatB BconsistsB BofB BseveralB BotherB Bthings,B
BmonthsB BandB BdaysB BareB BarraysB BofB Bnames.B BRestructuringB BisB BquiteB BeasyB
BwhenB BbuildingB BbindingsB BforB BimportedB Blayouts.B BTheB BmoduleB BattachesB
BitsB BlayoutB BfunctionB BtoB BexportsB BsoB BthatB BmodulesB BthatB BrelyB BonB BitB
BhaveB BaccessB BtoB Bit.B BUtilizeB BtheB BmoduleB BthisB Bway:
constB B{formatDate}B B=B Brequire(“.B B/format-date");
console.log(formatDate(newB BDate(2017,B B9,B B13),
"ddddB BtheB BDo"));
//B B→B BFridayB BtheB B13th
WeB BcanB BdefineB Brequire,B BinB BitsB BmostB BminimalB Bform,B BlikeB Bthis:
require.cacheB B=B BObject.create(null);
functionB Brequire(name)B B{
ifB B(!B B(nameB BinB Brequire.cache))B B{
letB BcodeB B=B BreadFile(name);
letB BmoduleB B=B B{exports:B B{}};
require.cache[name]B B=B Bmodule;
letB BwrapperB B=B BFunction("require,B Bexports,B Bmodule",B Bcode);
wrapper(require,B Bmodule.exports,B Bmodule);
}

returnB Brequire.cache[name].exports;
}

InB BthisB Bcode,B BreadFileB BisB BaB BpoweredB BfunctionB BthatB BreadsB BaB BfileB BandB
sendsB BbackB BitsB BcontentsB BasB BaB Bstring.B BStandardB BJavaScriptB BdoesB BnotB
B

offerB BsuchB Bfunctionality,B BbutB BseveralB BotherB BJavaScriptB BenvironmentsB


B

suchB BasB BNode.jsB BandB BtheB BbrowserB BoffersB BtheirB BuniqueB BwaysB BofB
B

accessingB Bfiles.B BTheB BaboveB BexampleB BbluffsB BthatB BreadFileB Bexists.B BToB
B

keepB BawayB BfromB BloadingB BtheB BsameB BmoduleB BseveralB Btimes,B ByouB
B

needB BaB BstoreB B(cache)B BofB BalreadyB BloadedB Bmodules.B BIfB Bcalled,B BitB
B

examinesB BifB BtheB BdemandedB BmoduleB BloadsB Band,B BifB Bnot,B BitB BloadsB Bit.B
B

ItB BrequiresB BreadingB BtheB Bmodule’sB Bcode,B BenclosingB BitB BwithinB BaB
B

functionB BandB BcallingB Bit.B BTheB BlayoutB BofB BtheB BordinalB BpackageB BfromB
B

earlierB BisB BaB BfunctionB BandB BnotB BanB Bobject.B BTheB BCommonJSB BmodulesB
B
createB BanB BemptyB BlayoutB BobjectB BusingB BtheB BmoduleB BsystemB BforB ByouB
B

toB Bexport,B BrestoreB BthatB BwithB BvaluesB BbyB BoverwritingB Bmodule.exports.B


B

ModulesB BdoB BthisB BtoB BexportB BaB BsingleB BvalueB BinsteadB BofB BaB BlayoutB
B

object.B BByB BdescribingB Bexports,B BrequireB BandB BmoduleB BasB BparametersB


B

forB BtheB BcreatedB BenclosingB BfunctionB B(andB BsettingB BtheB BrightB BvaluesB
B

whileB BcallingB Bit),B BtheB BloaderB BensuresB BthatB BtheseB BbindingsB BareB
B

accessibleB BwithinB BtheB Bmodule’sB Bscope.B BStringsB BsetB BtoB BrequireB BisB
B

interpretedB BtoB BaB BfilenameB BorB BwebB BaddressB BvaryB BinB BseparateB
B

systems.B BWhenB BitB BstartsB BwithB B“.B B/"B Bor.B B“/,"B BitB BisB BusuallyB
B

translatedB BasB BrelativeB BtoB BtheB BexistingB Bmodule’sB Bfilename.B BSoB B“.B B/B
B

format-date"B BwillB BbeB BtheB BfileB BcalledB Bformat-date.jsB BinB BtheB BsameB
B

directory.
B

IfB BtheB BnameB BisB BnotB Brelative,B BNode.jsB BwillB BsearchB BforB BaB BpackageB
thatB BisB BinstalledB BbyB BthatB Bname.
B

Now,B BinsteadB BofB BwritingB ByourB BownB BINIB BfileB Bparser,B ByouB BcanB ButilizeB
oneB BfromB BNPM.
B

constB B{parse}B B=B Brequire("ini");


console.log(parse("xB B=B B10\nyB B=B B20"));
//B B→B B{x:B B"10",B By:B B"20"}
ECMAScript modulesBB

CommonJSB BmodulesB BperformB BwellB BwhileB BcombiningB BwithB BNPM,B BandB


theyB BenableB BtheB BJavaScriptB BcommunityB BtoB BbeginB BcodesharingB BonB BaB
B

substantialB Bscale.B BTheB BnotationB BisB BquiteB Bweird.B BTheB BthingsB BaddedB
B

toB BexportsB BareB BnotB BaccessibleB BwithinB BtheB BlocalB Bscope.B BWithoutB
B

runningB BtheB BcodeB BofB BaB Bmodule,B BitB BwillB BbeB BtoughB BtoB BdetermineB BitsB
B

dependenciesB BbeforeB BtakingB BanyB Bargument.B BThatB BisB BtheB BreasonB


B

JavaScriptB BstandardB BestablishesB BitsB Bown,B BseparateB BmoduleB Bsystem.B


B
ItB BisB BnamedB BcalledB BESB Bmodules,B BwhereB BESB BrepresentsB BECMAScript.B
B

TheB BinitialB BideaB BofB BdependenciesB BandB BinterfacesB BstayB BtheB Bsame,B
B

butB BtheirB BdetailsB BareB Bdifferent.B BTheB BnotationB BintegratesB BintoB BtheB
B

language.B BYouB BcanB BnowB BuseB BaB BuniqueB BimportB BkeywordB BtoB BaccessB BaB
B

dependencyB BinsteadB BofB BcallingB BaB Bfunction.


B

ImportB BordinalB BfromB B"ordinal";


importB B{days,B Bmonths}B BfromB B"date-names";
exportB BfunctionB BformatDate(date,B Bformat)B B{B B/*B B...B B*/B B}
UseB BtheB BexportB BkeywordB BtoB BexportB Bthings.B BItB BcouldB BdisplayB BatB BtheB
frontB BofB BaB Bclass,B BfunctionB BorB BbindingB BdefinitionB B(let,B Bconst,B BorB
B

var).B BAnB BESB Bmodule’sB BlayoutB BdoesB BnotB BrepresentB BaB BsingleB BvalueB
B

butB BaB BsetB BofB BnamedB Bbindings.B BTheB BpreviousB BmoduleB BattachesB
B

formatDateB BtoB BaB Bfunction.B BIfB ByouB BimportB BfromB BaB BdifferentB Bmodule,B
B

theB BbindingB BcomesB BwithB Bit,B BandB BnotB BtheB Bvalue,B BwhichB BmeansB BtheB
B

valueB BofB BanB BexportingB BmoduleB BcanB BchangeB BtheB BbindingB BanyB Btime,B
B

andB BtheB BimportingB BmodulesB BwillB BrecognizeB BitsB BnewB Bvalue.B BIfB BaB
B

bindingB BisB BnamedB Bdefault,B BrecognizesB BitB BasB BtheB Bmodule’sB BmajorB
B

exportedB Bvalue.B BIfB BaB BmoduleB BlikeB BordinalB BimportsB BinB BtheB Bexample,B
B

omittingB BtheB BbracesB BacrossB BtheB BbindingB Bname,B ByouB BwillB BfindB BitsB
B

defaultB Bbinding.B BToB BdevelopB BaB BdefaultB Bexport,B BwriteB BexportB BdefaultB
B

aheadB BofB Bexpression,B BaB BclassB BorB BaB BfunctionB Bdeclaration.


B

exportB BdefaultB B["Winter",B B"Spring",B B"Summer",B B"Autumn"];


YouB BcanB BrenameB BimportedB BbindingsB BusingB BtheB BwordB BlikeB Bthis.
importB B{daysB BasB BdayNames}B BfromB B"date-names";
console.log(dayNames.length);

//B B→B B7
AnotherB BmajorB BdifferenceB BisB BthatB BtheB BESB BmoduleB BimportsB BoccurB
beforeB BaB Bmodule’sB BscriptB BbeginsB BtoB Brun.B BImportB BdeclarationsB BmayB
B

notB BdisplayB BwithinB BfunctionsB BorB Bblocks,B BandB BtheB BdependentB BnamesB
B

shouldB BbeB BquotedB BstringsB BandB BnotB BarbitraryB Bexpressions.B BAB BlotB BofB
B

projectsB BareB BwrittenB BthroughB BESB BmodulesB BandB BthenB BchangedB BtoB
B

someB BotherB BformatB BwhenB BitB BisB Bpublished.B BDuringB BaB BtransitionalB
B

period,B BuseB BtwoB BseparateB BmoduleB BsystemsB BsideB BbyB Bside.


B

ModuleB Bdesign
ProgramB BstructuringB BisB BoneB BofB BtheB BniceB BfeaturesB BofB Bprogramming.B
AnyB BunknownB BfunctionalityB BcanB BmodelB BinB BdifferentB Bways.B BTheB
B

goodB BprogramB BdesignB BisB BaB BpersonalizedB Bone,B BandB BthereB BisB BaB
B

matterB BofB BpreferenceB BandB Btaste.B BToB BunderstandB BtheB BvalueB BofB Bwell-
B

organizedB Bdesign,B ByouB BneedB BtoB BreadB BandB BworkB BonB BseveralB
programsB BandB BtakeB BnoteB BofB BperformingB BandB Bnon-performingB
B

functions.B BTheB BmoduleB BdesignB BisB BstraightforwardB BtoB Buse.B BTheB BiniB
B

packageB BmoduleB BfollowsB BtheB BstandardB BJSONB BobjectB BbyB BsupplyingB


B

stringifyB BandB BparseB B(toB BwriteB BanB BINIB Bfile)B Bfunctions,B Band,B BlikeB
B

JSON,B BchangesB BbetweenB BplainB BobjectsB BandB Bstrings.B BAB BlotB BofB BtheB BINI-
B

fileB BparsingB BmodulesB BonB BNPMB BsupplyB BaB BfunctionB BthatB BreadsB BthatB
typeB BofB BfileB BfromB BtheB BhardB BdiskB BandB BparsesB Bit.B BConcentratedB
B

modulesB BthatB BcalculateB BvaluesB BareB BsuitableB BinB BaB BlargerB BrangeB BofB
B

programsB BthanB BlargerB BmodulesB BthatB BexecuteB BcomplexB BactionsB BthatB


B

haveB BsideB Beffects.B BAnB BINIB BfileB BreaderB BthatB BwantB BtoB BreadB BtheB BfileB
B

fromB BdiskB BisB BnotB BusefulB BinB BcasesB BwherebyB BtheB Bfile’sB BcontentB BcomesB
B

fromB BanotherB Bsource.B BSimilarly,B BstatefulB BobjectsB BareB BoccasionallyB


B

necessaryB BandB Buseful,B BbutB BifB ByouB BcanB BuseB BaB Bfunction,B ButilizeB Bit.B
B

VariousB BINIB BfileB BreadersB BonB BNPMB BgivesB BaB BlayoutB BstyleB BthatB BneedsB
B

youB BtoB BbuildB BanB Bobject,B BthenB BloadB BtheB BfileB BintoB BtheB Bobject,B BandB
B
useB BspecificB BmethodsB BtoB BachieveB BtheB BdesiredB Bresults.B BItB BisB BtheB
B

object-orientedB BstyleB BandB Btradition.B BInB BJavaScript,B BthereB BisB BnoB


B

particularB BwayB BtoB BrepresentB BaB Bgraph.B BThereB BareB BvariousB


B

pathfindingB BpackagesB BavailableB BonB BNPM,B BbutB BnoneB ButilizesB BtheB


B

graphB Bformat.B BTheyB BoftenB BletB BgraphB BedgesB BcontainB BaB Bweight,B BandB
B

thatB BisB BtheB BdistanceB BorB Bcost-relatedB BwithB Bit.B BForB Binstance,B BweB BhaveB
B

theB BdijkstrajsB Bpackage.B BAB BrecognizedB BwayB BtoB Bpathfinding,B BrelatedB


B

toB BtheB BfindRouteB BfunctionB BisB BtheB BDijkstra’sB Balgorithm,B BafterB BEdsgerB
B

Dijkstra,B BtheB BpackageB BfirstB Bwriter.B BTheB BjsB BsuffixB BisB BregularlyB
B

attachedB BtoB BpackageB BnamesB BtoB BspecifyB BthatB ByouB BcanB BwriteB BinB
B

JavaScript.B BSo,B BifB ByouB BwantB BtoB BuseB BthatB Bpackage,B BensureB BthatB BtheB
B

graphB BsavesB BinB BitsB BexpectedB Bformat.


B

constB B{find_path}B B=B Brequire("dijkstrajs");


letB BgraphB B=B B{};
forB B(letB BnodeB BofB BObject.keys(roadGraph))B B{
letB BedgesB B=B Bgraph[node]B B=B B{};
forB B(letB BdestB BofB BroadGraph[node])B B{
edges[dest]B B=B B1;
}
}

console.log(findB Bpath(graph,B B"PostB BOffice",B B"Cabin"));


//B B→B B["PostB BOffice",B B"Alice'sB BHouse",B B"Cabin"]
ItB BcanB BbeB BaB BroadblockB BtoB BcompositionB BwhenB BseveralB BpackagesB BuseB
separateB BdataB BstructuresB BtoB BdefineB BrelatedB Bthings,B BandB BitB BisB BhardB
B

toB BcombineB Bthem.B BTherefore,B BwhenB ByouB BareB BdesigningB BforB


B

composability,B BknowB BexactlyB BtheB BdataB BstructuresB BothersB BareB BusingB


B

andB ByouB BcanB BfollowB BtheirB Bexample.


B
Summary

InB BthisB Bchapter,B BweB BcoveredB BtheB BModules.B BModulesB BgiveB BstructureB
toB BmoreB BextensiveB BprogramsB BbyB BdifferentiatingB BtheB BcodeB BintoB BbitsB
B

withB BunderstandableB BdependenciesB BandB Binterfaces.B BTheB BinterfaceB BisB


B

aB BmoduleB BwhichB ByouB BcanB BseeB BfromB BotherB Bmodules,B BandB BtheB
B

dependenciesB BareB BdifferentB BmodulesB BthatB BitB Buses.


B

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BshowB BtheB BcurrentB BdayB BandB BtimeB BinB
theB BfollowingB Bformat.
B

TodayB BisB BTuesday.


CurrentB BtimeB Bis:B B10B BPM:B B30:B B38
Solution
BB
Chapter 12: Asynchronous BB BB B

Programming
B

TheB BprocessorB BisB BaB BvitalB BpartB BofB BaB BcomputerB BthatB BperformsB BtheB
individualB BstepsB BthatB BbalanceB BourB Bprograms.B BTheB BspeedB BlevelB BofB
B

somethingB BlikeB BaB BloopB BthatB BinfluencesB BnumbersB BcompletionB


B

dependsB
B onB
B B theB processor'sB
B speed.B
B AB
B lotB
B ofB
B programsB
B

communicateB BwithB BthingsB BoutsideB BofB BtheB Bprocessor.B BForB Binstance,B


B

theyB BmayB BinteractB BthroughB BaB BcomputerB BnetworkB BorB BdemandB BforB
B

dataB BfromB BtheB BhardB Bdisk,B BwhichB BisB BquiteB BslowerB BthanB BobtainingB BitB
B

fromB Bmemory.B BInB Bpart,B BtheB BoperatingB BsystemB BhandlesB BthisB BpartB
B

andB BwillB BchangeB BtheB BprocessorB BbetweenB BvariousB BprogramsB BthatB BareB
B

running.
B

Asynchronicity

InB BtheB BasynchronousB BprogrammingB Bmodel,B BeverythingB BoccursB BoneB


atB BaB Btime.B BIfB ByouB BcallB BaB BfunctionB BthatB BexecutesB BaB BlongB BdurationB
B

action,B BresultsB BwillB BreturnB BwhenB BtheB BoperationB BcompletesB Bonly.B BNoB
B

otherB BactionB BwouldB BbeB BableB BtoB BtakeB BplaceB BduringB Bexecution.B BAnB
B

asynchronousB BmodelB BenablesB BseveralB BthingsB BtoB BoccurB BatB BtheB BsameB
B

time.B BWhenB BanB BactionB Bbegins,B BtheB BprogramB BdoesB BnotB BstopB
B

running.B BWhenB BtheB BtaskB Bcompletes,B BitB BnotifiesB BtheB BprogramB BandB
B

canB BaccessB BtheB BresultB B(forB Binstance,B BtheB BinformationB BreadB BfromB
B

disk).B
B YouB
B canB
B B differentiateB betweenB
B B synchronousB andB
B

asynchronousB BprogrammingB BthroughB BaB BlittleB Bexample:B BaB BprogramB


B

thatB BobtainsB BtwoB BresourcesB BfromB BtheB BnetworkB BandB BthenB BunifiesB
B

theB Bresults.
B
InB BanB BasynchronousB Benvironment,B BtheB BrequestB BfunctionB BreturnsB
whenB BtheB BworkB Bcompletes.B BTheB BsimplestB BwayB BtoB BexecuteB BthisB BtaskB
B

isB BtoB BcallB BtheB BrequestsB BoneB BafterB Banother.B BItB BconsistsB BofB BtheB
B

drawbackB BthatB BbeginsB BtheB BsecondB BrequestB BonlyB BwhenB BtheB BfirstB BtaskB
B

completes.B BTheB BsumB BofB BbothB BresponseB BtimesB BwillB BbeB BtheB BtotalB
B

timeB Btaken.B BToB BsolveB BthisB BproblemB BinB BaB BsynchronousB Bsystem,B BstartB
B

addingB BthreadsB BofB Bcontrol.B BAB BthreadB BisB BaB BrunningB BprogramB BthatB
B

itsB BexecutionB BcouldB BbeB BrenderedB BwithB BotherB BprogramsB BthroughB BtheB
B

operatingB
B systemB
B BbecauseB modernB
B computersB
B haveB
B severalB
B

processors,B BvariousB BthreadsB BcanB BrunB BatB BonceB BonB BseparateB


B

processors.B BAB BsecondB BthreadB BmayB BbeginB BtheB BsecondB Brequest,B BandB
B

thenB BtheB BtwoB BthreadsB BbothB BwaitB BforB BtheirB BresultsB BtoB Breturn,B BafterB
B

that,B
B theyB
B resynchronizeB
B BtoB unifyB
B bothB
B results.B
B InB
B theB
B

asynchronousB Bmodel,B BtheB BnetworkB BtimeB BisB BpartB BofB BtheB BtimelineB BforB
B

aB BstatedB BthreadB BofB Bcontrol.B BInB BanB BasynchronousB Bmodel,B BlaunchingB


B

aB BnetworkB BactionB BnotionalB BcreatesB BaB BdivisionB BinB BtheB Btimeline.B BTheB
B

programB BthatB BcommencesB BtheB BactionB BdoesB BnotB BstopB Brunning,B BandB
B

thenB BtheB BactionB BoccursB BwithB Bit,B BitB BinformsB BtheB BprogramB BwhenB BitB
B

completes.
B

AnotherB BwayB BtoB BdetermineB BtheB BsimilaritiesB BisB BthatB BwaitingB BforB
tasksB BtoB BcompleteB BisB BindirectB BinB BtheB BsynchronousB Bmodel,B BwhileB BitB
B

isB BdirectlyB BunderB BourB Bcontrol,B BinB BtheB BasynchronousB Bone.


B

Callbacks

OneB BprocedureB BtoB BasynchronousB BprogrammingB BisB BtoB BenableB


functionsB BthatB BexecuteB BaB BslowB BactionB BtoB BgainB BanB BextraB Bargument,B
B

andB BtheB BargumentB BisB BcalledB BaB BcallbackB Bfunction.B BWhenB BtheB BactionB
B

beginsB BandB Bends,B ByouB BshouldB BcallB BtheB BresultB BwithB BtheB BcallbackB
B

function.B BForB Binstance,B BtheB BsetTimeoutB Bfunction,B BaccessibleB BbothB BinB


B
BtheB BbrowsersB BandB BNode.js,B BwaitsB BaB BstatedB BnumberB BofB BmillisecondsB
BandB BthenB BcallsB BaB Bfunction.B BsetTimeout(()B B=>B Bconsole.log("Tick"),B
B500);B BWaitingB BisB BnotB BanB BidealB BtypeB BofB Bwork,B BbutB BcanB BbeB BapplicableB
BwhenB ByouB BareB BrunningB BprogramsB BlikeB BanB BanimationB BupdateB BorB
BcheckingB BifB BaB BfunctionB BisB BtakingB BlongerB BthanB BtheB BspecifiedB Btime.B
BRunningB BseveralB BasynchronousB BtasksB BinB BaB BrowB BthroughB BcallbacksB
BsignifiesB BthatB ByouB BhaveB BtoB BcontinueB BsettingB BnewB BfunctionsB BtoB
BcontrolB BtheB BcontinuationB BofB BtheB BcalculationsB BafterB BtheB Bactions.
AB BlotB BofB BcrowB BnestB BcomputersB BconsistB BofB BaB BlongstandingB BdataB
BstorageB Bbulb,B BwhereB BdataB BisB BstoredB BintoB BtwigsB BsoB BthatB BitB BcanB BbeB
BaccessedB BandB BrestoredB Blater.B BStoring,B BorB BsearchingB BforB BaB BpieceB BofB
BdataB BtakesB BlittleB Btime,B BsoB BtheB BlayoutB BtoB BlongstandingB BstorageB BisB
BasynchronousB BandB ButilizesB BcallbackB Bfunctions.B BStorageB BbulbsB BsaveB
BbitsB BofB BJSON-encodableB BdataB BunderB Bnames.B BAB BcrowB BcouldB BsaveB BdataB
BaboutB BplacesB BitB BhasB BhiddenB BfoodB BunderB BtheB BnameB B"foodB Bcaches,"B
BthatB BholdsB BanB BarrayB BofB BnamesB BthatB BpointB BatB BotherB BpiecesB BofB Bdata,B
BdefiningB BtheB Bcache.B BToB BsearchB BforB BaB BfoodB BcacheB BinB BtheB BstorageB
BbulbsB BofB BtheB BBigB BOakB Bnest,B BaB BcrowB BcouldB BrunB BcodeB BthisB Bway:
importB B{bigOak}B BfromB B“.B B/crow-tech";
bigOak.readStorage("foodB Bcaches",B BcachesB B=>B B{
letB BfirstCacheB B=B Bcaches[0];
bigOak.readStorage(firstCache,B BinfoB B=>B B{
console.log(info);
});
});

ThisB BprogrammingB BstyleB BisB Bpracticable,B BbutB BtheB BindentationB BlevelB


BexpandsB BwithB BeveryB BasynchronousB BactionB BbecauseB BitB BleadsB BinB
BanotherB Bfunction.B BPerformingB BsomeB BdifficultB BtaskB BsuchB BasB BrunningB
BseveralB BactionsB Bconcurrently,B BcanB BgetB Bweird.B BCrowB BnestB BcomputersB
BareB BcreatedB BtoB BinteractB BthroughB Brequest-responseB Bpairs.B BThatB
BmeansB BoneB BnestB BtransfersB BaB BmessageB BtoB BtheB BotherB Bnest,B BwhichB
BinstantlyB BreturnsB BaB Bmessage,B BaffirmingB BreceiptB BandB BattachingB BaB
BreplyB BtoB BtheB BmessageB Bquestions.B BEveryB BmessageB BearmarkB BwithB BaB
Btype,B BwhichB BdecidesB BhowB BitB Bcontrols.B BYourB BcodeB BcanB BdescribeB
BhandlersB BforB BcertainB BrequestB Btypes,B BandB BwhenB BtheB BrequestB BcomesB
Bin,B BtheB BhandlerB BisB BcalledB BtoB BprovideB BaB Breply.B BTheB BlayoutB BexportedB
BbyB BtheB B“.B B/crow-tech"B BmoduleB BproducesB Bcallback-basedB BfunctionsB
BforB Binteraction.B BNestsB BcontainB BaB BsendB BmethodB BwhichB BsendsB BoffB BaB
Brequest.B BItB BawaitsB BtheB BrequestB Btype,B BtheB BtargetB BnestB Bname,B BandB
BtheB BrequestedB BcontentB BasB BitsB BfirstB BthreeB Barguments,B BandB BitB BexpectsB
BaB BfunctionB BtoB BcallB BwhenB BaB BreplyB BcomesB BinB BasB BitsB BfourthB BandB BlastB
Bargument.
bigOak.send("CowB BPasture",B B"note",B B"Let'sB BcawB BloudlyB BatB B7PM",
()B B=>B Bconsole.log("NoteB Bdelivered."));
ButB BtoB BmakeB BsureB BnestB BcanB BreceiveB BthatB Brequest,B ByouB BmustB BstateB BaB
BrequestB BtypeB BnamedB B"note."B BTheB BcodeB BthatB BcontrolsB BtheB BrequestsB
BthatB BneedB BtoB BrunB Band,B BonB BallB Bnests,B BcanB BreceiveB BthisB BtypeB BofB
Bmessages.B BLetB BusB BstateB BthatB BaB BcrowB BfliesB BoverB BandB BinstallsB BourB
BhandlerB BcodeB BonB BallB BtheB Bnests.
importB B{defineRequestType}B BfromB B“.B B/crow-tech";
defineRequestType("note",B B(nest,B Bcontent,B Bsource,B Bdone)B B=>B B{
console.log(`${nest.name}B BreceivedB Bnote:B B${content}`);
done();
});
TheB BdefineRequestTypeB BfunctionB BdescribesB BaB BnewB BtypeB BofB Brequest.B
TheB BexampleB BattachesB BsupportB BforB B"note"B BrequestsB BthatB BsendsB BaB
B

noteB BtoB BaB BstatedB Bnest.B BOurB BimplementationB BcallsB Bconsole.logB BsoB
B

thatB BweB BcanB BcheckB BifB BtheB BrequestB BhasB Barrived.B BNestsB BconsistB BofB BaB
B

nameB BpropertyB BthatB BholdsB BitsB Bname.B BTheB BfourthB BargumentB BstatedB
B

toB BtheB Bhandler,B Bdone,B BisB BaB BcallbackB BfunctionB BthatB BcallsB BwhenB BitB
B

hasB BcompletedB BtheB Btask.B BIfB ByouB BuseB BtheB Bhandler’sB BreturnB BvalueB BasB
B

theB BvalueB BofB BtheB Bresponse,B BthatB BmeansB BthatB BaB BrequestB BhandlerB
B

can’tB BexecuteB BasynchronousB BactionsB Bitself.B BAB BfunctionB BperformingB


B

asynchronousB BactionsB BreturnsB BbeforeB BtheB BtaskB Bcompletes,B BhavingB BaB


B

callbackB BreadyB BtoB BbeB BcalledB BuponB BwhenB BitB Bfinishes.B BInB BaB Bway,B
B

asynchronicityB BisB Bcontagious.B BAB BfunctionB BthatB BcallsB BaB BfunctionB BthatB
B

performsB BasynchronouslyB BmustB BbeB BasynchronousB Bitself,B ButilizingB BaB


B

callbackB BtoB BdeliverB BitsB Bresult.B BCallingB BaB BcallbackB BisB Berror-proneB
B

andB BmoreB BinvolvedB BthanB BsimplyB BsendingB BbackB BaB Bvalue.


B

Promises

WorkingB BwithB BabstractB BmethodsB BisB BsimplerB BwhenB BvaluesB BrepresentB


theB Bmethods.B BInB BtheB BcaseB BofB BasynchronousB Bactions,B BinsteadB BofB
B

makingB BpreparationsB BforB BaB BfunctionB BtoB BbeB BcalledB BatB BaB BcertainB
B

pointB BinB BtheB Bfuture,B BsendB BbackB BanB BobjectB BthatB BstandsB BforB BtheB
B

futureB Bevent.B BAB BpromiseB BisB BanB BasynchronousB BactionB BthatB BcanB
B

finishB BatB BsomeB BpointB BandB BprovideB Bvalue.B BItB BcanB BnotifyB BanyoneB
B

interestedB BwhenB BitsB BvalueB BisB Bavailable.B BTheB BsimplestB BwayB BtoB BbuildB
B

aB BpromiseB BisB BbyB BcallingB BPromise.resolve.B BThisB BfunctionB BguaranteesB


B

thatB BtheB BvalueB ByouB BsetB BenclosesB BinB BaB Bpromise.B BIfB BitB BisB BaB BpromiseB
B

Balready,B BitB Breturns.B BOtherwise,B BaB BnewB BpromiseB BwillB BbeB BcreatedB
BinstantlyB BwithB ByourB BvalueB BasB BaB Bresult.

letB BfifteenB B=B BPromise.resolve(15);


fifteen.then(valueB B=>B Bconsole.log(`GotB B${value}`));
//B B→B BGotB B15
ToB BachieveB BtheB BresultB BofB BaB Bpromise,B ButilizeB BitsB BformerB Bmethod.B BItB
BindicatesB BanB BintendedB BcallbackB BfunctionB BwhenB BtheB BpromiseB BsolvesB
BandB BprovidesB BaB Bvalue.B BYouB BcanB BattachB BseveralB BcallbacksB BtoB BanB
BindividualB Bpromise,B BandB BtheyB BwillB BcallB BtheB Bcallbacks,B BevenB BifB BtheyB
BwereB BattachedB BwhenB BtheB BpromiseB BhasB BbeenB Bcompleted.B BTheB BthenB
BmethodB BalsoB BsendB BbackB BanotherB BpromiseB BthatB BsolvesB BtheB BvalueB
BthatB BtheB BhandlerB BfunctionB Breturns.B BItB BisB BimportantB BtoB BseeB BpromisesB
BasB BaB BdeviceB BtoB BturnB BvaluesB BintoB BanB BasynchronousB Breality.B BAB
BpromisedB BvalueB BisB BaB BvalueB BthatB BcouldB BbeB BthereB BorB BcouldB BdisplayB
BatB BaB BcertainB BpointB BinB BtheB Bfuture.B BComputationsB BdescribedB BinB BtermsB
BofB BpromisesB BworkB BonB BenclosedB BvaluesB BandB BareB BperformedB
BasynchronouslyB BasB BtheB BvaluesB BbecomeB Bavailable.B BToB BbuildB BaB
Bpromise,B BuseB BtheB BPromiseB BasB BaB Bconstructor.B BItB BcontainsB BanB BoddB
Blayout,B BandB BtheB BconstructorB BexpectsB BaB BfunctionB BasB BanB Bargument,B
BwhichB BitB BcallsB Binstantly,B BsendingB BitB BaB BfunctionB BthatB BcanB BbeB BusedB
BtoB BsolveB BtheB Bpromise.B BItB BisB BhowB BtoB BbuildB BaB Bpromise-basedB BlayoutB
BforB BtheB BreadStorageB Bfunction:
functionB Bstorage(nest,B Bname)B B{
returnB BnewB BPromise(resolveB B=>B B{
nest.readStorage(name,B BresultB B=>B Bresolve(result));
});
}

storage(bigOak,B B"enemies")
.then(valueB B=>B Bconsole.log("Got",B Bvalue));
ThisB BasynchronousB BfunctionB BreturnsB BaB BsignificantB Bvalue.
Failure

JavaScriptB BcomputingB BcanB BfailB BbyB BoutputtingB BanB Bexception.B BAB


networkB
B requestB
B BcouldB Bfail,B orB
B someB
B asynchronousB
B codeB
B

computationB BcouldB BbringB BanB Bexception.B BAsynchronousB BprogrammingB


B

callbackB BstyleB BmostB BconsistentB BissuesB BareB BthatB BitB BmakesB BitB BveryB
B

hardB BtoB BensureB BfailuresB BrevealB BcorrectlyB BtoB BtheB Bcallbacks.B BAB
B

generallyB BusedB BmethodB BisB BthatB BtheB BfirstB BargumentB BtoB BtheB BcallbackB
B

isB BusedB BtoB BspecifyB BtheB BfailedB Baction,B BandB BtheB BsecondB BhasB BtheB
B

valueB BprovidedB BbyB BtheB BactionB BwhenB BitB Bcompletes.B BSuchB BcallbackB
B

functionsB BalwaysB BcheckB BifB BtheyB BobtainB BanB BexceptionB BandB BensureB
B

thatB BanyB BuprisingB Bproblems,B BincludingB BexceptionsB BoutputB BbyB


B

functionsB BtheyB Bcall,B BareB BgivenB BtoB BtheB BcorrectB Bfunction.B BTheyB BcanB
B

reduceB BwhenB BitB BcompletesB BsuccessfullyB BorB BdeclinedB BwhenB BitB Bfails.B
B

CallB BReduceB BhandlersB BitB BonlyB BwhenB BtheB BtaskB BcompletesB BsuccessfullyB
B

andB BdeclinesB BautomaticallyB BgeneratedB BtoB BtheB BreturnedB BnewB


B

promise.B BAndB BwhenB BaB BhandlerB BoutputsB BanB Bexception,B BthisB


B

automaticallyB BtriggersB BtheB BpromiseB BprovidedB BbyB BitsB BrecentB BcallB


B

declines.B BWhenB BanB BelementB BinB BaB BchainB BofB BasynchronousB BactionsB
B

fails,B BtheB BoutputB BofB BtheB BwholeB BchainB BdeclinesB BandB BnoB BsuccessB
B

handlersB BcallB BpastB BtheB BfailingB Bpoint.B BMuchB BlikeB BsolvingB BaB BpromiseB
B

producesB BaB Bvalue,B BrejectingB BoneB BalsoB BprovideB Bone,B BoftenB BcalledB BtheB
B

rejectionB Breason.B BIfB BanB BexceptionB BinB BaB BhandlerB BfunctionB BcreatesB
B

theB Brejection,B BuseB BtheB BexceptionB BvalueB BasB BtheB Breason.B BComparably,B
B

whenB BaB BhandlerB BsendsB BbackB BaB BrejectedB Bpromise,B BthatB BrejectionB
B

goesB BintoB BtheB BnextB Bpromise.B BThere’sB BaB BPromise.B BRejectB BfunctionB
B

thatB BdevelopsB BaB Bnew,B BinstantlyB BdeclinedB Bpromise.


B

IfB BaB BcatchB BhandlerB BoutputB BanB Berror,B BtheB BnewB BpromiseB BisB BequallyB
declined.B BInB Bshorthand,B BthenB BalsoB BtakeB BaB BdeclineB BhandlerB BasB BaB
B
secondB Bargument,B BsoB ByouB BshouldB BinstallB BtheB BtwoB BtypesB BofB BhandlersB
B

inB BanB BindividualB BmethodB Bcall.B BAB BfunctionB BsentB BtoB BtheB BPromiseB
B

constructorB BacceptsB BaB BsecondB Bargument,B BtogetherB BwithB BtheB BresolveB


B

function,B BwhichB BitB BcanB BuseB BtoB BdeclineB BtheB BnewB Bpromise.B BTheB
B

chainsB BofB BpromiseB BvaluesB BdevelopedB BbyB BcallsB BtoB BthenB BandB BcatchB
B

recognizedB BasB BaB BpipelineB BasynchronousB BvaluesB BorB BfailuresB BmoveB


B

through.B BBecauseB BthoseB BchainsB BbuiltB BbyB BregisteringB Bhandlers,B BeveryB


B

linkB BconsistsB BofB BeitherB BbothB BorB BaB BsuccessB BhandlerB BorB BaB BrejectionB
B

handlerB BrelatedB BtoB Bit.B BHandlersB BthatB BdoB BnotB BmatchB BtheB BtypeB BofB
B

outputB Bdeclined.B BButB BthoseB BthatB BmatchB BgetsB Bcalled,B BandB BtheirB
B

outputB BdecidesB BwhatB BtypeB BofB BvalueB BcomesB Bnext,B BsuccessB BwhenB BitB
B

sendsB BbackB BaB Bnon-promiseB Bvalue,B BrejectionB BwhenB BitB BoutputB BanB
B

exception,B BandB BtheB BresultB BofB BaB BpromiseB BwhenB BitB BsendsB BbackB BoneB
B

ofB Bthose.
B

newB BPromise((_,B Breject)B B=>B Breject(newB BError("Fail")))


.then(valueB B=>B Bconsole.log("HandlerB B1"))
.catch(reasonB B=>B B{
console.log("CaughtB BfailureB B"B B+B Breason);
returnB B"nothing";
})

.then(valueB B=>B Bconsole.log("HandlerB B2",B Bvalue));


//B B→B BCaughtB BfailureB BError:B BFail
//B B→B BHandlerB B2B Bnothing
NetworksB BareB Bhard
Periodically,B Bthere'sB BveryB BlittleB BlightB BforB BtheB Bcrows’B BmirrorB BsystemsB
toB BconveyB BaB BsignalB BisB BobstructingB BtheB BwayB BofB BtheB Bsignal.B BItB BisB
B

viableB BforB BaB BsignalB BtoB BbeB BtransferredB BbutB BgotB Bdeclined.B BOften,B
B
BtransmissionB BfailuresB BareB BunexpectedB Baccidents,B BlikeB BaB Bcar’sB
BheadlightB BobstructB BtheB BlightB Bsignals,B BandB BresendingB BtheB BrequestB
BcouldB BmakeB BitB Bsucceed.B BSo,B Blet’sB BcreateB BourB BrequestB Bfunction,B BandB
BconsequentlyB BretryB BtheB BsendingB BofB BtheB BrequestB BmoreB BtimeB BbeforeB
BitB Bstops.B BAnd,B BsinceB BweB BhaveB BestablishedB BthatB BpromisesB BareB Bgood,B
Bwe’llB BalsoB BensureB BourB BrequestB BfunctionB BsendsB BbackB BaB Bpromise.B
BWhenB BitB BcomesB BtoB BwhatB BtheyB BcanB Bindicate,B BpromisesB BandB BcallbacksB
BareB Bequal.B BCallback-basedB BfunctionsB BareB BenclosedB BtoB BuncoverB BaB
Bpromise-basedB BlayoutB BandB BviceB Bversa.B BEvenB BwhenB BaB BrequestB BandB
BitsB BreplyB BconveyB Bsuccessfully,B BtheB BreplyB BcouldB BspecifyB Bfailure,B BforB
Binstance,B BifB BtheB BrequestB BtriesB BtoB ButilizeB BaB BrequestB BtypeB BthatB BhasB
BnotB BbeenB BdescribedB BorB BtheB BhandlerB BoutputB BanB Berror.B BToB BaidB Bthis,B
BsendB BandB BdefineRequestTypeB BfollowB BtheB BconventionB BdeclaredB
Bearlier,B BwhereB BtheB BfirstB BargumentB BsentB BtoB BcallbacksB BisB BtheB BreasonB
BforB BfailureB BifB Bany,B BandB BtheB BsecondB BisB BtheB BDefiniteB Bresult.B BTheyB BareB
BinterpretedB BtoB BpromiseB BresolutionB BandB BrejectionB BbyB BourB Bwrapper.
classB BTimeoutB BextendsB BErrorB B{}
functionB Brequest(nest,B Btarget,B Btype,B Bcontent)B B{
returnB BnewB BPromise((resolve,B Breject)B B=>B B{
letB BdoneB B=B Bfalse;
functionB Battempt(n)B B{
nest.send(target,B Btype,B Bcontent,B B(failed,B Bvalue)B B=>B B{
doneB B=B Btrue;
ifB B(failed)B Breject(failed);
elseB Bresolve(value);
});

setTimeout(()B B=>B B{
ifB B(done)B Breturn;
elseB BifB B(nB B<B B3)B Battempt(nB B+B B1);
elseB Breject(newB BTimeout("TimedB Bout"));
},B B250);
}
attempt(1);
});
}

BecauseB BpromisesB BcanB BbeB BacceptedB BorB BdeclinedB BonceB Bonly,B BitB BwillB
Bwork.B BTheB BfirstB BtimeB BresolveB BorB BrejectB BcallB BdecidesB BtheB BresultB BofB
BtheB Bpromise,B BandB BanyB BotherB Bcalls,B BareB Bdisregarded.B BToB BcreateB BanB
BasynchronousB Bloop,B BforB BtheB Bretries,B BuseB BaB BrecursiveB Bfunction,B BanB
BefficientB BloopB BdoesB BnotB BallowB BusB BtoB BstopB BandB BwaitB BforB BanB
BasynchronousB Baction.B BTheB BattemptB BfunctionB BcreatesB BaB BsingleB
BattemptB BtoB BtransferB BaB Brequest.B BItB BalsoB BspecifiesB BaB BtimeoutB Bthat,B BifB
BthereB BisB BcomebackB BresponseB BafterB B250B Bmilliseconds,B BbeginsB BtheB
BnextB BattemptB Bor,B BifB BitB BisB BtheB BfourthB Btry,B BdeclinesB BtheB BpromiseB
BwithB BanB BinstanceB BofB BTimeoutB BbeingB BtheB Breason.B BRetryingB BeachB
Bquarter-secondB BandB BstopsB BwhenB BthereB BisB BnoB BresponseB BafterB BaB
BsecondB BisB BcertainlyB BarbitraryB BifB BtheB BrequestB BshowsB Bup,B BbutB BtheB
BhandlerB BtakesB BlongerB BforB BrequestsB BtoB BtransferB BseveralB Btimes.B BCreateB
ByourB BhandlersB BwithB BthatB BproblemB BinB Bmind,B BandB BcoupledB BmessagesB

BareB BnotB Bharmful.B BToB BsegregateB BourselvesB BfromB BcallbacksB Btotally,B


BdefineB BaB BcoverB BforB BdefineRequestTypeB BthatB BenablesB BtheB BhandlerB
BfunctionB BtoB BsendB BbackB BaB BpromiseB BorB BsimpleB BvalueB BandB BwiresB BthatB
BdoB BtheB BcallbackB BforB Bus.
functionB BrequestType(name,B Bhandler)B B{
defineRequestType(name,B B(nest,B Bcontent,B Bsource,
callback)B B=>B B{
tryB B{
Promise.resolve(handler(nest,B Bcontent,B Bsource))
.then(responseB B=>B Bcallback(null,B Bresponse),
failureB B=>B Bcallback(failure));
}B BcatchB B(exception)B B{
callback(exception);
}
});
}

Promise.resolveB BisB BusedB BtoB BtransformB BtheB BreturnedB BvalueB BbyB BtheB
BhandlerB BtoB BaB BpromiseB BifB BitB BisB BnotB Bready.
Collections of promises
BB BB

EveryB BnestB BcomputerB BstoresB BanB BarrayB BofB BotherB BnestsB BinsideB
BtransmissionB BdistanceB BinB BitsB Bneighbor’sB Bproperty.B BToB BexamineB
BwhichB BisB Breachable,B BwriteB BaB BfunctionB BthatB BtriesB BtoB BtransferB BaB
B"ping"B BrequestB B(requestB BthatB BdemandsB BaB Bresponse)B BtoB BallB BofB BthemB
BandB BcheckB BforB BwhichB BonesB BcomeB Bback.B BIfB Byou'reB BworkingB BwithB BaB
BgroupB BofB BpromisesB BrunningB BatB Bonce,B BtheB BPromise.allB BfunctionB BisB
BveryB Bimportant.B BItB BsendsB BbackB BaB BpromiseB BthatB BholdsB BonB BforB BallB BofB
BtheB BpromisesB BinB BtheB BarrayB BtoB BreconcileB BandB BthenB BsettleB BtoB BanB
BarrayB BofB BtheB BvaluesB BthatB BtheseB BpromisesB Bprovided.B BIfB BanyB BpromiseB
BisB Bdeclined,B BtheB BresultB BofB BPromise.allB BisB BalsoB Bdeclined.
requestType("ping",B B()B B=>B B"pong");
functionB BavailableNeighbors(nest)B B{
letB BrequestsB B=B Bnest.neighbors.map(neighborB B=>B B{
returnB Brequest(nest,B Bneighbor,B B"ping")
.then(()B B=>B Btrue,B B()B B=>B Bfalse);
});

returnB BPromise.all(requests).then(resultB B=>B B{


returnB Bnest.neighbors.filter((_,B Bi)B B=>B Bresult[i]);
});
}

NetworkB Bflooding
NestsB BcanB BcommunicateB BwithB BtheirB BneighborsB BonlyB BandB BthatB BgreatlyB
BaffectsB BtheB BsignificanceB BofB BthisB Bnetwork.B BToB BbroadcastB BinformationB
BtoB BtheB BentireB Bnetwork,B BaB BsolutionB BisB BtoB BcreateB BaB BtypeB BofB BrequestB
BthatB BisB BsentB BautomaticallyB BtoB Bneighbors.B BTheseB BneighborsB BthenB
BsendB BitB BtoB BtheirB BneighborsB BuntilB BtheB BentireB BnetworkB BhasB BcollectedB
BtheB Bmessage.
importB B{everywhere}B BfromB B“.B B/crow-tech";
everywhere(nestB B=>B B{
nest.state.gossipB B=B B[];
});

functionB BsendGossip(nest,B Bmessage,B BexceptForB B=B Bnull)B B{


nest.state.gossip.push(message);

forB B(letB BneighborB BofB Bnest.neighbors)B B{


ifB B(neighborB B==B BexceptFor)B Bcontinue;
request(nest,B Bneighbor,B B"gossip",B Bmessage);
}
}

requestType("gossip",B B(nest,B Bmessage,B Bsource)B B=>B B{


ifB B(nest.state.gossip.include(message))B Breturn;
console.log(`${nest.name}B BreceiveB BgossipB B'${
messages}'B BfromB B${source}`);
sendGossip(nest,B Bmessage,B Bsource);
});

YouB BcanB BavoidB BtransferringB BtheB BsimilarB BmessageB BacrossB BtheB


BnetworkB Bforever,B BeveryB BnestB BsavesB BanB BarrayB BofB BgossipB BstringsB BthatB
BitB BhasB Bseen.B BToB BdescribeB BthisB Barray,B BusesB BtheB BeverywhereB BfunctionB
BthatB BrunsB BcodeB BonB BeachB BnestB BtoB BattachB BaB BpropertyB BtoB BtheB Bnest’sB
BstateB Bobject.
MessageB Brouting
IfB BaB BsetB BnodeB BwantsB BtoB BcommunicateB BwithB BaB BsingleB BotherB Bnode.B
BTheB BbestB BapproachB BisB BtoB BbuildB BaB BpathB BforB BmessagesB BtoB BjumpB BfromB
BnodeB BtoB BnodeB BuntilB BtheyB BgetB BtoB BtheirB Bdestination.B BYouB BneedB BtoB
BunderstandB BtheB BinterfaceB BofB BtheB Bnetwork.B BToB BsendB BaB BrequestB BtoB BaB
BnestB BatB BaB Bdistance,B BitB BisB BimportantB BtoB BknowB BwhichB BneighboringB
BnestB BcanB BgetB BtheB BjobB Bdone.B BEveryB BnestB BknowsB BaboutB BitsB BdirectB
BneighborsB Bonly,B BitB BcannotB BcomputeB BaB Broute,B BitB BlacksB BtheB
Binformation.B BYouB BmustB BunderstandB BhowB BtoB BspreadB BtheB BinformationB
BaboutB BtheseB BconnectionsB BtoB BeveryB BnestB BinB BaB BwayB BthatB BenablesB BitB
BtoB BtransformB BwithB Btime,B BwhenB BnewB BnestsB BareB Bcreated.B BNowB ByouB
BcanB BuseB Bflooding,B BbutB BinsteadB BofB BcheckingB BwhetherB BaB BmessageB BhasB
BbeenB Bcollected,B BnowB BcheckB BifB BtheB BnewB BsetB BofB BneighborsB BforB BaB
BgivenB BnestB BisB BsimilarB BtoB BtheB BcurrentB Bset.
requestType("connections",B B(nest,B B{name,B Bneighbors},
source)B B=>B B{
letB BconnectionsB B=B Bnest.state.connections;
ifB B(JSON.stringify(connections.get(name))B B==
JSON.stringify(neighbors))B Breturn;
connections.set(name,B Bneighbors);
broadcastConnections(nest,B Bname,B Bsource);
});

functionB BbroadcastConnections(nest,B Bname,B BexceptForB B=B Bnull)B B{


forB B(letB BneighborB BofB Bnest.neighbors)B B{
ifB B(neighborB B==B BexceptFor)B Bcontinue;
request(nest,B Bneighbor,B B"connections",B B{
name,

neighbors:B Bnest.state.connections.get(name)
});
}
}

everywhere(nestB B=>B B{
nest.state.connectionsB B=B BnewB BMap;
nest.state.connection.set(nest.name,B Bnest.neighbors);
broadcastConnections(nest,B Bnest.names);
});

TheB BcomparisonB ButilizesB BJSON.stringifyB BbecauseB B==,B BonB BobjectsB BorB


Barrays,B BwillB BsendB BbackB BtrueB BwhenB BtheB BvalueB BofB BtheB BtwoB BareB BtheB
BsameB Bonly.B BDifferentiatingB BtheB BJSONB BstringsB BisB BaB BveryB BsuccessfulB
BwayB BtoB BcompareB BtheirB Bcontent.B BTheB BnodesB BinstantlyB BbeginB
BtransmittingB BtheirB BconnectionsB BexceptB BtoB BtheB BunreachableB Bnests,B
BwhichB BgiveB BthemB BaB BmapB BofB BtheB BexistingB BnetworkB Bgraph.B BTheB
BfindRouteB BfunctionB BfindsB BaB BpathB BtoB BreachB BaB BsetB BnodeB BwithinB BtheB
Bnetwork.B BButB BinsteadB BofB BsendingB BbackB BtheB BwholeB Broute,B BitB BjustB
BbringsB BbackB BtheB BnextB Bstep.B BThatB BnextB BnestB BwillB BuseB BitsB BexistingB
informationB BaboutB BtheB Bnetwork,B BdetermineB BwhereB BitB BtransfersB BtheB
B

message.
B

functionB BfindRoute(from,B Bto,B Bconnections)B B{


letB BworkB B=B B[{at:B Bfrom,B Bvia:B Bnull}];
forB B(letB BIB B=B B0;B BIB B<B Bwork.length;B Bi++)B B{
letB B{at,B Bvia}B B=B Bwork[i];
forB B(letB BnextB BofB Bconnections.get(at)B B||B B[])B B{
ifB B(nextB B==B Bto)B BreturnB Bvia;
ifB B(!work.some(wB B=>B Bw.atB B==B Bnext))B B{
work.push({at:B Bnext,B Bvia:B BviaB B||B Bnext});
}
}
}

returnB Bnull;
}

YouB BcanB BnowB BcreateB BaB BfunctionB BthatB BcanB BsendB BmessagesB BtoB BlongB
distance.B BIfB BtheB BmessageB BisB BattachedB BtoB BaB BdirectB Bneighbor,B BitB BisB
B

conveyedB BasB Busual.B BIfB Bnot,B BitB BisB BwrappedB BinB BanB BobjectB BandB
B

transferredB BtoB BaB BneighborB BcloserB BtoB BtheB Btarget,B BthroughB BtheB
B

"route"B BrequestB Btype,B BthatB BwillB BmakeB BthatB BneighborB BrepeatB BtheB
B

sameB Bcharacter.
B

functionB BrouteRequest(nest,B Btarget,B Btypes,B Bcontent)B B{


ifB B(nest.neighbors.includes(target))B B{
returnB Brequest(nest,B Btarget,B Btypes,B Bcontent);
}B BelseB B{
letB BviaB B=B BfindRoute(nest.name,B Btarget,
nest.state.connections);

ifB B(!via)B BthrowB BnewB BError(`NoB BroutesB BtoB B${target}`);


returnB Brequest(nest,B Bvia,B B"route",
{target,B Btype,B Bcontent});
}
}

requestType("route",B B(nest,B B{target,B Btype,B Bcontent})B B=>B B{


returnB BrouteRequest(nest,B Btarget,B Btype,B Bcontent);
});

WeB BhaveB BcreatedB BdifferentB BlayersB BofB BfunctionalityB BatB BtheB BtopB BofB BaB
BprimaryB BcommunicationB BsystemB BtoB BenableB BeasyB Buse.B BThisB BisB BaB
BsimplifiedB BmodelB BofB BhowB BcomputerB BnetworksB Bwork.
AsyncB Bfunctions
ToB BsaveB BsignificantB Binformation,B BcrowsB BuseB BtheB BduplicationB Bmethod,B
BtheyB BduplicateB BitB BacrossB Bnests.B BThatB Bway,B BwhenB BaB BbirdB BdismantlesB
BaB Bnest,B BtheB BinformationB BwouldB BnotB BbeB Blost.B BToB BrecoverB BaB
BparticularB BpieceB BofB BinformationB BthatB BhasB BnoB BstorageB Bbulb,B BaB BnestB
BcomputerB BwouldB BtalkB BtoB BrandomB BotherB BnestsB BinB BtheB BnetworkB BuntilB
BtheB BoneB BthatB BhasB BitB BisB Bfound.
requestType("storage",B B(nest,B Bname)B B=>B Bstorage(nest,B Bname));
functionB BfindInStorage(nest,B Bname)B B{
returnB Bstorage(nest,B Bname).then(foundB B=>B B{
ifB B(foundB B!=B Bnull)B BreturnB Bfound;
elseB BreturnB BfindInRemoteStorage(nest,B Bname);
});
}

functionB Bnetwork(nest)B B{
returnB BArray.from(nest.state.connections.keys());
}

functionB BfindInRemoteStorage(nest,B Bname)B B{


letB BsourcesB B=B Bnetwork(nest).filter(nB B=>B BnB B!=B Bnest.name);
functionB Bnext()B B{
ifB B(sources.lengthB B==B B0)B B{
returnB BPromise.reject(newB BError("NotB Bfound"));
}B BelseB B{
letB BsourceB B=B Bsources[Math.floor(Math.random()B B*
sources.length)];

sourcesB B=B Bsources.filter(nB B=>B BnB B!=B Bsource);


returnB BrouteRequest(nest,B Bsource,B B"storage",B Bname)
.then(valueB B=>B BvalueB B!=B BnullB B?B BvalueB B:B Bnext(),
next);
}
}

returnB Bnext();
}

Object.keysB BcannotB BworkB BonB BconnectionsB BbecauseB BitB BisB BaB BMap.B BItB
containsB BaB BkeyB Bmethod,B BbutB BthatB BsendsB BbackB BanB BiteratorB BinsteadB
B

ofB BanB Barray.B BAnB BiteratorB BcanB BbeB BtransformedB BtoB BanB BarrayB BusingB
B

theB BArray.fromB Bfunction.B BVariousB BasynchronousB BactionsB BareB BtiedB


B

togetherB BinB BunclearB Bways.B BNowB ByouB BneedB BaB BrecurringB BfunctionB BtoB
B

modelB BloopingB BacrossB BtheB Bnests.B BInB BaB BsynchronousB BprogrammingB


B

model,B BitB BisB BeasyB BtoB Bexpress.B BJavaScriptB BalsoB BletsB ByouB BwriteB
B

pseudo-synchronousB BcodeB BtoB BdefineB BasynchronousB Bcomputation.B BAnB


B

asyncB BfunctionB BisB BaB BfunctionB BthatB BcompletelyB BbringB BbackB BaB
B
promiseB BandB BthatB BcanB BwaitB BforB BotherB BpromisesB BinB BaB BsynchronousB
B

way.B BRewriteB BfindInStorageB BlikeB Bthis:


B

asyncB BfunctionB BfindInStorage(nest,B Bname)B B{


letB BlocalB B=B BawaitB Bstorage(nest,B Bname);
ifB B(localB B!=B Bnull)B BreturnB Blocal;
letB BsourcesB B=B Bnetwork(nest).filter(nB B=>B BnB B!=B Bnest.name);
whileB B(sources.lengthB B>B B0)B B{
letB BsourceB B=B Bsources[Math.floor(Math.random()B B*
sources.length)];

sourcesB B=B Bsources.filter(nB B=>B BnB B!=B Bsource);


tryB B{
letB BfoundB B=B BawaitB BrouteRequest(nest,B Bsource,B B"storage",
name);

ifB B(foundB B!=B Bnull)B BreturnB Bfound;


}B BcatchB B(_)B B{}
}

throwB BnewB BError("NotB Bfound");


}

AnB BasyncB BfunctionB BisB BmarkedB BwithB BtheB BwordB BasyncB BandB BthenB BtheB
functionB Bkeyword.B BMethodsB BcanB BalsoB BbecomeB BasyncB BbyB BwritingB
B

asyncB BbeforeB BtheirB Bname.B BWhenB BtheB BfunctionB BorB BmethodB BisB Bcalled,B
B

itB BbringsB BbackB BaB Bpromise.B BWhenB BtheB BbodyB BreturnsB Bsomething,B BthatB
B

promiseB BisB Bsettled.B BIfB BitB BoutputsB BanB Bexception,B BtheB BpromiseB BisB
B

declined.B BWithinB BanB BasyncB Bfunction,B BtheB BwordB BawaitB BisB BsetB BinB
B

frontB BofB BanB BexpressionB BtoB BawaitB BaB BpromiseB BtoB BgetB BsettledB BandB
B

onlyB BthenB BproceedsB BtoB BexecuteB BtheB Bfunction.B BSuchB BfunctionsB


B

cannotB BrunB BfromB BstartB BtoB BfinishB BatB Bonce,B BbutB BitB BcanB BbeB BfrozenB BatB
B
pointsB BandB BcanB BrestartB Blater.B BForB Bnon-trivialB BasynchronousB Bcode,B
B

thisB BnotationB BisB BeasierB BthanB BdirectlyB BthroughB Bpromises.


B

Generators

AsyncB BfunctionsB BdoB BnotB BhaveB BtoB BbeB BpausedB BandB BthenB BresumedB
again.B BJavaScriptB BconsistsB BofB BaB BfeatureB BcalledB BgeneratorB Bfunctions.B
B

TheseB BareB BidenticalB BbutB BdoB BnotB BcontainB BtheB Bpromises.B BWhenB ByouB
B

callB BaB BfunctionB BwithB Bfunction*B B(putB BanB BasteriskB BafterB BtheB BwordB
B

function),B BitB BchangesB BtoB BaB Bgenerator.B BWhenB ByouB BcallB BaB Bgenerator,B
B

itB BsendsB BbackB BanB Biterator.


B

function*B Bpowers(n)B B{
forB B(letB BcurrentB B=B Bn;;B BcurrentB B*=B Bn)B B{
yieldB Bcurrently;
}
}

forB B(letB BpowerB BofB Bpowers(3))B B{


ifB B(powerB B>B B50)B Bbreak;
console.log(power);
}

//B B→B B3
//B B→B B9
//B B→B B27
Normally,B BifB ByouB BcallB Bpowers,B BtheB BfunctionB BisB BfrozenB BatB BtheB
beginning.B BEachB BtimeB ByouB BcallB BnextB BonB BtheB Biterator,B BtheB BfunctionB
B

willB BrunB BuntilB BitB BhitsB BaB ByieldB Bexpression,B BwhichB BwillB BpauseB BitB BandB
B

makeB BtheB ByieldedB BvalueB BtheB BnextB BvalueB BprovidedB BbyB BtheB Biterator.B
B

WhenB BtheB BfunctionB Breturns,B BtheB BiteratorB Bcompletes.B BWritingB


B
BiteratorsB BisB BsimpleB BwhenB ByouB ButilizeB BtheB BgeneratorB Bfunctions.B
BWriteB BtheB BiteratorB BforB BtheB BGroupB BclassB BwithB BthisB Bgenerator:
Group.prototype[Symbol.iterator]B B=B Bfunction*()B B{
forB B(letB BiB B=B B0;B BiB B<B Bthis.members.length;B BI++)B B{
yieldB Bthis.members[i];
}
};

There’sB BnoB BneedB BtoB BbuildB BanB BobjectB BtoB BholdB BtheB BiterationB Bstate,B
BandB BgeneratorsB BstoreB BtheirB BlocalB BstateB BimmediatelyB BandB BtheyB ByieldB
BeveryB Btime.B BThisB ByieldB BexpressionB BcanB BhappenB BonlyB BdirectlyB BwithinB
BtheB BgeneratorB BfunctionB BandB BnotB BinB BanB BinnerB BfunctionB BthatB ByouB BsetB
BwithinB Bit.B BTheB BgeneratorB BsavesB BwhenB Byielding.B BThisB BisB BitsB BlocalB
BenvironmentB BandB BtheB BpositionB BwhereB BitB Byields.B BAnB BasyncB BfunctionB
BisB BaB BuniqueB BkindB BofB Bgenerator.B BItB BcreatesB BaB BpromiseB BwhenB Bit’sB
Bcalled,B BwhichB BresolvesB BwhenB BitB BcompletesB BandB BdeclinesB BwhenB BitB
BoutputsB BanB Bexception.B BAnytimeB BitB ByieldsB BaB Bpromise,B BtheB BresultB BofB
BthatB BpromiseB BwillB BbeB BtheB BresultB BofB BtheB BawaitB Bexpression.
The event loop
BB BB

AsynchronousB BprogramsB BperformB BoneB BbyB Bone.B BEveryB BpieceB BmayB


BbeginB BaB BfewB BactionsB BandB BarrangeB BcodeB BtoB BexecuteB BwhenB BtheB
BactionB BcompletesB BorB Bfails.B BBetweenB BtheseB Bpieces,B BtheB BprogramB BdoesB
Bnothing,B BawaitingB BtheB BnextB Baction.B BSoB ByouB BcannotB BcallB BcallbacksB
BbyB BtheB BcodeB BthatB BarrangedB Bthem.B BIfB ByouB BcallB BsetTimeoutB BfromB
BinsideB BaB Bfunction,B BthatB BfunctionB BwillB BhaveB BbeenB BsentB BbackB BbeforeB
BtheB BcallbackB BfunctionB BgetsB Bcalled.B BAsynchronousB BcharacterB BoccursB
BonB BitsB BemptyB BfunctionB BcalledB Bstack.B BSinceB BeachB BcallbackB BbeginsB
withB BanB BemptyB Bstack,B ByourB BcatchB BhandlersB BwillB BnotB BbeB BonB BtheB
B

stackB BwhenB BanB BexceptionB Bruns.


B

tryB B{
setTimeout(()B B=>B B{
throwB BnewB BError("Woosh");
},B B20);
}B BcatchB B(_)B B{
//B BThisB BwillB BnotB Brun
console.log("Caught!");
}

NoB BmatterB BhowB BeventsB BlikeB BtimeoutsB BorB BincomingB BrequestsB Boccur,B
aB BJavaScriptB BenvironmentB BrunsB BoneB BprogramB BatB Bonce.B BWhenB
B

there’sB BnothingB BtoB Bdo,B BtheB BloopB Bstops.B BButB BasB BeventsB BcomeB Bin,B
B

theyB BareB BattachedB BtoB BaB Bqueue,B BandB BtheirB BcodeB BperformsB BoneB BafterB
B

other.B BBecauseB BtwoB BthingsB BdoB BnotB BrunB BatB Bonce,B Bslow-runningB BcodeB
B

mayB BholdB BupB BtheB BhandlingB BofB BotherB Bevents.B BTheB BbelowB BexampleB
B

setsB BaB BtimeoutB BbutB BalsoB BlingersB BuntilB BafterB BtheB Btimeout’sB BfixedB
B

pointB BofB Btime,B BmakingB BtheB BtimeoutB BtoB BbeB Blate.


B

letB BstartB B=B BDate.now();


setTimeout(()B B=>B B{
console.log("TimeoutB BranB Bat",B BDate.now()B B-B Bstart);
},B B20);
whileB B(Date.now()B B<B BstartB B+B B50)B B{}
console.log("WastedB BtimeB Buntil",B BDate.now()B B-B Bstart);
//B B→B BWastedB BtimeB BuntilB B50
//B B→B BTimeoutB BranB BatB B55
PromisesB BresolveB BorB BdeclineB BasB BaB BnewB Bevent.B BEvenB BifB BaB BpromiseB BisB
resolvedB Balready,B BwaitingB BforB BitB BwillB BmakeB ByourB BcallbackB BrunB BafterB
B

theB BexistingB BscriptB Bcompletes,B BinsteadB BofB Bimmediately.


B

Promise.resolve("Done").then(console.log);

console.log("MeB Bfirst!");
//B B→B BMeB Bfirst!
//B B→B BDone
AsynchronousB Bbugs
WhenB ByouB BrunB ByourB BprogramB Bsynchronously,B BthereB BisB BnoB BgivenB
occurringB
B B transformationB besidesB
B theB
B onesB
B thatB
B programB
B

themselves.B BButB BwhenB ByouB BrunB BanB BasynchronousB Bprogram,B BthisB BisB
B

anotherB Bscenario.B BTheyB BcouldB BcontainB BgapsB BduringB BexecutionB BthatB


B

otherB BcodeB BcanB Butilize.B BBelowB BisB BanB Billustration.B BOneB BofB BourB
B

crow’sB BfavoritesB BisB BtoB BenumerateB BtheB BnumberB BofB BchicksB BthatB BhatchB
B

duringB BtheB BvillageB BeachB Byear.B BNestsB BkeepB BthisB BcountB BwithinB BtheirB
B

storageB Bbulbs.B BTheB BbelowB BcodeB BtriesB BtoB BtallyB BtheB BcountsB BfromB
B

everyB BnestB BforB BaB BparticularB Byear:


B

functionB BanyStorage(nest,B Bsource,B Bname)B B{


ifB B(sourceB B==B Bnest.names)B BreturnB Bstorage(nest,B Bname);
elseB BreturnB BrouteRequest(nest,B Bsource,B B"storage",B Bname);
}

asyncB BfunctionB Bchicks(nest,B Byear)B B{


letB BlistB B=B B"";
awaitB BPromise.all(network(nest).map(asyncB BnameB B=>B B{
listB B+=B B`${name}:B B${
awaitB BanyStorage(nest,B Bnames,B B`chicksB BinB B${year}`)
}\n`;
}));

returnB Blist;
}

TheB BasyncB BnameB B=>B BdisplaysB BthatB BarrowB BfunctionsB BareB BalsoB BmadeB
BasyncB BbyB BplacingB BtheB BwordB BasyncB BinB BfrontB BofB Bthem.B BTheB BcodeB
BdrawsB BtheB BasyncB BarrowB BfunctionB BacrossB BtheB BsetB BofB Bnests,B BbuildingB
BanB BarrayB BofB Bpromises,B BandB BalsoB ButilizingB BPromise.allB BtoB BwaitB BbeforeB
BsendingB BbackB BtheB BlistB BtheyB Bcreated.B BButB Bit'sB Bbroken.B BIt’llB BsendB
BbackB BaB BsingleB BlineB BofB Boutput,B BlistingB BtheB BslowestB BtoB BrespondB Bnests.B
BDoB ByouB BknowB Bwhy?
TheB BproblemB BisB BinB BtheB B+=B BoperatorB BthatB BtakesB BtheB BpresentB BvalueB
BofB BtheB BlistB BwhenB BtheB BstatementB BbeginsB BexecutingB BandB BwhenB BtheB

BwaitB Bends,B BsetsB BtheB BlistB BbindingB BtoB BbeB BtheB BvalueB BtogetherB BwithB
BtheB BaddedB Bstring.B BButB BbetweenB BtheB BbeginningB BandB BendB BofB BtheB
Bstatement,B BanB BasynchronousB BgapB BisB Bpresent.B BTheB BmapB BexpressionB
BisB BtheB BfirstB BtoB BrunB BbeforeB ByouB BcanB BaddB BanythingB BtoB BtheB Blist,B BsoB
BeveryB B+=B BoperatorB BbeginsB BfromB BanB BemptyB BstringB BandB BfinishesB BwhenB
BitsB BretrievalB BstorageB Bcompletes.B BAsB Busual,B BcalculatingB BnewB BvaluesB BisB
BanB Berror-freeB BprocessB BratherB BthanB BtransformingB BexistingB Bvalues.
asyncB BfunctionB Bchicks(nest,B Byear)B B{
letB BlinesB B=B Bnetwork(nest).map(asyncB BnameB B=>B B{
returnB BnameB B+B B":B B"B B+
awaitB BanyStorage(nest,B Bnames,B B`chicksB BinB B${year}`);
});

returnB B(awaitB BPromise.all(lines)).join("\n");


}
MistakesB BareB BelementaryB BtoB Bmake,B BespeciallyB BduringB BtheB BuseB BofB
await,B BandB ByouB BshouldB BknowB BwhereB BgapsB BareB BwithinB ByourB Bcode.
B

Summary

WeB BlearnedB BeverythingB BaboutB BAsynchronousB BprogrammingB BinB BthisB


chapter.B
B AsynchronousB
B BprogrammingB enablesB
B BtheB expressionB
B

waitingB BforB BactionB BthatB BrunsB BforB BaB BlongB BtimeB BwithoutB BgivingB BtheB
B

programB
B problemsB
B BthroughoutB BtheB operations.B
B JavaScriptB
B

environmentsB BgenerallyB ButilizeB BthisB BstyleB BofB BprogrammingB BthroughB


B

callbacks,B BfunctionsB BwhichB BtoB BcallB BwhenB BactionsB Bend.B BWeB BtouchedB
B

onB BtheB BeventB BloopB BasB Bwell.B BAnB BeventB BloopB BcreatesB BaB BplanB BforB
B

suchB BcallbacksB BtoB BbeB BcalledB BwhenB BitB BisB Btime,B BoneB BafterB Banother,B BtoB
B

avoidB Boverlapping.
B

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BtransformB BanB BasynchronousB BfunctionB


toB BreturnB BaB Bpromise.
B

Solution
Chapter 13: Parsing
BB BB

DevelopingB Bone'sB BprogrammingB BlanguageB BisB BrelativelyB BeasyB BandB


veryB Bexciting.B BThisB BchapterB BwillB BteachB ByouB BhowB BtoB BbuildB ByourB
B

language.B BWeB BwillB BcreateB BaB BprogrammingB BlanguageB BcalledB BEgg.B BAB
B

small,B BsimpleB BlanguageB BisB ByetB BstrongB BenoughB BtoB BexpressB BanyB
B

thinkableB Bcomputation.B BItB BenablesB BpureB BabstractionB BdeterminedB


B

functions.
B

Parsing

TheB BnoticeableB BpartB BofB BaB BprogrammingB BlanguageB BisB BtheB BnotationB BorB
syntax.B BAB BparserB BisB BaB BprogramB BthatB BreadsB BtheB BtextB BandB BprovidesB
B

aB BdataB BlayoutB BthatB BreflectsB BtheB BlayoutB BofB BtheB BprogramB BwithinB BthatB
B

text.B BIfB BtheB BtextB BrefusesB BtoB BcreateB BaB BvalidB Bprogram,B BtheB BparserB
B

wouldB BindicateB BanB Berror.B BOurB BlanguageB BwouldB BcontainB BpreciseB BandB
B

uniformB Bsyntax.B BEverythingB BincludedB BinB BEggB BisB BanB Bexpression.B BAnB
B

expressionB BcouldB BbeB BtheB BbindingB Bname,B Bnumber,B Bstring,B BorB


B

application.B BUtilizeB BApplicationsB BforB BfunctionB BcallsB BandB BasB BwellB BasB
B

constructsB BlikeB BifB BorB Bwhile.


B

ToB BkeepB BtheB BsimpleB Bparser,B BstringsB BwithinB BtheB BEggB BdoB BnotB BsupportB
backslashB Bescapes.B BAB BstringB BisB BaB BsuccessionB BofB BcharactersB BthatB BareB
B

notB BdoubleB Bquotes,B BenclosedB BinB Bdouble-quotes.B BNameB BBindingB BcanB


B

containB BanyB BcharacterB BthatB Bisn'tB BwhitespaceB BandB BthatB BdoB BnotB
B

containB BaB BuniqueB BmeaningB BinB BtheB Bsyntax.B BWriteB BapplicationsB BinB
B

JavaScript,B BbyB BplacingB BparenthesesB BafterB BanB BexpressionB BandB BputtingB


B

anyB BnumberB BofB BargumentsB BwithinB BtheB Bparentheses,B BdifferentiatedB


B

byB Bcommas.
B

do(define(x,B B10),
if(>(x,B B5),
print("large"),
print("small")))

TheB BconsistencyB BofB BtheB BEggB BlanguageB BmeansB BthatB BoperatorsB BinB
BJavaScriptB B(likeB BtheB B>)B BareB BcalledB BbindingsB BinB BthisB Blanguage,B

utilizedB BsimilarlyB BlikeB BotherB Bfunctions.B BAndB BtheB BsyntaxB BcontainsB


B

zeroB BblockB Bconcept,B BsoB BaB BconstructB BisB BneededB BtoB BrepresentB
B

runningB BseveralB BthingsB BinB Bsuccession.B BTheB BdataB BlayoutB BtheB BparserB
B

utilizesB BtoB BdefineB BaB BprogramB BcontainingB BexpressionB Bobjects.B BEachB


B

oneB BcontainsB BaB BtypeB BofB BpropertyB BsignifyingB BtheB BkindB BofB BexpressionB
B

itB BisB BandB BseveralB BotherB BpropertiesB BtoB BdetermineB BitsB Bcontent.B
B

ExpressionsB BofB BtypeB B"value"B BmeanB BstringsB BorB Bnumbers.B BTheirB BvalueB
B

propertyB BconsistsB BofB BtheB BstringB BorB BnumberB BvalueB BthatB BtheyB BstandB
B

for.B BUseB BexpressionsB BofB BtypeB B"word"B BforB BidentifiersB B(names).B BTheseB
B

typesB BofB BobjectsB BcontainB BaB BnameB BpropertyB BthatB BholdsB BtheB
B

identifier’sB BtitleB BasB BaB Bstring.B BAndB BthenB BtheB B"apply"B BexpressionsB
B

standB BforB Bapplications.B BTheyB BincludeB BanB BoperatorB BpropertyB BthatB


B

citesB BtheB BappliedB Bexpression,B BtogetherB BwithB BanB BargsB BpropertyB BthatB
B

holdsB BanB BarrayB BofB BargumentB Bexpressions.


B

TheB B>(x,B B5)B BpartB BofB BtheB BnewB BprogramB BwouldB BbeB BlikeB Bthis:
{

type:B B"apply",
operator:B B{type:B B"word",B Bname:B B">"},
args:B B[
{type:B B"word",B Bname:B B"x"},
{type:B B"value",B Bvalue:B B5}
]
}
WeB BdescribeB BaB BfunctionB BparseExpression,B BwhichB BrecognizeB BaB BstringB
asB BinputB BandB BsendB BbackB BanB BobjectB BthatB BconsistsB BofB BtheB BdataB
B

layoutB BforB BtheB BexpressionB BatB BtheB BbeginningB BofB BtheB Bstring,B BtogetherB
B

withB BtheB BstringB BpartB BleftB BafterB BparsingB BthisB Bexpression.B BWhenB ByouB
B

areB BparsingB Bsubexpressions,B ByouB BcanB BcallB BthisB BfunctionB Bagain,B


B

capitulatingB BtheB BargumentB BexpressionB BwithB BtheB BremainingB Btext.B


B

ThisB BtextB BcouldB BconsistB BofB BmoreB BargumentsB BorB BtheB BclosingB
B

parenthesisB BthatB BendsB BtheB BargumentB Blist.


B

BelowB BisB BtheB BparserB BfirstB Bpart:


functionB BparseExpression(program)B B{
programB B=B BskipSpace(program);
letB Bmatch,B Bexpr;
ifB B(matchB B=B B/^"([^"]*)"/.exec(program))B B{
exprB B=B B{type:B B"value",B Bvalue:B Bmatch[1]};
}B BelseB BifB B(matchB B=B B/^\d+\b/.exec(program))B B{
exprB B=B B{type:B B"value",B Bvalue:B BNumber(match[0])};
}B BelseB BifB B(matchB B=B B/^[^\s(),#"]+/.exec(program))B B{
exprB B=B B{type:B B"word",B Bname:B Bmatch[0]};
}B BelseB B{
204

throwB BnewB BSyntaxError("UnexpectedB Bsyntax:B B"B B+B Bprograms);


}

returnB BparseApply(expr,B Bprograms.slice(match[0].length));


}

functionB BskipSpace(string)B B{
letB BfirstB B=B Bstring.search(/\S/);
ifB B(firstB B==B B-1)B BreturnB B"";
returnB Bstring.slice(first);
}

TheB Bevaluator
TheB BevaluatorB BisB BusedB BtoB BrunB BtheB BsyntaxB BtreeB BforB BaB Bprogram.B BSetB
itB BaB BsyntaxB BtreeB BandB BaB BscopeB BobjectB BthatB BrelateB BnamesB BwithB
B

values,B BandB BitB BwillB BaccessB BtheB BexpressionB BthatB BtheB BtreeB BstandsB BforB
B

andB BsendB BbackB BtheB BvalueB BthatB BitB Bprovides.


B

constB BspecialFormsB B=B BObject.create(null);


functionB Bevaluate(expr,B Bscope)B B{
ifB B(expr.typeB B==B B"value")B B{
returnB Bexpr.value;
}B BelseB BifB B(expr.typeB B==B B"word")B B{
ifB B(expr.nameB BinB Bscope)B B{
returnB Bscope[expr.name];
}B BelseB B{
throwB BnewB BReferenceError(
`UndefinedB Bbinding:B B${expr.name}`);
}

}B BelseB BifB B(expr.typeB B==B B"apply")B B{


letB B{operator,B Bargs}B B=B Bexpr;
ifB B(operator.typeB B==B B"word"B B&&
operator.nameB BinB BspecialForms)B B{
returnB BspecialForms[operator.name](expr.args,B Bscope);
}B BelseB B{
letB BopB B=B Bevaluate(operator,B Bscope);
ifB B(typeofB BopB B==B B"function")B B{
returnB Bop(...args.map(argB B=>B Bevaluate(arg,B Bscope)));
}B BelseB B{
throwB BnewB BTypeError("ApplyingB BaB Bnon-function.");
}
}
}
}

TheB BevaluatorB BcontainsB BcodesB BforB BeveryB BexpressionB Btype.B BAB BliteralB
valueB BexpressionB BprovidesB BitsB Bvalue.B BToB Bbind,B BcheckB BifB BitB BdescribesB
B

inB BtheB BscopeB Band,B BifB Byes,B BgetB BtheB BvalueB BofB BtheB Bbinding.B BIfB BitB
B

containsB BaB BuniqueB BformB BthatB BdoesB BnotB BaccessB Banything,B BandB ByetB
B

transfersB BtheB BargumentB BexpressionsB BwithB Bscope,B BtoB BtheB BfunctionB


B

thatB BinfluencesB BtheB Bform.B BIfB BtheB BcallB BisB Btypical,B BaccessB BtheB
B

operator,B BdetermineB BifB BitB BisB BaB Bfunction,B BandB BcallB BitB BwithB BtheB
B

accessibleB Barguments.B BUtilizeB BtheB BcommonB BJavaScriptB BfunctionB


B

valuesB BtoB BstandB BforB BtheB BvalueB BofB BEgg’sB Bfunction.B BTheB BrecursiveB
B

layoutB BofB BevaluatingB BisB BaB BsimilarB BlayoutB BofB BtheB Bparser,B BandB BtheB
B

twoB BmirrorB BtheB BlayoutB BofB BtheB Blanguage.B BYouB BcanB BcombineB BtheB
B

parserB BusingB BtheB BevaluatorB BandB BevaluateB BwhenB Bparsing,B BbutB


B

separatingB BthemB BgivesB BaB BclearerB BofB BtheB Bprogram.B BItB BisB BallB ByouB
B

needB BtoB BcombineB BEgg.


B

Special forms BB

TheB BspecialFormsB BobjectB BdescribesB BuniqueB BsyntaxB BinB BEgg.B BItB BrelatesB
wordsB BwithB BfunctionsB BthatB BaccessB BsuchB Bforms.B BItB BisB BpresentlyB
B

empty.B BLetB BusB BinsertB Bif.


B
specialForms.ifB B=B B(args,B Bscope)B B=>B B{
ifB B(args.lengthB B!=B B3)B B{
throwB BnewB BSyntaxError("WrongB BnumberB BofB BargsB BtoB Bif");
}B BelseB BifB B(evaluate(args[0],B Bscope)B B!==B Bfalse)B B{
returnB Bevaluate(args[1],B Bscope);
}B BelseB B{
returnB Bevaluate(args[2],B Bscope);
}
};

Egg’sB BifB BconstructB BexpectsB BthreeB Barguments.B BItB BwillB BaccessB BtheB Bfirst,B
BandB BifB BtheB BvalueB BisB BnotB Bfalse,B BitB BmovesB BtoB BaccessB BtheB Bsecond.B BIfB
Bnot,B BitB BaccessesB BtheB Bthird.B BTheB BifB BformB BlooksB BmoreB BlikeB
BJavaScript’sB Bternary?:B BoperatorB BthanB BJavaScript’sB Bif.B BItB BisB BanB
BexpressionB BandB BnotB BaB Bstatement,B BandB BprovidesB BaB Bvalue,B BwhichB BareB
BtheB BresultsB BofB BtheB BsecondB BorB BthirdB Bargument.B BEggB BareB BalsoB
BdifferentB BfromB BJavaScriptB BinB BhandlingB BtheB BconditionB BvalueB BtoB Bit.B BItB
BdoesB BnotB BrelateB BwithB BthingsB BlikeB BzeroB BorB BemptyB BstringsB BasB Bfalse,B
BonlyB BtheB BexactB BvalueB Bfalse.B BAllB BargumentsB BtoB BfunctionsB BareB
BaccessedB BbeforeB ByouB BcallB BtheB Bfunction.
specialForms.whileB B=B B(args,B Bscope)B B=>B B{
ifB B(args.lengthB B!=B B2)B B{
throwB BnewB BSyntaxError("WrongB BnumberB BofB BargsB BtoB Bwhile");
}

whileB B(evaluate(args[0],B Bscope)B B!==B Bfalse)B B{


evaluate(args[1],B Bscope);
}

//B BSinceB BundefinedB BareB BnotB BinB BEgg,B BweB BreturnB Bfalse,
//B BforB BlackB BofB BaB BsignificantB Bresult.
returnB Bfalse;
};

OneB BotherB BbuildingB BblockB BisB Bdo,B BthatB BperformsB BitsB BargumentsB BfromB
BtopB BtoB Bbottom.B BItsB BvalueB BisB BprovidedB BbyB BtheB BlastB Bargument.
specialForms.doB B=B B(args,B Bscope)B B=>B B{
letB BvalueB B=B Bfalse;
forB B(letB BargB BofB Bargs)B B{
valueB B=B Bevaluate(arg,B Bscope);
}

returnB Bvalue;
};

ToB BbuildB BbindingsB BandB BsetB BnewB Bvalues,B ByouB BshouldB BbuildB BaB BformB
BcalledB Bdefine.B BItB BawaitsB BaB BwordB BasB BitsB BfirstB BargumentB BandB BanB
BexpressionB BprovidingB BtheB BvalueB BtoB BsetB BtoB BthatB BwordB BasB BitsB BsecondB
Bargument.B BSinceB BdefineB BisB BanB Bexpression,B BitB BmustB BsendB BbackB BaB
Bvalue.B BWeB BwillB BreturnB BtheB BvalueB BthatB BwasB BsetB B(likeB BJavaScript’sB B=B
Boperator).
specialForms.defineB B=B B(args,B Bscope)B B=>B B{
ifB B(args.lengthsB B!=B B2B B||B Bargs[0].typeB B!=B B"word")B B{
throwB BnewB BSyntaxError("IncorrectB BuseB BofB Bdefine");
}

letB BvalueB B=B Bevaluate(args[1],B Bscope);


scope[args[0].name]B B=B Bvalue;
returnB Bvalue;
};
TheB Benvironment
TheB BscopeB BthatB BevaluateB BallowsB BisB BanB BobjectB BcontainingB BfewB
propertiesB BthatB BhaveB BtheirB BnameB BtallyB BwithB BbindingB Bnames.B BTheirB
B

valuesB BareB BinB BaccordanceB BtoB BtheB BvaluesB BthoseB BboundedB Bbindings.B
B

BelowB BisB BanB BillustrationB BofB BanB BobjectB BtoB BstandB BforB BglobalB Bscope.B
B

ToB BenableB BtheB ButilizationB BofB BtheB BearlierB BdescribedB BifB Bconstruct,B BtheB
B

BooleanB BvaluesB BmustB BbeB Baccessible.B BTherefore,B BthereB BareB BtwoB


B

BooleanB BvaluesB Bonly,B BallB ByouB BneedB BtoB BdoB BisB BtoB BbindB BtwoB BnamesB BtoB
B

theB BvaluesB BtrueB BandB BfalseB BandB ButilizeB Bthem.


B

constB BtopScopeB B=B BObject.create(null);


topScope.trueB B=B Btrue;
topScope.falseB B=B Bfalse;
WeB BcanB BnowB BexamineB BaB BsimpleB BexpressionB BthatB BnullifyB BaB BBooleanB
value.
B

letB BprogB B=B Bparses(`if(true,B Bfalse,B Btrue)`);


console.log(examine(prog,B BtopScope));
//B B→B Bfalse
ToB BprovideB BfundamentalB BarithmeticB BasB BwellB BasB BcomparisonB
operators,B BletsB BincludeB BfunctionB BvaluesB BtoB Bscope.B BWeB BwillB BuseB
B

functionB BonB BfewB BoperatorB BfunctionsB BwithinB BaB Bloop,B BandB BnotB BstatingB
B

themB BoneB BbyB Bone.


B

forB B(letB BopB BofB B["+",B B"-",B B"*",B B"/",B B"==",B B"<",B B">"])B B{
topScope[op]B B=B BFunction("a,B Bb",B B`returnB BaB B${op}B Bb;`);
}

weB BwillB BencloseB Bconsole.logB BinB BaB BfunctionB BtoB BoutputB BtheB Bvalues
andB BcallB BitB Bprint.
topScope.printB B=B BvalueB B=>B B{
console.log(value);

returnB Bvalue;
};

ThatB BprovidesB BadequateB BelementaryB BtoolsB BtoB BcodeB BeasyB Bprogram,B


BanalyzeB BandB BrunB BitB BinB BaB BnewB Bscope:
functionB Brun(program)B B{
returnB Bevaluate(parse(program),B BObject.create(topScope));
}

TheB BchainsB BofB BtheB BobjectB BprototypeB BwillB BstandB BforB BnestedB BscopesB
BtoB BenableB BaddB BbindingsB BwithoutB BalteringB BtheB Bhigh-levelB Bscope.
run(`

do(define(total,B B0),
define(count,B B1),
while(<(count,B B11),
do(define(total,B B+(total,B Bcount)),
define(count,B B+(count,B B1)))),
print(total))
`);

//B B→B B55


ThisB BconceptB BexplainsB BtheB BtotalB BnumbersB BfromB B1B BtoB B10,B BasB
BindicatedB BinB Begg.
Functions

ProgrammingB BlanguageB BthatB BhasB BnoB BfunctionsB BisB BaB BreallyB BbadB Bone,B
BalthoughB BitB BisB BeasyB BtoB BinsertB BaB BfunctionB BthatB BusesB BitsB BlastB
BargumentB BasB BtheB Bfunction’sB Bbody.B BItB BalsoB ButilizesB BeveryB BargumentB
BbeforeB BthatB BasB BtheB Bfunction’sB BparametersB Bnames.
specialForms.funB B=B B(args,B Bscope)B B=>B B{
ifB B(!args.length)B B{
throwB BnewB BSyntaxError("FunctionsB BneedB BaB Bbody");
}

letB BbodyB B=B Bargs[args.lengthB B-B B1];


letB BparamB B=B Bargs.slice(0,B Bargs.lengthsB B-B B1).map(exprB B=>B B{
ifB B(expr.typeB B!=B B"word")B B{
throwB BnewB BSyntaxError("ParameterB BnamesB BmustB BbeB Bwords");
}

returnB Bexpr.name;
});
211

returnB Bfunction()B B{
ifB B(arguments.lengthB B!=B Bparams.length)B B{
throwB BnewB BTypeError("WrongB BnumberB BofB Barguments");
}

letB BlocalScopeB B=B BObject.create(scope);


forB B(letB BiB B=B B0;B BiB B<B Barguments.length;B Bi++)B B{
localScope[params[i]]B B=B Barguments[i];
}

returnB Bevaluate(body,B BlocalScope);


};
};

TheB BeggB BfunctionsB BhaveB BtheirB BownB BlocalB Bscope.B BTheB BfunctionB
BprovidedB BbyB BtheB BfunB BformB BbuildsB BthisB BlocalB BscopeB BandB BattachesB
BtheB BargumentB BbindingsB BtoB Bit.B BItB BthenB BaccessesB BtheB BfunctionB BbodyB
BinB BthisB BscopeB BandB BgivesB BbackB BtheB Bresult.
run(`

do(define(plusOne,B Bfun(a,B B+(a,B B1))),


print(plusOne(10)))
`);

//B B→B B11


run(`

do(define(pow,B Bfun(base,B Bexp,


if(==(exp,B B0),
1,

*(base,B Bpow(base,B B-(exp,B B1)))))),


print(pow(2,B B10)))
`);

//B B→B B1024


Summary

WeB BcoveredB BtheB Bparsing,B Bfunctions,B BspecialB Bforms,B BandB BtheB


BevaluatorB BinB BthisB Bchapter.B BNotationB BorB BsyntaxB BisB BaB BveryB BimportantB
BaspectB BofB Bprogramming.B BAB BparserB BreadsB BtextB BandB BoffersB BaB BdataB
BlayoutB BthatB BshowsB BtheB BprogramB BlayoutB BinB BtheB Btext.B BIfB BtheB BtextB
BcreatesB BanB BinvalidB Bprogram,B BtheB BparserB BwouldB BsignifyB BanB Berror.
Exercise

WriteB BaB BJavaScriptB BfunctionB BtoB BcalculateB BtheB BfactorsB BofB BaB BpositiveB
Binteger.
Solution
Conclusion

ThisB BbookB BconsistsB BofB BimportantB BinformationB BconnectedB BtoB BtheB


JavaScriptB BprogrammingB Blanguage.B BTheB BinformationB BinB BthisB BbookB
B

willB BhelpB ByouB BtoB BunderstandB BandB BpracticeB BtheB BseveralB BJavaScriptB
B

operators,B BloopsB BandB BconditionalB Bstatements,B Bfunctions,B BtheB BscopeB


B

ofB Bvariables,B BinventB Btypes,B BandB BsoB Bon.B BAndB BwhileB BedgingB BtowardB
B

theB BendB BofB BtheB Bcourse,B ByouB BwillB BhaveB BanB BexcellentB BunderstandingB
B

ofB BtheB BJavaScriptB BlanguageB BasB ByouB BwillB BhaveB BlearnedB BJavaScriptB
B

andB Bforms,B ByouB BwillB BunderstandB BtheB BbasicsB BofB BjQuery,B BframesB BandB
B

debuggingB Bscripts.B BTheB BbestB BadviceB BtoB BgiveB BaB BprogrammerB BisB BtoB
B

keepB BpracticingB BbecauseB BthatB BisB BtheB BonlyB BwayB ByouB BcanB BmasterB
B

whatB ByouB BhaveB Blearned.B B


B

You might also like