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 BtransmittedB BwithoutB BdirectB BwrittenB BpermissionB BfromB BtheB BauthorB BorB BtheB Bpublisher.

UnderB BnoB BcircumstancesB BwillB BanyB BblameB BorB BlegalB BresponsibilityB BbeB BheldB BagainstB BtheB Bpublisher,B BorB Bauthor,B BforB BanyB Bdamages,B Breparation,B BorB BmonetaryB BlossB BdueB BtoB BtheB BinformationB BcontainedB BwithinB BthisB Bbook,B BeitherB BdirectlyB BorB Bindirectly.

LegalB BNotice:

ThisB BbookB BisB BcopyrightB Bprotected.B BItB BisB BonlyB BforB BpersonalB Buse.B BYouB BcannotB Bamend,B Bdistribute,B Bsell,B Buse,B BquoteB BorB BparaphraseB BanyB Bpart,B BorB BtheB BcontentB BwithinB BthisB Bbook,B BwithoutB BtheB BconsentB BofB BtheB BauthorB BorB Bpublisher.

DisclaimerB BNotice:

PleaseB BnoteB BtheB BinformationB BcontainedB BwithinB BthisB BdocumentB BisB BforB BeducationalB BandB BentertainmentB BpurposesB Bonly.B BAllB BeffortB BhasB BbeenB BexecutedB BtoB BpresentB Baccurate,B BupB BtoB Bdate,B Breliable,B BcompleteB Binformation.B BNoB BwarrantiesB BofB BanyB BkindB BareB BdeclaredB BorB Bimplied.B BReadersB BacknowledgeB BthatB BtheB BauthorB BdoB BnotB BengageB BinB BtheB BrenderingB BofB Blegal,B Bfinancial,B Bmedical,B BorB BprofessionalB Badvice.B BTheB BcontentB BwithinB BthisB BbookB BhasB BbeenB BderivedB BfromB BvariousB Bsources.B BPleaseB BconsultB BaB BlicensedB BprofessionalB BbeforeB BattemptingB BanyB BtechniquesB BoutlinedB BinB BthisB Bbook.

ByB BreadingB BthisB Bdocument,B BtheB BreaderB BagreesB BthatB BunderB BnoB BcircumstancesB BisB BtheB BauthorB BresponsibleB BforB BanyB Blosses,B BdirectB BorB Bindirect,B BthatB BareB BincurredB BasB BaB BresultB BofB BtheB BuseB BofB BtheB BinformationB BcontainedB BwithinB BthisB Bdocument,B Bincluding,B BbutB BnotB BlimitedB Bto,B Berrors,B Bomissions,B BorB Binaccuracies.

B B

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 BthatB BadheresB BtoB BtheB BECMAScriptB Bspecification.B BTheB BprogrammingB BlanguageB BconsistsB BofB Bhigh-poweredB Btyping,B BtheB BcurlyB BbracketB Bsyntax,B Btop-qualityB Bfunctions,B BandB Bprototype-basedB Bobject-orientation.B BAccompaniedB BbyB BHTMLB BandB BCSS,B BJavaScriptB BisB BoneB BofB BtheB BsignificantB BtechnologiesB BofB BtheB BWorldB BWideB BWeb.B BJavaScriptB BfacilitatesB BinterchangeableB BwebB BpagesB BandB BisB BaB BvitalB BpartB BofB BwebB Bapplications.B BAlmostB BeveryB BwebsiteB ButilizesB BJavaScript,B BandB BallB BtheB BsignificantB BwebB BbrowsersB BconsistB BofB BtheB BJavaScriptB BengineB BtoB BfunctionB Bcorrectly.B BBrendanB BEichB BdevelopedB BJavaScriptB BinB B1995B BwhenB BheB BwasB BwithB BNetscapeB BCommunications.B BJavaScriptB BaidsB Bfunctional,B Bevent-driven,B Bprototype-basedB BandB Bobject-orientedB BprogrammingB Bstyles.B BJavaScriptB BupgradesB BwebB BuserB BinterfaceB BbyB BaffirmingB BactivitiesB BtakenB BonB BtheB Bclient-sideB BbyB BtheB Buser.B BYouB BcanB BinsertB BJavaScriptB BenginesB BintoB BdifferentB BtypesB BofB BhostB Bsoftware,B BwhichB BincludesB BdatabasesB BandB BwebB Bservers,B BandB Bnon-webB BrelatedB BprogramsB BlikeB BwordB Bprocessors.

TheB BconceptsB BofB BJavaScriptB BareB BexplainedB BfurtherB BinB BthisB BbookB BwithB BtheB BgoalB BtoB BhelpB ByouB BlearnB BandB BunderstandB BJavaScriptB BlanguageB BwithoutB Bpressure.B BTheB BknowledgeB BofB BHTML,B BtextB Beditor,B BwebB Bbrowser,B BandB BCSSB BareB BallB Bthat'sB BneededB BtoB BlearnB BJavaScript.B BToB BgetB BtheB BlearningB BprocessB Bstarted,B BoneB BofB BtheB BessentialB BtoolsB BisB BaB BtextB Beditor,B BandB BitB BisB BrequiredB BtoB BwriteB Bcodes.B BYou’llB BalsoB BneedB BaB BbrowserB BtoB BunveilB ByourB BdevelopedB BwebB Bpages.B BThereB BareB BdifferentB BtypesB BofB BtextB BeditorsB BsuchB BasB BtheB BSublimeB BText,B BNotepad++B BandB BbrowsersB BsuchB BasB BFirefox,B BGoogleB BChrome,B BandB BsoB Bon.B B

B B

ChapterB B1:B BWhatB BisB BJavaScript

JavaScript,B BabbreviatedB BJS,B BisB BaB Bhigh-levelB BprogrammingB BlanguageB BintroducedB BtoB BaddB BspecificB BprogramsB BtoB BwebB Bpages,B BandB BitB BhasB BbeenB BadoptedB BbyB BallB BmajorB BwebB Bbrowsers.B BJavaScriptB BcanB BbeB BusedB BtoB BbuildB BinteractiveB BwebB BapplicationsB BtoB BfunctionB BappropriatelyB BwithoutB BreloadingB BeveryB BpageB Bper-action.B BJavaScriptB BisB BusedB BtoB BcreateB BdifferentB BformsB BofB BactivitiesB BwithinB BwebB BpagesB BandB BisB BoneB BofB BtheB BessentialB BcomponentsB BofB BtheB BWorldB BWideB BWebB B(www),B BwhichB BareB BHTMLB B(HypertextB BMarkupB BLanguage)B BandB BCSSB B(CascadingB BStyleB BSheets).B BJavaScriptB BandB BHTMLB BareB BusedB BtoB BdevelopB BwebB Bpages.B BJavaScriptB BbringsB BaB BpageB BtoB BlifeB BbyB BaddingB BspecialB BeffectsB BsuchB BasB Bsliders,B Bpop-ups,B BformB Bvalidations,B Betc.B BCSSB BdeterminesB BtheB BcolorB Bintensity,B BimageB Bsize,B BbackgroundB Bcolors,B Btypeface,B BfontB Bsize,B Betc.

Client-SideB BJavaScript

Client-SideB BJavaScriptB BisB BtheB BusualB BformB BofB BJavaScriptB Blanguage.B BTheB BscriptB BmustB BbeB BinsertedB BorB BreferencedB BbyB BanB BHTMLB BdocumentB BsoB BthatB BtheB BbrowserB BcanB BinterpretB BtheB Bcode.B BItB BenablesB BwebB BpagesB BtoB BincludeB BinteractiveB BprogramsB BwithB BtheB Buser,B BdevelopB BHTMLB BcontentB Bdynamically,B BandB BcommandB BtheB Bbrowser.B BUsersB BuseB BJavaScriptB BcodeB BwhenB BtheyB BwantB BtoB BsubmitB BformsB BandB BalsoB BdetermineB BifB BallB BentriesB BareB BvalidB BbeforeB BitB BtransfersB BthemB BtoB BtheB Bserver.

AdvantagesB BofB BJavaScript

·B BWithB BJavaScript,B BusersB BcanB BorganizeB BinputB BbeforeB BgettingB BtheB BpageB BsentB BtoB BtheB Bserver,B BwhichB BautomaticallyB BreducesB BloadsB BonB BtheB Bserver.

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

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

LimitationsB BofB BJavaScript

JavaScriptB BprogrammingB BlanguageB BlacksB BtheB BfollowingB BessentialB Bfeatures.B BTheyB Bare:

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

·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 BJavaScriptB Bcodes.B BYouB BcanB BwriteB BwithB BaB BsimpleB BtextB BeditorB BsuchB BasB BMicrosoftB BFrontPage,B BMacromediaB BDreamweaverB BMX,B BMacromediaB BHomeSiteB B5,B Betc.

JavascriptB BPlacement

JavaScriptB BcodeB BisB BinsertedB BanywhereB BinB BanB BHTMLB Bdocument.B BHowever,B ByouB BwantB BtoB BinsertB BJavaScriptB BcodeB BinB BanB BHTMLB BfileB BlikeB Bthis:

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 Bevent,B BsuchB BasB BanB BactionB BwhenB BaB BbuttonB Bclicked,B BplaceB BtheB BscriptB BinB BtheB BheadB BsectionB BlikeB Bthis:

<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 BscriptB BonB BtheB BcontentB Bpage,B BinsertB BtheB BscriptB BwithinB BtheB B<body>B Bsection.B BThisB BisB BwhatB BtheB BcodeB BshouldB BlookB Blike:

<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>

JavaScriptB BinB BExternalB BFiles

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>.

ChapterB B2:B BValues,B BTypes,B BandB BOperators

InB BtheB BworldB BofB Bcomputers,B BthereB BisB Bdata.B BYouB BcanB BcreateB BnewB Bdata,B BreadB BdataB BandB BchangeB Bdata,B BwhichB BareB BallB BstoredB BasB BaB Blook-alikeB BlongB BsuccessionB BofB Bbits.B BDefineB BbitsB BasB BzerosB BandB BonesB BthatB BtakeB BaB BstrongB BorB BweakB Bsignal,B BandB BhighB BorB BlowB BelectricalB BchargeB BfromB BinsideB BtheB Bcomputer.B BAllB BdataB BandB BpiecesB BofB BinformationB BareB BdescribedB BasB BaB BsuccessionB BofB BzerosB BandB BonesB BandB BrepresentedB BinB Bbits.

Values

TakeB BaB BdeepB BbreathB BandB BthinkB BofB BanB BoceanB BofB Bbits.B BTheB BlatestB BPCsB BcontainsB BmoreB BthanB B30B BbillionB BbitsB BinB BitsB BdataB Bstorage.B BWeB BuseB BbitsB BtoB BcreateB Bvalues.B BTheB BcomputerB BcanB BfunctionB BcorrectlyB BbecauseB BeveryB BbitB BofB BinformationB BisB BsplitB BintoB Bvalues.B BEveryB BvalueB BconsistsB BofB BaB BtypeB BthatB BinfluencesB BitsB Brole,B BandB BvaluesB BcanB BbeB Bnumbers,B BtextB BorB Bfunctions,B Betc.B BToB BgenerateB Bvalue,B ByouB BneedB BtoB BinvokeB BitsB Bname,B BandB BitB BappearsB BfromB BwhereB BitB BwasB Bstored.

Arithmetic

ArithmeticB BisB BtheB BmajorB BthingB BtoB BdoB BwithB Bnumbers.B BTheB Bmultiplication,B Baddition,B BandB BsubtractionB BofB BmoreB BthanB BoneB BnumberB BtoB BproduceB BanotherB BnumberB BisB BanB BarithmeticB Boperation.B BThisB BisB BanB BexampleB BofB BwhatB BtheyB BlookB BlikeB BinB BJavaScript:

100B B+B B4B B*B B11

TheB B+B BandB B*B BsymbolsB BareB BcalledB Boperators,B BtheB BfirstB BmeansB BadditionB BwhileB BtheB BotherB BmeansB Bmultiplication.B BAnB BoperatorB BinsertedB BbetweenB BtwoB BvaluesB BwillB BproduceB BanotherB Bvalue.B BTheB B-B BoperatorB BisB BforB BsubtractionB BandB BtheB B/B BoperatorB BisB BforB BtheB Bdivision.B BIfB BoperatorsB BshowB BtogetherB BwithoutB Bparentheses,B BtheB BprecedenceB BofB BtheB BoperatorsB BdecidesB BtheB BwayB BtheyB BareB Bapplied.B BIfB BseveralB BoperatorsB BwithB BtheB BsameB BprecedenceB BshowB BrightB BnextB BtoB BeachB BotherB BlikeB B1B B-B B2B B+B B1,B BapplyB BthemB BleftB BtoB Bright:B B(1B B-B B2)B B+B B1.

SpecialB Bnumbers

JavaScriptB BconsistsB BofB BthreeB BuniqueB BvaluesB BthatB BdoB BnotB BactB BlikeB BnumbersB BbutB BareB BregardedB BasB Bnumbers.B BInfinityB BandB B-InfinityB BareB BtheB BfirstB Btwo,B BwhichB BmeanB BtheB BpositiveB BandB BnegativeB Binfinities,B BandB BtheB BlastB BvalueB BisB BtheB BNaN.B BNaNB BsaysB B“notB BaB Bnumber,”B BalthoughB BitB BisB BaB BvalueB BofB BtheB BnumberB Btype.

Strings

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

`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 Bquotes,B BorB BtheB BbackticksB BtoB BmarkB Bstrings.B BItB BisB BessentialB BthatB BtheB BstringsB Bmatch.B BTheB BelementsB BwithinB BtheB BquotesB BcreateB BaB BstringB BvalueB BbyB BJavaScript.B BJavaScriptB BusesB BtheB BUnicodeB BstandardB BtoB 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 BstringsB BbutB ByouB BcanB BuseB BtheB B+B Boperator,B BwhichB BwillB BnotB BaddB BbutB BconcatenatesB BtwoB BstringsB Btogether.B BConcatenationB BmeansB BtoB BglueB BstringsB Btogether.

UnaryB Boperators

SymbolsB BdoB BnotB BrepresentB BallB BtheB Boperators.B BYouB BcanB BwriteB BsomeB BoperatorsB BinB Bwords.B BAB BclearB BexampleB BisB BaB BtypeB BofB Boperator,B BandB BthisB BoperatorB BcreatesB BaB BstringB BvalueB BwithB BtheB BnameB BofB BtheB BtypeofB BitsB BattachedB Bvalue.

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 BbecauseB BtheyB BuseB BtwoB Bvalues,B BwhileB BoperatorsB BthatB BuseB BoneB BvalueB BareB BtheB BunaryB Boperator.

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 BasB B“on”B BandB B“off”B BandB BsoB Bon.B BTheB BBooleanB BconsistsB BofB BonlyB BtrueB BandB Bfalse.

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 Bthan”B BandB B“isB BlessB Bthan,”B Baccordingly.B BYouB BcanB BuseB BbinaryB BoperatorsB BinB BaB BBooleanB BvalueB BthatB BdeterminesB BifB BtheB BcontainedB BvalueB BifB BtrueB BorB Bfalse.

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 BareB BoftenB B“less”B BthanB Blowercase,B BsoB B"Z"B B<B B"a,"B BandB Bnon-alphabeticB BcharactersB B(!B B-,B BandB BsoB Bon)B BareB BalsoB BpresentB BinB BtheB Bordering.B BWhenB BJavaScriptB BwantB BtoB BcompareB Bstrings,B BitB BrecognizesB BcharactersB BfromB BleftB BtoB Bright,B BdifferentiatingB BtheB BUnicodeB BcodesB Bindividually.

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

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 BwhichB BisB BtheB BNaNB B(“notB BaB Bnumber”).

console.log(NaNB B==B BNaN)

//B B→B Bfalse

LogicalB Boperator

JavaScriptB BendorsesB BonlyB BthreeB BoperatorsB BthatB ByouB BcanB BapplyB BtoB BBooleanB Bvalues,B BtheyB BareB Band,B Bor,B BandB Bnot.B BTheB B&&B BoperatorB BsignifiesB BlogicalB BorB BandB BitsB BresultsB BdependB BonB BwhereB BtheB BvaluesB BimputedB BareB BtrueB BorB Bfalse.

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 BtheB BgivenB BvalueB BisB Btrue.

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 BoverturnsB BtheB BsetB Bvalue,B BandB BitB BchangesB BfromB BtrueB BtoB BfalseB BandB BfalseB BtoB Btrue.

TheB B||B BconsistsB BofB BtheB BlowestB BprecedenceB BofB BallB Boperators,B BthenB B&&,B BtheB BcomparisonB BoperatorsB B(>,B B==,B Betc.),B BandB BsoB Bon.B BTheB BexampleB BbelowB BstatesB BthatB BparenthesesB BareB Bnecessary:

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 BareB BusedB BtoB BindicateB BtheB Bnon-appearanceB BofB BanB BimportantB Bvalue.B BTheyB BcontainB BzeroB Bdata.

AutomaticB BtypeB Bconversion

EarlierB BIB BsaidB BthatB BJavaScriptB BacceptsB BpracticallyB BallB BgivenB Bprograms,B BincludingB BprogramsB BwithB BoddB Bbehaviors.B BAutomaticB BtypeB BconversionB BillustratesB BinB BtheB BfollowingB Bexpressions:

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 BreturnsB BthatB BvalueB BtoB BtheB BexactB BtypeB BitB BrequiresB BusingB BtheB BtypeB BcoercionB Brule.B BInB BtheB BfirstB Bexpression,B BtheB BnullB BturnsB BtoB B0,B BandB 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 BnumericB Baddition,B BwhichB BconvertsB BtheB B1B BtoB B1B B(fromB BnumberB BtoB BaB Bstring).B BWhenB BoddB BnumbersB BsuchB BasB B"five"B BorB BundefinedB BchangesB BtoB BtheB Bnumber,B BitB BgetsB BtheB BvalueB BofB BNaN.B BIfB ByouB BwantB BtoB BdifferentiateB BbetweenB BvaluesB BofB BtheB BsameB BtypeB BusingB B==,B BtheB BoutputB BshouldB BbeB BtrueB BifB BtheB BvaluesB BareB BsimilarB BexceptB BNaN.B BIfB ByouB 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 Bconversions,B BuseB BtheB Bthree-characterB BcomparisonB Boperators.

Short-circuitingB BofB BlogicalB Boperators

TheB B&&B BandB B||B BareB BcalledB BtheB BlogicalB Boperators.B BTheyB BareB BusedB BtoB BholdB BseveralB BtypesB BofB BvaluesB BinB BaB BspecificB Bway.B BTheyB BchangeB BtheB BvaluesB BcontainedB BinB BtheB BleftB BsideB BtoB BBooleanB BtypeB BtoB Bdecide,B BalthoughB BitB BdependsB BonB BtheB BoperatorsB BandB BtheB BtypeB BofB BgeneratedB Bresult,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 BtoB BtrueB BandB BwillB BreinstateB BtheB BvalueB BtoB BtheB Bright.

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 BplacedB BwithinB BanB BemptyB BvalueB BasB BaB Breplacement.B BStringsB BandB BnumbersB BtoB BBooleanB BvalueB BconversionB BrulesB BindicateB BthatB B0,B BNaN,B BandB BemptyB BstringB B(")B BcountB BasB BfalseB BwhileB BotherB BvaluesB BareB Btrue.B BThereforeB B0B B||B B-1B BoutputsB B-1,B BandB B""B B||B B"!?"B ByieldsB B"!?".B BTheB B&&B BoperatorB BoperatesB BidenticallyB BbutB BtheB BotherB BwayB Baround.B BWhenB BvaluesB BtoB BtheB BleftB BcanB BbeB BchangedB BtoB Bfalse,B BreturnB BtheB Bvalue,B BorB BitB BsendsB BtheB BvalueB BtoB BtheB Bright.B BBothB BoperatorsB BevaluateB BtheB BvalueB BtoB BtheB BrightB BonlyB BwhenB BitB BisB Brequired.B BForB Bexample,B BweB BhaveB BtheB BfollowingB BvaluesB BsetB BasB BtrueB B||B BX,B BtheB BvalueB BofB BXB BwillB BbeB BtrueB BandB BwillB BnotB BconsiderB Bit.B BTheB BsameB BruleB BappliesB BtoB BtheB BfalseB B&&B BX,B BwhichB BtheB BxB BisB BfalseB BandB BwillB BoverlookB Bit.B BYouB BcanB BcallB BthisB BprocessB BtheB Bshort-circuitB Bevaluation.

Summary

ThisB BchapterB BlooksB BatB BtheB BfourB BtypesB BofB BJavaScriptB Bvalues,B BwhichB BareB Bstrings,B Bnumbers,B BundefinedB BvaluesB BandB BBooleans.B BTheseB BvaluesB BareB 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 BlookedB BatB BbinaryB BoperatorsB BforB BarithmeticB B(+,B B-,B B*,B B/,B BandB B%),B BstringB BconcatenationB B(+),B BcomparisonB B(==,B B!=,B B===,B B!==,B B<,B B>,B B<=,B B>=),B BandB BlogicB B(&&,B B||),B BandB BalsoB BvariousB BunaryB BoperatorsB B(-B BtoB BnullifyB BaB Bnumber,B B!B BtoB BnullifyB Blogically,B BandB BtypeB BofB BtoB BsearchB BforB BaB Bvalue’sB Btype)B BandB BaB BternaryB BoperatorB B(?:)B BtoB BchooseB BoneB BofB BtwoB BvaluesB BdependingB BonB BaB BthirdB Bvalue.B BYouB BwillB BgetB BsufficientB BinformationB BtoB BuseB BJavaScriptB BlikeB BaB BsmallB Bcalculator,B BandB ByouB BwillB BimproveB BinB BtheB BfollowingB Bchapters.

Exercise

WriteB BaB BJavaScriptB BpracticeB BtoB BbuildB BaB BvariableB BthroughB B
aB Buser-definedB Bname.

Solution

B B

ChapterB B3:B BProgramB BStructure

WeB BwillB BbeginB BtheB BexpansionB BofB BtheB BJavaScriptB BprogrammingB BlanguageB BcommandsB BbeyondB BsentenceB BfragmentsB BandB Bnouns.

ExpressionsB BandB Bstatements

AB BblockB BofB BcodeB BthatB BmanufacturesB BaB BvalueB BisB BcalledB BanB Bexpression.B BAB BsingleB BvalueB BisB BwrittenB BpreciselyB BasB B22,B BorB BpsychoanalysisB BisB BcalledB BanB Bexpression.B BAnB BexpressionB BwithinB BaB BbinaryB BoperatorB BsetB BtoB BtwoB BexpressionsB BorB BwithinB BparenthesesB BisB BanB Bexpression.B BAnB BexpressionB BthatB BcanB BaccommodateB BotherB BexpressionsB BcomparablyB BtoB BhowB BtheB BhumanB BlanguageB Btranslates.B BItB BenablesB BusB BtoB BdevelopB BexpressionsB BthatB BnarrateB BtheB BarbitrarilyB BcomplexB Bcomputations.B BWhenB BanB BexpressionB BisB BcomparableB BtoB BaB BsentenceB Bfragment,B BtheB BJavaScriptB BstatementB BwillB BcompleteB BtheB Bsentence.B BAB BlistB BofB BstatementsB BisB BcalledB BaB Bprogram,B BandB BtheB BmostB BaccessibleB BtypeB BofB BstatementB BisB BaB BlineB BofB BcodeB BwithB BaB BsemicolonB BendingB Bit.

ForB Binstance:

1;

!false;

WithB BthisB Bfunction,B BaB BstatementB BcanB BstandB Bindependently,B BandB BitB BcanB BaddB BaB BfeatureB BthatB BchangesB BcolorsB BoccasionallyB BtoB BaB BscreenB BorB BmodifyB BtheB BinnerB BstateB BofB BtheB BmachineB BinfluencingB BtheB BfollowingB BstatementsB BafterB Bit.

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 BsentenceB BwillB BspecifyB BaB BbindingB BtogetherB BwithB BtheB BbindingB BnameB BandB BvalueB BcanB BbeB BattachedB BusingB BtheB B=B BoperatorB BandB BanB Bexpression.B BUseB BaB BdefinedB BbindingB BasB BanB Bexpression,B BanB BexpressionB BcontainingB BtheB BbindingB Bvalue.B BHereB BisB BanB BexampleB Bbelow:

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 BbindingB BfromB BaB BsetB BvalueB BandB BpointB BthemB BtoB BaB BnewB Bone.

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 BnothingB BtoB Bhold.B BTherefore,B BaskingB BforB BtheB BvalueB BofB BaB BbindingB BproduceB BtheB BundefinedB Bvalue.B BYouB BcanB BdefineB BmultipleB BbindingB BbyB BaB BsingleB BstatementB BdividedB BbyB Bcommas.

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 BwhichB BpointsB BtoB BitsB BsetB BvalueB BforB BitsB Blifetime.B BTheseB BwordsB BareB BoftenB BusedB BtoB BdeclareB BaB BnameB BtoB BaB BvalueB BtoB BenableB BeasyB BreferenceB BlaterB Bon.

BindingB Bnames

AlthoughB BthereB BareB BsomeB BreservedB BwordsB BlikeB Bconst,B Bclass,B Bdefault,B Bbreak,B Bcontinue,B Bdelete,B Bdo,B BelseB ByetB BanyB BwordB BcanB BbeB BcalledB BaB BbindingB Bname,B BitB BcanB BalsoB BconsistB BofB BdigitsB BbutB BdoB BnotB BbeginB BtheB BstatementB BwithB BaB Bfigure.B BAB BbindingB BnameB BcanB BalsoB BcontainB BdollarB BsignsB B($)B BorB BunderscoresB B(_)B BbutB BdoB BnotB BentertainB BanyB BotherB BspecialB BcharactersB BorB Bpunctuation.

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 BcontainsB BtheB BbindingB BthatB BcreatesB BinteractionB BwithB BsystemB Bsurroundings.B BForB Binstance,B BaB BbrowserB BcarriesB BfunctionsB BthatB BcommunicateB BwithB BtheB BlaunchedB BwebsiteB BasB BwellB BasB BreadB BtheB BkeyboardB BandB BmouseB Binput.

Functions

AB BbitB BofB BprogramB BenclosedB BinB BvalueB BisB BcalledB BaB Bfunction,B BandB BtheseB BvaluesB BareB BaddedB BtoB BlaunchB BtheB BwrappedB Bprogram.B BForB Binstance,B BaB BfunctionB BthatB BdisplaysB BaB BsmallB BdialogB BboxB BforB BuserB Binput.

PromptB B("EnterB Bpasscode");

TheB BprocessB BofB BeffectingB BaB BfunctionB BisB BdescribedB BasB BaB Bcalling,B Binvoking,B BorB Bapplying.B BCallB BaB BfunctionB BbyB BinsertingB BparenthesesB BfollowingB BanB BexpressionB BthatB BprovidesB BaB BfunctionB Bvalue.B BSetB BtheB BparenthesisB BvalueB BtoB BtheB BprogramB BwithinB BtheB Bfunction.B BDefineB BvaluesB BsetB BtoB BfunctionsB BasB Barguments.

TheB Bconsole.logB Bfunction

InB BtheB BaboveB Bsamples,B BweB BusedB BtheB Bconsole.logB BtoB BoutputB Bvalues.B BAllB BmajorB BbrowsersB ButilizeB BtheB Bconsole.logB BfunctionB BtoB BstateB BoutB BitsB BargumentsB BtoB BtheB BdeviceB BthatB BoutputsB BtheB Btext.B BInB BmodernB Bbrowsers,B BtheB BoutputB BisB BoftenB BinB BtheB BJavaScriptB BconsoleB BthatB BisB BinvisibleB BbyB Bdefault;B ByouB BcanB BtapB BtheB BF12B BcommandB BonB ByourB BkeyboardB BorB BtheB Bcommand-option-IB BonB BMac.B BBindingB BnamesB BdoB BnotB BaccommodateB BperiodB Bcharacters,B BbutB Bconsole.logB BdoesB BbecauseB BitB BisB BanB BexpressionB BthatB BreclaimsB BtheB BlogB BpropertyB BfromB BtheB BconsoleB BbindingB Bvalue.

ReturnB Bvalues

FunctionsB BareB BusedB BtoB BproduceB BsideB Beffects.B BTheyB BcanB BalsoB BprovideB BvaluesB BthatB BdoB BnotB BneedB BsideB Beffects.B BForB Binstance,B BtheB BfunctionB BCalculate.maxB BwillB BtakeB BaB BsumB BofB BnumberB BargumentsB BandB BreturnsB BtheB Bgreatest.

console.log(Calculate.max(2,B B4));

//B B→B B4

JavaScriptB BregardsB BanythingB BthatB BprovidesB BvalueB BasB BanB Bexpression,B BwhichB BenablesB BfunctionB BcallsB BtoB BattachB BintoB BtheB BsubstantialB Bexpression.B BLet’sB BcallB BtheB BCalculate.min,B BwhichB BisB BaB BdirectB BoppositeB BtoB BCalculate.max:

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 BexecuteB BinB BaB BstoryB BformB BfromB BtheB BbeginningB BofB BtheB BcodeB BtoB BtheB Bend.B BThisB BtypeB BofB BprogramB BconsistsB BofB BtwoB BtypesB BofB Bstatement;B BtheB BfirstB BdemandB BnumbersB BfromB BtheB BuserB BwhileB BtheB BsecondB BdisplaysB BtheB BsquareB BofB BtheB BnumberB BandB BexecutesB BimmediatelyB BafterB BtheB Bfirst.

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 BtheNumber);

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

ConditionalB Bexecution

TheB BkeyboardB BisB BusedB BtoB BdevelopB BconditionalB BexecutionsB BinB BJavaScript.B BYouB BmayB BwantB BsomeB BcodeB BtoB BexecuteB Bif,B BandB BonlyB Bif,B BaB BspecificB BconditionB BisB Bpositive.B BLetB BusB BdisplayB BtheB BsquareB BofB BtheB BinputB BifB BonlyB BitB BisB BaB Bnumber.

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 BtheB BBooleanB BexpressionB Bvalue.B BTypeB BtheB BdeterminingB BexpressionB BafterB BtheB BkeyboardB BwithinB BtheB BparenthesesB BaccompaniedB BbyB BtheB BstatementB BtoB Baccomplish.

TheB BNumber.isNaNB BfunctionB BisB BaB Bhigh-levelB BJavaScriptB BfunctionB BthatB BoutputsB BonlyB BtrueB BifB BtheB BstatementB BisB BdeclaredB BasB BNaN.B BTheB BnumberB BfunctionB BreturnsB BNaNB BwhenB BanB BassignedB BstringB BisB BnotB BaB BvalidB Bnumber.B BStatementsB BafterB BtheB BifB BstatementB BisB BenclosedB BinB BbracesB B({and}).B BBracesB BareB BusedB BtoB BcategorizeB BdifferentB BnumbersB BofB BstatementB BwithinB BanB BindividualB Bstatement.

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 BtoB BprovideB BtwoB BdifferentB BexecutionB Bpaths.

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 B“chain”B Bmultiple

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 BselectsB BthatB Bbranch,B BandB BthenB BdisplaysB B"Small".B BButB BifB BtheB BnumB BisB BgreaterB BthanB B10,B BitB BselectsB BtheB BelseB BbranchB BwhichB BconsistsB BofB BaB BsecondB BifB BstatementB BofB BitsB Bown.

whileB BandB BdoB Bloops

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

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 Bloop.

TheB BloopingB BcontrolB BflowB BenablesB BtheB BuserB BtoB BreturnB BtoB BcertainB BpointsB BinB BwrittenB BprogramsB BandB BredoB BitB BwithB BtheB BcurrentB BstateB BofB BtheB Bprogram.B BIntegrateB BthisB BwithB BaB BbindingB BthatB BenumeratesB BasB Bfollows:

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 BproducingB BaB Bloop.B BTheB BkeywordB BwhileB BaccompaniedB BbyB BanB BexpressionB BinB BparenthesesB BfollowedB BbyB BaB BstatementB BlikeB BtheB BifB Bstatement.B BTheB BloopB BbecomesB BcontinuousB BuntilB BtheB BexpressionB BprovidesB BaB BvalueB BthatB BstatesB BtrueB BwhenB BtranslatedB BtoB BBoolean.B BEachB BtimeB BtheB BloopB Brepeats,B BnumbersB BadoptB BaB BnumberB BtwiceB BofB BtheirB BpreviousB Bvalue.B BLetB BusB BwriteB BaB BprogramB BthatB BevaluatesB BandB BdisplayB BtheB BvalueB BofB B210B B(2B BraisedB BtoB BtheB BpowerB BofB B10th).B BWeB BwillB ButilizeB BtwoB Bbindings.B BOneB BtoB BkeepB BanB BeyeB BonB BourB BresultB BandB BtheB BotherB BtoB BcalculateB BhowB BmanyB BtimesB BtheB BvalueB BofB BtwoB BmultipliedB BbyB BtheB Bresult.B BItB BmultipliesB BuntilB BtheB BsecondB BbindingB BreachesB B10:

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 BloopB BalwaysB BtakeB BplaceB BatB BleastB BonceB BinB BaB Bstatement,B BandB BthenB BitB BbeginsB BtoB BcheckB BifB BitB BendsB BafterB BtheB BfirstB BexecutionB Bonly.B BFollowB BtheB BfollowingB Bsteps:

letB ByourName;

doB B{

yourNameB B=B Bprompt("WhoB BareB Byou?");

}B BwhileB B(!B ByourName);

console.log(yourName);

B B

B B

forB Bloops

AB BlotB BofB BloopsB BfollowB BtheB BwhileB BloopB Bpattern,B BcreatingB BaB BcounterB BbindingB BtoB BtrackB BtheB Bloop'sB Bprogress.B BThenB BaB BwhileB BloopB BwithB BaB BtestB BexpressionB BtoB BseeB BifB BtheB BcounterB BreachesB BtheB BsetB Bvalue.

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 Bkeyword,B BtheB BfirstB BpartB BthatB BisB BbeforeB BtheB BfirstB BsemicolonB BseparatesB BtheB BloopB BbyB BdescribingB BaB Bbinding.B BTheB BotherB BpartB BisB BtheB BstatementB BthatB BdeterminesB BifB BtheB BloopB BshouldB Bcontinue.B BHereB BisB BtheB BcodeB BthatB BevaluateB B210B BusingB BforB BinsteadB BofB Bwhile:

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 BconditionB BgiveB BaB Bfalse.B BBreakB BcanB BinfluenceB BjumpingB BoutB BofB BtheB BconfinedB Bloop.B BTheB BbreakB BstatementB BevaluatesB BthisB BprogramB BifB BtheB BfirstB Bnumber,B BwhichB BisB BbothB BgreaterB BthanB BorB BequalB BtoB B20,B BandB BcanB BbeB BdividedB BbyB B7.

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 BanotherB Bnumber.B BIfB BitB BcanB BbeB Bdivided,B BthenB BtheB BremainingB BdivisionB BisB Bzero.B BTheB BforB BinB BtheB BexampleB BisB BnotB BcheckedB BatB BtheB BendB BofB BtheB Bloop,B BwhichB BmeansB BuntilB BtheB BbreakB BstatementB BinsideB BisB BimplementedB BtheB BloopB BbecomesB BinfiniteB BandB BneverB Bstops.

UpdatingB BbindingsB Bsuccinctly

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

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*=B B2B BtoB BmultiplyB BresultB BorB BcounterB B-=B B1B BtoB BcountB BinB BdescendingB Border.

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 Bstraightforwardly.B BBelowB BisB BaB BgoodB Bexample:

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 BseveralB BwordsB BtoB BdefineB BtheB BbindingB Bvalues.B BHereB BareB BaB BfewB BtypesB BthatB BcanB BbeB ButilizedB BwhenB BbindingB BnamesB BwithB BdifferentB Bwords:

fuzzylittleturtle

fuzzy_little_turtle

FuzzyLittleTurtle

fuzzyLittleTurtle

Comments

SometimesB BrawB BcodesB BdoB BnotB BtransmitB BeveryB BsingleB BpieceB BofB BinformationB BthatB ByouB BwantB BtheB BprogramB BtoB BsendB BtoB BreadersB BorB BspreadsB BtheB BmessageB BinB BaB BwayB BpeopleB BwillB BfindB BitB BhardB BtoB Bdecipher.B BOtherB BtimesB ByouB BfeelB BlikeB ByouB BshouldB BattachB BsomeB BsimilarB BthoughtsB BtoB ByourB Bprogram,B BtheB BcommentB BperformsB BthisB Bfunction.B BAB BcommentB BisB BaB BbitB BchunkB BofB BtheB BtextB BcontainedB BinB BaB Bprogram,B BbutB BtheB BcomputerB BignoresB Bit.B BToB BcodeB BaB BsingleB BlineB Bcomment,B BuseB BtheB BtwoB BslashB BcharactersB B(//),B BfollowedB BbyB BtheB BcommentB Btext.

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 BWhereB BtheB BsunB BandB BtheB BmoonB Bmeets:B BaddToReport(accountBalance,B Breport);

//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 BwithinB B/*B BandB B*/B BignoreB Bit,B BandB BitB BdoesB BnotB BmatterB BifB BitB BcontainsB BlineB Bbreaks.B BItB BisB BusedB BtoB BattachB BblocksB BofB BinformationB BaboutB BaB BprogramB BorB Bfile.

Summary

NowB ByouB BunderstandB BthatB ByouB BcanB BdevelopB BaB BprogramB BthroughB BtheB BuseB BofB Bstatements,B BwhichB BstatementB BitselfB BcanB BcontainB BseveralB Bstatements.B BStatementsB BconsistB BofB Bexpressions,B BandB ByouB BcanB BcreateB BexpressionsB BthroughB BsmallerB Bexpressions.B BSettingB BstatementsB BafterB BeachB BanotherB BprovidesB BanB BexecutedB BprogramB BfromB BtopB BtoB Bbottom.B BDisturbancesB BcanB BalsoB BcomeB BintoB BtheB BflowB BofB BinfluenceB BthroughB BconditionalB B(if,B Belse,B BandB Bswitch)B BandB BloopingB B(while,B Bdo,B BandB Bfor)B Bstatements.B BAndB BweB BtouchedB Bbindings,B BtheyB BcategorizeB BbitsB BofB BdataB BunderB BaB Bname,B BandB BtheyB BcanB BalsoB BtrackB BstateB BwithinB BtheB Bprogram.B BTheB BdefinedB BbindingsB BenjoyB BtheB BenvironmentB Bbetter.B BWeB BalsoB BtouchedB BonB BtheB BfunctionsB BsectionB BbeingB BuniqueB BvaluesB BthatB BsummarizeB BaB BpieceB BofB Bprogram.B BYouB BcanB BcallB BthemB BbyB BtypingB BfunctionName(argument1,B Bargument2).B BThisB BtypeB BofB BfunctionB BcallB BisB BanB BexpressionB BandB BcanB BprovideB Bvalue.

Exercise

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

Solution

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

letB BabcB B=B B"abc";

console.log(abc.length);

//B B→B B3

ChapterB B4:B BFunctions

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.

BindingsB BandB Bscopes

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 BsequencesB BoccurredB BbecauseB BfunctionsB BgoB BbackB BtoB BwhereB Bit'sB BcalledB Bposition.B BWhenB BConsole.logB Bcompletes,B BitB BmustB BreturnB BtoB BtheB BendB BofB BtheB Bprogram.B BAB BcallB BstackB BisB BaB BplaceB BwhereB BtheB BcomputerB BstoresB BthisB Bcontext.B BWheneverB ByouB BcallB BaB Bfunction,B BtheB BpresentB BcontextB BsavesB BatB BtheB BtopB BofB BthisB Bstack.B BByB BtheB BtimeB BaB BfunctionB BgoesB Bback,B BitB BeradicatesB BtheB BtopB BcontextB BandB ButilizesB BtheB BcontentB BforB BcontinualB Bexecution.

TheB BstackB BneedsB BspaceB BtoB BbeB BsavedB BintoB BwithinB BtheB BcomputerB Bmemory.B BTheB BbelowB BcodeB BexplainsB BthisB BbyB BqueryingB BtheB BcomputerB BthatB BcreatesB BzeroB BlimitationB BbetweenB BtwoB BfunctionsB BbackB BandB Bforth.

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 Bthree.B BThatB BisB BpossibleB BbecauseB BtheB BprogrammingB BlanguageB BdisregardsB BtheB BsurplusB BargumentsB BandB BrecognizesB BtheB BsquareB BofB BtheB BfirstB Bone.B BJavaScriptB BisB BveryB BtolerantB BaboutB BtheB BamountB BofB BargumentsB BbeingB BpassedB BtoB BaB Bfunction.B BTheB BgoodB BsideB BofB BthisB BcharacterB BisB BthatB BitB BenablesB BcallingB BfunctionsB BwithB BseparateB BnumbersB BofB Barguments:

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 Bexpression,B BtheB BexpressionB BvalueB BwillB BrestoreB BtheB Bnon-specifiedB Bargument.B BIfB ByouB BwantB BtoB BpassB BandB BnotB BproduceB BtheB BsecondB Bargument,B BtheB BdefaultB BbecomesB BtwoB BandB BtheB BfunctionB BactsB BlikeB BaB Bsquare.

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 BthatB BlocalB BbindingsB BareB BcreatedB BagainB BwheneverB ByouB BcallB BaB Bfunction.B BTheB BbelowB BcodeB BdisplaysB BthisB Bexample;B BitB BdescribesB BaB BwrapB Bvalue,B BaB BfunctionB BthatB BdevelopsB BaB BlocalB BbindingB BandB BthenB BsendsB BbackB BaB BfunctionB BthatB BentersB BandB BreturnsB BtheB BlocalB Bbinding.

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 BreferenceB BaB BparticularB BinstanceB BofB BaB BlocalB BbindingB BwithinB BaB BconfiningB Bscope.B BAddingB BaB BfewB Bchanges,B BourB BpreviousB BexampleB BcanB BturnB BintoB BaB BwayB BtoB BdevelopB BfunctionsB BthatB BaccumulatesB BbyB BanB BarbitraryB Bamount.

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 BavoidB BstackB Boverflow.B BRecursiveB BfunctionB BisB BaB BfunctionB BthatB BcallsB Bitself.B BRecursionB BenablesB BfewB BfunctionsB BwrittenB BinB BseparateB Bstyles.B BForB Binstance,B BtheB BbelowB BcodeB BisB BtheB BexecutionB BofB Bpower.

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 BtoB BotherB BloopingB Bversions.B BUtilizingB BaB BsingleB BloopB BisB BconsideredB BlowB BcostB BthanB BtheB BmultipleB BcallingB BofB Bfunctions.B BAlthoughB BthatB BdoesB BnotB BmakeB BrecursionB BanB BineffectiveB BoptionB BofB Blooping,B BfewB BproblemsB BareB BsolvedB BwithB BrecursionB BeasierB BthanB BwithB BtheB BuseB BofB Bloops.B BProblemsB BthatB BneedB BinspectingB BorB BprocessingB BseveralB Bbranches.B BCheckB BthisB Bout:B BweB BbeginB BfromB BnumberB B1B BandB BcontinuouslyB BaddB B5B BorB BmultiplyB BbyB B3.B BForB Binstance,B BtheB BnumberB B13B BcanB BbeB BobtainedB BbyB BmultiplyingB BbyB B3B BandB BtheB BadditionB BofB B5B Btwice,B BtherebyB BweB BcannotB BattainB BtheB B15.B BTheB BcodeB BisB BtheB BrecursiveB Bsolution:

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 BandB BaB BstringB BthatB BdocumentsB BtheB BprocessB BofB BattainingB BthisB Bnumber.B BIfB BaB BsolutionB BisB Bfound,B BitB BsendsB BbackB BaB BstringB BthatB BdisplaysB BtheB BrouteB BtoB BtheB BtargetB BandB BifB BnoB BsolutionB BisB Bfound,B BtheB BreturnedB BvalueB BwillB BbeB Bnull.B BToB BachieveB Bthis,B BtheB BfunctionB BexecutesB BoneB BofB BthreeB Bactions.B BIfB ByourB BtargetB BisB BtheB BisB BtheB BcurrentB Bnumber,B ByouB BcanB BattainB BthatB BtargetB BbyB BusingB BtheB BcurrentB BhistoryB BsoB BitB BisB BsentB Bback.B BSometimesB BtheB BnumberB BisB BlargerB BthanB BtheB Btarget,B BbutB ByouB BdoB BnotB BneedB BtoB BexploreB BthisB BoptionB BbecauseB BadditionB BandB BsubtractionB BcanB BonlyB BenlargeB BtheB BnumberB BsoB BitB BisB BsentB BbackB BasB Bnull.B BIfB ByouB BremainB BbeneathB BtheB BtargetB Bnumber,B BbothB BpathsB BthatB BbeginB BtheB BcurrentB BnumberB BisB BtriedB BbyB BcallingB BitselfB Btwice,B BoneB BtoB BaddB BandB BtheB BotherB BtoB Bmultiply.B BIfB BtheB BfirstB BcallB BsendsB BsomethingB BvalidB BbackB BinB Breturn,B BthenB Bgood,B BifB Bnot,B BreturnB BtheB BsecondB Bcall,B BitB BdoesB BnotB BmatterB BwhetherB BaB BstringB BorB BnullB BisB Bprovided.B BBelowB BisB BanB BillustrationB BofB BhowB BfunctionsB BprovideB Beffects.B BThisB BexampleB BsearchesB BforB BaB BremedyB BforB BtheB BnumberB B13.

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.

GrowingB Bfunctions

FunctionsB BcanB BbeB BintroducedB BintoB BprogramsB BinB BtwoB Bways.B BTheB BfirstB BisB BbyB BwritingB BsimilarB BcodesB BaB BlotB BofB Btimes,B BwhichB BenablesB BmoreB BmistakesB BwhileB BtheB BsecondB BisB BtoB BsearchB BforB BaB BfewB BfunctionalitiesB BthatB BhaveB BnotB BbeenB BwrittenB BandB BdeservesB BitsB BownB Bfunction.B BYouB BcanB BbeginB BbyB BnamingB BtheB BfunctionB BandB BwriteB BtheB Bbody.B BBelowB BisB BanB Bexample.B BWeB BwillB BwriteB BaB BprogramB BthatB BreproduceB BtwoB Bnumbers–theB BamountB BofB BchickenB BandB BcowsB BavailableB BonB BaB Bfarm.

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 BtheB BparticularB Bstring.B BTheB BloopB BcontinuesB BtoB BaddB BzerosB BatB BtheB BbeginningB BofB BtheB BnumberB BstringsB BuntilB BtheyB BcompriseB BofB BthreeB Bcharacters.

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 Bscopes.B BEveryB BblockB BbuildsB BaB BnewB Bscope.B BParametersB BandB BbindingsB BsetB BinB BaB BspecificB BscopeB BareB BlocalB BandB BinvisibleB BfromB BtheB Boutside.B BBindingsB BsetB BwithB BvarB BactB Bdifferently,B BandB BtheyB BresultB BinB BtheB BglobalB Bscope.B BDifferentiatingB BtheB BtasksB BthatB BtheB BprogramB BexecutesB BintoB BvariousB BfunctionsB BisB Bimportant.B BYouB BdoB BnotB BneedB BtoB BrepeatB ByourselfB Boften,B BandB BfunctionsB BcanB BarrangeB BaB BprogramB BbyB BcategorizingB BcodeB BintoB BbitsB BthatB BperformB BspecificB Bactions.

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BseeB BifB BaB BnumberB BisB BevenB BorB Bnot.

Solution

B B

ChapterB B5:B BDataB BStructures:B BObjectsB BandB BArrays

DataB BlayoutsB BdevelopB BfromB BBooleans,B Bstrings,B BandB BnumbersB Bfragments.B BSeveralB BtypesB BofB BinformationB BuseB BmoreB BthanB BoneB Bchunk.B BObjectsB BenableB BtheB BuserB BtoB BcollateB BvaluesB BtogetherB BwithB BotherB BobjectsB BtoB BdevelopB BmoreB BcompoundB Blayouts.B BInB BthisB Bchapter,B ByouB BwillB BunderstandB BtheB BconceptsB BofB BsolvingB BaB BrealB BproblemB BatB Bhand.

DataB Bsets

IfB ByouB BwantB BtoB BworkB BwithB BaB BlotB BofB BdigitalB Bdata,B ByouB BmustB BrepresentB BtheB BdigitalB BdataB BinB BtheB BmachineB Bmemory.B BForB Binstance,B ByouB BneedB BtoB BrepresentB BaB BgroupB BofB BnumbersB BlikeB B2,B B3,B B5,B B7,B BandB B11.B BNowB Blet’sB BgetB BprolificB BwithB BourB BuseB BofB BstringsB BasB BstringsB BcanB BcontainB BquiteB BaB BlotB BofB Bdata.B BWeB BwillB BuseB B2B B3B B5B B7B B11B BasB BtheB Brepresentation.B BJavaScriptB BprogrammingB BlanguageB BoffersB BaB BuniqueB BdataB BtypeB BforB BsavingB BsequencesB BofB Bvalues,B BwhichB BisB BcalledB BanB Barray.B BWriteB BanB BarrayB BasB BaB BlistB BofB BvaluesB BwithinB BtheB BbetweenB BsquareB Bbrackets,B BdifferentiatedB BbyB Bcommas.

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 BtheB BsquareB Bbrackets.B BAB BcompleteB BsquareB BbracketsB BpairB BrightB BafterB BanB BexpressionB BthatB BcontainsB BanotherB BexpressionB Bwithin.B BWhenB ByouB BstartB BcountingB BelementsB BinB BanB Barray,B ByouB BbeginB BfromB BzeroB BandB BnotB Bone.B BThereforeB BtheB BfirstB BelementB BisB BredeemedB BwithB BlistOfNumbers[0].

Properties

TheB BpreviousB BchaptersB BhaveB BcontainedB BexpressionsB BlikeB BtheB BmyString.B BLengthB B(toB BcalculateB BtheB BlengthB BofB BaB Bstring)B BandB BMath.maxB B(theB BmaximumB Bfunction).B BTheseB BareB BpropertiesB BthatB BcanB BapproachB BtheB BpropertyB Bvalues.B BVirtuallyB BallB BJavaScriptB BvaluesB BcontainB Bproperties.B BTheB BfewB BvaluesB BthatB BdoB BnotB BcontainB BpropertiesB BareB BnullB BandB Bundefined.B BIfB ByouB BaccessB BaB BpropertyB BwithB BaB Bnonvalue,B BtheB BresultB BwillB BbeB BanB Berror.

null.length;

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

InB BJavaScript,B BtheB BtwoB BmajorB BwaysB BtoB BevaluateB BpropertiesB BareB BwithB BaB BdotB BandB BsquareB Bbrackets.B BTheB Bvalue.xB BandB Bvalue[x]B BcanB BevaluateB BtheB BpropertyB BonB Bvalue,B BnotB BparticularlyB BtheB BsameB Bproperty.B BHowB ByouB BuseB BxB BisB BdifferentB BfromB BhowB ByouB BuseB BaB Bdot.

IfB ByouB BwantB BtoB BuseB BtheB Bdot,B BtheB BtextB ByouB BinputB BafterB BtheB BdotB BisB BtheB BnameB BofB BtheB Bproperty.B BAndB BifB Byou'reB BgoingB BtoB BuseB BtheB BsquareB Bbrackets,B BtheB BexpressionB BwithinB BtheB BbracketsB BisB BaccessedB BtoB BredeemB BtheB BpropertyB Bname.B BValue.xB BdeliversB BtheB BpropertyB BofB BvalueB BcalledB B“x,”B BwhileB Bvalue[x]B BaccessesB BtheB BexpressionB BxB BandB ButilizeB BtheB Bresult,B BtransformedB BintoB BaB BstringB BasB BtheB BnameB BofB BtheB Bproperty.B BIfB BtheB BpropertyB ByouB BwantB BisB BnamedB Bcolor,B ByouB BshouldB BtypeB Bvalue.color.B BYouB BcanB BwithdrawB BtheB BpropertyB BthatB BtheB BvalueB BcalledB BwithinB BtheB BbindingB Bi,B BtypeB Bvalue[i].B BTheB BnameB BofB BpropertiesB BareB Bstrings,B BbutB BtheB BdotB BnotationB BperformsB BwithB BonlyB BvalidB BbindingB Bnames.B BThereforeB BifB ByouB BwantB BtoB BevaluateB BaB BpropertyB BnamedB B2B BorB BJohnB BDoe,B BuseB BtheB BsquareB Bbrackets:B Bvalue[2]B BorB Bvalue["JohnB BDoe"].

TheB BelementsB BwithinB BanB BarrayB BsaveB BasB BtheB BpropertiesB BofB BanB BarrayB BthatB ButilizeB BnumbersB BasB BpropertyB Bnames.B BAnB Barray'sB BlengthB BpropertyB BdeterminesB BhowB BmanyB BitemsB BitB Bcontains.B BTheB BnameB BofB BthatB BpropertyB BisB BaB Bvalid,B BbindingB Bname.B BTypeB Barray.lengthB BtoB BdetermineB BtheB BlengthB BofB BanB Barray,B BitB BisB BmuchB BeasierB BtoB BtypeB BthanB BtheB Barray["length"].

Methods

TheB BstringB BandB BarrayB BobjectsB BaccommodateB BseveralB BpropertiesB BthatB BstoreB BfunctionB Bvalues.

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 BthisB Bproperty,B BitB BsendsB BbackB BaB BcopyB BofB BtheB BstringB BwherebyB BallB BtheB BcontainingB BlettersB BtransformB BintoB Buppercase.B BAlthoughB BtheB BtoUpperCaseB BdoB BnotB BgoB BthroughB BanB Bargument,B BtheB BfunctionB BcanB BevaluateB BtheB BstringB B"Doh,"B BwhichB BisB BtheB BpropertyB BofB BtheB BvalueB BweB BcalledB Babove.B BPropertiesB BthatB BconsistB BofB BfunctionsB BareB BknownB BasB Bmethods.B BTheB BbelowB BexampleB BillustratesB BtwoB BmethodsB BthatB BcanB BbeB BusedB BtoB BinfluenceB Barrays.

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 BarrayB BwhileB BtheB BpopB BmethodB BdoesB BtheB BdirectB Bopposite.B BItB BeradicatesB BtheB BlastB BvalueB BwithinB BanB BarrayB BandB BsendsB BitB Bback.B BTheseB BareB BgenerationalB BtermsB BofB BoperationsB BonB BaB Bstack.B BAB BstackB BisB BaB BdataB BlayoutB BthatB BenablesB BusersB BtoB BpushB BvaluesB BinB BandB BpopB BthemB BoutB BinB BtheB BoppositeB BdirectionB BsoB BthatB BtheB BaddedB BvalueB BwillB BremoveB Bfirst.

Objects

YouB BcanB BrepresentB BaB BgroupB BofB BlogB BentriesB BasB BanB BarrayB BalthoughB BeachB BstringB BentryB BisB BrequiredB BtoB BsaveB BaB BlistB BofB BactivitiesB BasB BwellB BasB BaB BBooleanB BvalueB BthatB BspecifiesB BifB BJacquesB BtransformedB BtoB BaB 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 BcollectionsB BofB BpropertiesB BareB BtheB BvalueB BofB BtheB BtypeB Bobject.B BWeB BwillB BdevelopB BanB BobjectB ButilizingB BbracesB BasB BanB Bexpression.

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 BaB BnamedB Bproperty.B BTheB BmajorB BdifferentiationB BbetweenB BspecifyingB BaB BpropertyB BtoB BundefinedB BandB BdeletingB BitB BisB BthatB BtheB BobjectB BconsistsB BofB BaB BpropertyB BandB BtheB BdeletingB BdoesB BnotB BpossessB BtheB Bproperty,B BsoB BtheB BvalueB BreturnsB BasB Bfalse.B BToB BdetermineB BwhatB BpropertiesB BcontainedB BinB BanB BobjectB BandB BsendsB BbackB BanB BarrayB BofB BstringsB BwithB BpropertyB BnamesB BofB BtheB Bobject.

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 BobjectB BtoB Banother.

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 BWhenB ByouB BaccessB BtheB BtypeofB B[],B BitB BprovidesB B"object."B BTheB BbelowB 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 BareB BidenticalB BbyB Bnature.B BTheB BbindingB Bobject3B BpointsB BtoB BaB BseparateB BobjectB BthatB BconsistsB BofB BsimilarB BpropertiesB BasB BtheB Bobject1B BbutB BhasB BaB BdifferentB Blife.B BBindingsB BcanB BbeB BconstantB BorB Bchangeable,B BbutB BitB BdoesB BnotB BinfluenceB BtheirB Bvalues.B BAB BconstB BbindingB BanB BobjectB BcannotB BbeB BtransformedB BandB BrelentlesslyB BpointingB BtoB BtheB BsameB Bobject.B BItB BisB BtheB BobjectB BcontentsB BthatB BcanB BbeB Bchanged.

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 BitB BusesB BtheB BidentityB BtoB BperformB BthatB Btask.B BItB BwillB BtranslateB BtrueB BifB BtheB BobjectsB BcontainB BtheB BsameB Bvalue.B BDifferentiatingB BseveralB BobjectsB BwillB BreturnB Bfalse,B BevenB BifB BtheirB BpropertiesB BareB Bsimilar.

TheB Blycanthrope'sB Blog

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

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 BpropertyB Bname.

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

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

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 Bvariables.B BTheyB BareB BknownB BasB BvaluesB BthatB BspanB BfromB B-1B BtoB B1.B BAnB BUnrelatedB BvariableB BisB BcalledB BaB BzeroB Bcorrelation.B BAB BcorrelationB BofB B1B BsignifiesB BthatB BtheB BtwoB BareB Brelated.B BNegativeB BmeansB BthatB BtheB BvariablesB BareB BrelatedB BperfectlyB BbutB BoppositesB BtoB BeachB Bother;B BoneB BisB Btrue,B BandB BtheB BotherB BisB Bfalse.B BToB BcalculateB BtheB BevaluationB BofB BtheB BcorrelationB BbetweenB BtwoB BBooleanB Bvalues,B ButilizeB BtheB BphiB BcoefficientB B(φ).B BThisB BformulaB BinputB BisB BaB BfrequencyB BtableB BholdingB BtheB BnumberB BofB BtimesB BitB BnoticesB BseveralB BmixturesB BofB BtheB Bvariables.B BTheB Bformula'sB BoutputB BwillB BbeB BaB BnumberB BbetweenB B-1B BandB B1.B BThatB BisB BtheB BbestB BdefinitionB BofB BaB Bcorrelation.

LetB BusB BuseB BtheB BeventB BifB BeatingB BpizzaB BasB BanB BexampleB BandB BinsertB BitB BintoB BaB BfrequencyB BtableB BwherebyB BeveryB BnumberB BsignifiesB BtheB BtotalB BofB Btimes,B BandB BweB BusedB BtheB BcombinationB BinB BourB Bmeasurements.B BWeB BnameB BtheB BtableB Bn,B BandB BweB BcalculateB BφB BwithB BtheB BbelowB Bformula:

φB B=

n11n00B B−B Bn10n01

√

n1•n0•n•1n•0

TheB BnotationB Bn01B BsignifiesB BtheB BnumberB BofB BmeasurementsB BwhereB BtheB BfirstB BvariableB BturnsB BfalseB B(0),B BandB BtheB BsecondB BvariableB BbecomesB BtrueB B(1).B BTheB BpizzaB Btable,B Bn01B BisB B9.

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 BsecondB BvariableB BbecomesB Bfalse.

TheB BpizzaB Btable,B BtheB BtopB BofB BtheB BdivisionB BlineB BwouldB BbeB B1×76−4×9B B=B B40,B BandB BtheB BbelowB BpartB BbelowB BwouldB BbeB BtheB BsquareB BrootB BofB B5×85×10×80,B BorB B√340000.B BTheB BresultB BwillB BbeB BφB B≈B B0.069,B BwhichB BisB Btiny.B BTherefore,B BeatingB BpizzaB BhadB BnoB BimpactB BonB Btransformations.

ComputingB Bcorrelation

JavaScriptB BenablesB BtheB BrepresentationB BofB BaB Btwo-by-twoB BtableB BwithB BfourB BelementB BarraysB B([76,B B9,B B4,B B1]).B BOtherB BrepresentationsB BsuchB BasB BanB BarrayB BholdingB BtwoB Btwo-elementB B([[76,B B9],B B[4,B B1]])B BorB BanB BobjectB BcontainingB BpropertyB BnamesB BsuchB BasB B"11"B BandB B"01",B BandB BtheB BflatB Barray,B BwhichB BproducesB BtheB BexpressionB BthatB BaccessB BtheB BchairB Bshort.B BWeB BwillB BexplainB BtheB BindicesB BtoB BtheB BarrayB BasB Btwo-bitB BbinaryB Bnumbers,B BwhereB BtheB BmostB BsignificantB BdigitB BrefersB BtoB BtheB BsquirrelB BvariableB BwhileB BtheB BleastB BsignificantB BrefersB BtoB BtheB BeventB Btable.B BForB Binstance,B BtheB BbinaryB BnumberB B10B BrefersB BtoB BtheB B"JacquesB BdidB BturnB BintoB BaB Bsquirrel"B BcaseB BbutB BtheB BeventsB Bdidn’tB Bappear.B BItB BoccurredB BfourB BtiesB BandB BbinaryB BisB B2B BinB Bdecimal,B BtheB BnumberB BisB BstoredB BasB BanB BindexB B2B BofB BtheB Barray.B BThisB BfunctionB BcalculatesB BtheB BφB BcoefficientB BfromB BanB Barray:

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 BtheB BtotalB BnumberB BofB BrowsB BandB BcolumnsB BareB BstoredB BindirectlyB BintoB BourB BdataB Blayout.B BIfB ByouB BwantB BtoB BextractB BaB Btwo-by-twoB BtableB BforB BaB BparticularB Bevent,B ByouB BmustB BloopB BacrossB BallB BtheB BentriesB BandB BcalculateB BtheB BnumberB BofB BtimesB BtheB BeventB BhappenedB BtoB BtheB BsquirrelB Btransformations.

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 BsetB BvalueB BexistsB BinB BtheB Barray.B BThisB BmethodB BisB BusedB BbyB BtheB BfunctionB BtoB BdecideB BifB BtheB BeventB BnameB BisB BinterestedB BtheB BstatedB BeventB BlistB BforB BaB BgivenB Bday.

ArrayB Bloops

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 BtheB BvalueB BspecifiedB BafterB Bof.B BThisB BloopB BisB BusedB BforB BstringsB BandB BotherB BdataB Blayouts.

TheB BfinalB Banalysis

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

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 BareB BnotB BinB BtheB BeventsB Barray,B BthisB BfunctionB BgathersB BallB BtheB BtypeB BofB Bevent.

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

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 BthanB B0.1B BorB BlessB BthanB B-0.1.

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 BpeanutsB BhasB BaB BpowerfulB BchanceB BofB BtransformingB BintoB BaB Bsquirrel,B BtherebyB BbrushingB BtheB BteethB BhasB BaB BnotableB BnegativeB Beffect.B BHere'sB Bsomething:

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 BWeB BbeginB BwithB BtheB BuseB BofB BsomeB BusefulB BmethodsB BofB BanB Barray.

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

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 BwhenB ByouB BwantB BtoB BgetB BsomethingB Bdone,B BcallB BgetTask()B BtoB BgetB B(andB Bremove)B BitemB BfromB BtheB Bqueue.B BIfB ByouB BwantB BtoB BsearchB BforB BaB BparticularB Bvalue,B BarraysB BsupplyB BanB BindexOfB Bmethod.B BTheB BmethodB BfindsB BitsB BwayB BthroughB BtheB BarrayB BfromB BtheB BbeginningB BtoB BtheB BendB BandB BsendsB BbackB BtheB BindexB BtheB BvalueB Brequested,B BifB BitB BwasB BfoundB BitB BreturnsB B—orB B-1B BifB BitB Bwasn’tB Bfound.B BToB BsearchB BfromB BtheB BbeginningB BtoB BtheB Bend,B BuseB BtheB BlastIndexOfB Bmethod.

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 BspecifiesB BwhereB BtheB BsearchB Bbegins.B BAnotherB BgreatB BmethodB BisB BtheB Bslice,B BthisB BmethodB BbeginsB BandB BendsB BtheB BindicesB BandB BsendB BbackB BanB BarrayB BcontainingB BthreeB Belements.B BTheB BbeginningB BisB BinclusiveB BwhileB BtheB BendB BisB Bexclusive.

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 BtheB BstartB Bindex.B BYouB BcanB BuseB BtheB BconcatB BmethodB BtoB BglueB BarraysB BtogetherB BtoB BproduceB BaB BnewB Barray.B BTheB BbelowB BexampleB BdisplaysB BconcatB BandB BsliceB BinB Baction.

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 Bstick.

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 BindexOfB BwhichB BhaveB BaB BsimilarB BappearanceB BofB BarrayB BmethodsB BasB BwellB BasB BtheB Bname.

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 Bcharacter,B BwhileB BtheB BcorrespondingB BarrayB BmethodB BsearchB BforB BaB BsingleB Belement.

console.log("oneB BtwoB Bthree".indexOf("ee"));

//B B→B B11

TheB BtrimB BmethodB BeradicatesB BwhitespaceB BfromB BtheB BbeginningB BtoB BtheB BendB BofB BaB Bstring.

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 BpreferredB BpaddingB BandB BlengthB BcharacterB BasB Barguments.

console.log(String(6).padStart(3,B B"0"));

//B B→B B006

YouB BcanB BbreakB BaB BstringB BonB BeveryB BdevelopmentB BofB BanotherB BstringB BwithB BsplitB BandB BthenB BjoinB BthemB BtogetherB BwithB Bjoin.

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 BdevelopsB BaB BnewB BstringB BholdingB BseveralB BcopiesB BofB BtheB BoriginalB BstringB BattachedB Btogether.

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

//B B→B BLALALA

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

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 Barguments.B BIfB ByouB BwantB BtoB BwriteB BsuchB BaB Bfunction,B BaddB BthreeB BdotsB BbeforeB BtheB BlastB BparameterB BofB BtheB Bfunction.

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 BanB BarrayB BholdingB BtheB BrestB BofB BtheB Barguments.B BYouB BcanB BalsoB ButilizeB BtheB BthreeB BdotB BnotationB BtoB BcallB BfunctionsB BwithinB BanB BarrayB BofB Barguments.

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 BdifferentB Barguments,B BlikeB BmaxB B(9,B B...numbers,B B2).B BTheB BSquareB BbracketB BarrayB BnotationB BenablesB BtheB Btriple-dotB BoperatorB BbringB BanotherB BarrayB BintoB BaB BnewB Barray.

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 Bfunctionality.B BItB BproducesB BaB BnamespaceB BtoB BenableB BvaluesB BaB BfunctionsB BandB BfunctionsB BwithoutB BglobalB Bbindings.B BThisB BisB BtheB BoldB BwayB BtoB BwriteB BtheB BconstantB BvalueB BnameB BinB BallB Bcaps.

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 BbetweenB BzeroB BandB BoneB BwheneverB ByouB BcallB Bit.

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 Bone,B ByouB BcanB ButilizeB BtheB BMath.floorB BonB BtheB BoutcomeB BofB BtheB BMath.random.

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 BgreaterB BthanB BorB BequalB BtoB B0B BandB BbelowB B10.B BRememberB BtheB BMath.floorB BroundsB Bdown,B BtheB BoutputB BwillB BbeB BanyB BnumberB BfromB B0B BthroughB B9.B BTheB BmathB BobjectB BcontainsB BseveralB BfunctionsB BlikeB BtheB BMath.ceil,B BwhichB BroundsB BupB BtoB BaB BwholeB Bnumber,B BandB BtheB BMath.round,B BwhichB BroundsB BupB BtoB BtheB BnearestB BwholeB Bnumber,B BandB BMath.abs,B BthisB BfunctionB BtakesB BtheB BentireB BvalueB BofB BaB Bnumber.

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 BthereB BisB BaB BbindingB BdirectedB BtoB BtheB Barray,B BbutB BweB BwantB BbindingsB BforB BtheB BelementsB BofB BtheB Barray,B BthatB Bis,B BletB Bn00B B=B Btable[0]B BandB BsoB Bon.B BAlthough,B BthereB BisB BaB BbetterB BwayB BtoB BgetB BthisB BdoneB BinB BJavaScript.

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 BbyB BtheB Bleft,B Bvar,B BorB Bconst.B BIfB ByourB BpreferredB BbindingB BvalueB BisB BanB Barray,B ButilizeB BtheB BsquareB BbracketsB BtoB BcheckB BforB BtheB BvalueB BofB BitsB BbindingB Bcontents.B BUseB BtheB BsameB BconceptB BforB Bobjects,B ButilizeB BtheB BbracesB BandB BnotB BtheB BsquareB Bbrackets.

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 BcommunicationB BformatB BandB BdataB BstorageB BforB BtheB Bweb.B BJSONB BisB BveryB BsimilarB BtoB BJavaScriptB BinB BitsB BwritingB BstyleB BofB BarraysB BandB Bobject,B BalthoughB BthereB BareB Brestrictions.B BItsB BpropertyB BnamesB BshouldB BbeB BenclosedB BwithinB BdoubleB Bquotes,B BitB BallowsB BonlyB BsimpleB BdataB Bexpressions,B BbindingB Betc.B BJSONB BdoB BnotB BallowB Bcomments.

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 BtoB BtransformB BdataB BtoB BandB BfromB BthisB Bformat.B BJSON.stringifyB BtakesB BaB BJavaScriptB BvalueB BandB BsendsB BbackB BaB BJSON-encodedB BstringB BwhileB BJSON.parseB BtakesB BaB BstringB BandB BtransformsB BitB BtoB BitsB BencodedB Bvalue.

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 BarrayB BbyB BreversingB BtheB BorderB BthatB BitsB BelementsB Bdisplay.

Summary

WeB BcoveredB BtheB BobjectsB BandB BarraysB BinB BthisB Bchapter,B BandB BtheyB BcreateB BwaysB BtoB BcategorizeB BvariousB BvaluesB BinB BaB BsingleB Bvalue.B BFancifully,B BthisB BenablesB ByouB BtoB BinsertB BseveralB BassociatedB BitemsB BinB BaB BbagB BandB BmoveB BaboutB BwithB BtheB Bbag,B BratherB BthanB BenclosingB ByourB BarmsB BaroundB BeveryB BsingularB BthingB BandB BtryingB BtoB BkeepB BthemB Bdifferently.B BAB BlotB BofB BvaluesB BinB BJavaScriptB BcontainB Bproperties,B BtheB BinconsistencyB BbeingB BundefinedB BandB Bnull.B BYouB BcanB BaccessB BpropertiesB BusingB BtheB Bvalue.propB BorB Bvalue["prop"].B BYouB BcanB BuseB BnamesB BforB BobjectsB BpropertiesB BandB BsaveB BaB BdefinedB BsetB BofB Bthem.B BArrays,B BasB BwellB BcontainB BdifferentB BamountsB BofB BsimilarB BfancifulB BvaluesB BandB ButilizeB BtheB BnumbersB B(beginningB BfromB B0)B BasB BtheB Bproperty’sB Bnames.B BArraysB BcontainB BfewB BsetsB BofB Bproperties,B BwhichB BareB BtheB BlengthB BandB BseveralB Bmethods.B BMethodsB BareB BfunctionsB BthatB BresideB BwithinB BpropertiesB BandB BbehaveB BonB BtheB BvalueB BtheyB BareB BitsB Bproperty.B BYouB BcanB BloopB BacrossB BarraysB BthroughB BaB BuniqueB BtypeB BofB BforB Bloop—forB B(theB BletB BelementB BofB BanB Barray).

Exercise

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

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

ChapterB B6:B BHigher-OrderB BFunctions

AB BlargeB BprogramB BtakesB BtimeB BtoB BdevelopB BandB BproducesB BaB BlotB BofB BspaceB BforB BbugsB BtoB Bhide,B BwhichB BinB BturnB BmakesB BthemB BhardB BtoB Bfind.B BHereB BareB BexamplesB BofB BtwoB BlargeB Bprograms:

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 BisB BoneB BlineB Blong.

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

Abstraction

WhenB BitB BcomesB BtoB BJavaScriptB BprogrammingB Blanguage,B Bvocabulary’sB BuseB BtheB BtermB Babstraction.B BAbstractionB BisB BusedB BtoB BhideB BdetailsB BandB BgivesB BtheB BuserB BtheB BcapabilityB BtoB BtalkB BaboutB BproblemsB BonB BaB BhigherB Blevel.B BLetB BusB BdifferentiateB BtwoB BrecipesB BforB BpeaB Bsoup.B BFirst:

PerB Bperson,B BplaceB B1B BcupB BofB BdriedB BpeasB BwithinB BaB Bcontainer.B BPutB BenoughB BwaterB BtoB BcoverB BtheB Bpeas,B BletB BitB BsoakB BforB BaboutB B12B Bhours.B BRemoveB BitB BfromB BtheB BwaterB BandB BplaceB BitB BinB BaB BpotB BusedB BforB BcookingB BwithB BtheB BadditionB BofB BwaterB BfourB BcupsB BofB BwaterB B(4B Bcups).B BLetB BitB BboilB BforB BaboutB BtwoB Bhours,B Bper-personB BholdB BhalfB BofB BanB Bonion,B BsliceB BitB BusingB BaB Bknife,B BandB BpourB BitB BintoB BtheB Bpeas,B BletB BitB BprepareB BforB B10B Bminutes.

ThenB BtheB BsecondB Brecipe

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

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

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 BaB BprogramB BtoB BrepeatB BaB BparticularB BfunctionB BaB BspecifiedB BamountB BofB Btime.B ByouB BcanB BachieveB BthatB BwithB BaB BloopB BlikeB Bthis:

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 ByouB BcanB BrollB BactionB BasB BaB BfunctionB Bvalue.

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 BelementB BtoB Breceive.

TransformingB BwithB Bmap

TheB BmapB BmethodB BchangesB BanB BarrayB BbyB BsettingB BaB BfunctionB BtoB BeachB BandB BeveryB BofB BitsB BelementsB BandB BcreatingB BaB BnewB BarrayB BfromB BtheB BreturnedB Bvalues.B BTheB BnewB BarrayB BconsistsB BofB BtheB BsameB BlengthB BwithB BtheB BinputB BarrayB BbutB BwillB BmapB BoutB BitsB BcontentB BtoB BaB BrenewedB BforB BbyB BtheB Bfunction.

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 BelementB BtoB BtheB Bsum.B BTheB BparameterB BtoB BreduceB BareB BmapB BfunctionB BcombinationB BandB BbeginB BaB Bvalue.B BThisB BfunctionB BisB BmuchB BeasierB BtoB BunderstandB BthanB BtheB BfilterB BandB Bmap.B BItB BisB Bbelow:

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 Boperations.B BForB Binstance,B BhereB BisB BaB BlineB BofB BcodeB BthatB BsearchesB BforB BtheB BaverageB ByearB BforB BlivingB BandB BdeadB BinB Bhumans’B BscriptsB BinB BtheB BdataB Bset.

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 BtheB BlivingB Bones.

Let’sB BbeginB BwithB BtheB BentireB Bscript,B BfilterB BoutB BtheB BdeadB B(orB Bliving),B BeradicateB BtheirB Byears,B BaverageB BthemB BandB BcompleteB BtheB Bresult.B BYouB BcanB BasB BwellB BwriteB BtheseB BcalculationsB BasB BaB BbigB Bloop:

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 BwhenB BadministeringB BtheB BmapB BandB BfilterB BwhileB BtheB BsecondB BcalculateB BnumbersB Bonly.

StringsB BandB BcharacterB Bcodes

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

EveryB BscriptB BcontainsB BanB BarrayB BofB BcharacterB BcodeB BrangesB BrelatedB BwithB Bit.B BSo,B BifB ByouB BareB BgivenB BaB BcharacterB Bcode,B ButilizeB BthisB BfunctionB BtoB BsearchB BforB BtheB BequivalentB BscriptB B(ifB Bavailable):

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 BgetsB BaB BtestB BfunctionB BandB BdetermineB BifB BthatB BfunctionB BsendsB BbackB BtrueB BforB BanyB BcomponentB BinB BtheB Barray.

ThereB BareB BsomeB BoperationsB BonB BJavaScriptB BstringsB BlikeB BsecuringB BtheirB BlengthB BusingB BtheB BlengthB BpropertyB BandB BevaluatingB BtheirB BcontentsB BthroughB BtheB BsquareB Bbrackets.

//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 BThisB BmethodB BisB BusedB BtoB BtakeB BcharactersB BfromB BaB Bstring.B BAlthoughB BtheB BargumentB BsentB BtoB BcodePointAtB BremainsB BanB BindexB BintoB BtheB BsuccessionB BofB BcodeB Bunits.B BIfB ByouB BuseB BtheB BcodePointAtB BtoB BloopB BacrossB BaB Bstring,B BitB BproducesB BrealB BcharactersB BandB BnotB BcodeB Bunits.

letB BroseDragonB B=B B"🌹🐉";

forB B(letB BcharB BofB BroseDragon)B B{

console.log(char);

}

//B B→B B🌹

//B B→B B🐉

RecognizingB Btext

YouB BhaveB BtheB BcharacterB BScriptB BfunctionB BandB BaB BwayB BtoB BloopB BacrossB BcharactersB Bcorrectly,B BnowB BcalculateB BtheB BcharactersB BeachB BscriptB Bowns.B BTheB BbelowB BcountingB BabstractionB BisB BusedB Bhere:

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 Bnumbers,B BelementB BorB BanythingB BthatB ByouB BcanB BloopB BoverB BwithB Bfor/of)B BandB BaB BfunctionB BthatB BcalculatesB BaB BgroupB BnameB BforB BaB BspecifiedB Belement.B BItB BsendsB BbackB BaB BlistB BofB Bobjects.B BEachB BofB BtheB BobjectsB BnamesB BaB BgroupB BandB BdeterminesB BtheB BnumberB BofB BelementsB BcontainedB BinB BtheB Bgroup.

TheB BmethodB BfindIndexB BisB BsimilarB BtoB BindexOf.B BThisB BmethodB BisB BusedB BtoB BsearchB BforB BtheB BfirstB BvalueB BforB BwhichB BtheB BstatedB BfunctionB BsendsB BbackB BtrueB BandB BreturnsB B-1B BwhenB BzeroB BelementsB BisB Bfound.B BYouB BcanB BuseB BtheB BcountByB BtoB BdetermineB BwhichB BscriptB BisB ButilizedB BinB BaB BblockB BofB Btext.

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 BofB BcharacterScriptB BtoB BattachB BaB BnameB BandB BreturningB BbackB BtoB BtheB BstringB B"none"B BforB BcharactersB BwithoutB BanyB Bscript.B BIfB ByouB BwantB BtoB BcalculateB Bpercentages,B ByouB BneedB BtoB BdetermineB BtheB BtotalB BamountB BofB BcharactersB BbelongingB BtoB BaB BscriptB BthatB BtheB BreduceB BmethodB BcanB Breduce.B BIfB BitB BfindsB BzeroB Bcharacters,B BtheB BfunctionB BsendsB BbackB BtheB B"none"B Bstring.

Summary

HavingB BtheB BabilityB BtoB BsendB BfunctionB BvaluesB BtoB BseveralB BfunctionsB BisB BanB BessentialB BaspectB BofB BJavaScript.B BItB BenablesB BwritingB BfunctionsB BthatB BimitateB BcomputationsB BwithB B“gaps”B BbetweenB Bthem.B BTheB BcodeB BthatB BdeclaresB BtheseB BfunctionsB BcanB BcontainB BtheB BgapsB BbyB BgivingB BfunctionB Bvalues.B BArraysB BprovideB BseveralB BimportantB Bhigher-orderB Bmethods.B BUseB BforEachB BtoB BloopB BacrossB BelementsB BwithinB BanB Barray.B BUseB BtheB BfilterB BmethodB BtoB BsendB BbackB BaB BnewB BarrayB BthatB BhasB BelementsB BthatB BconveyB BtheB BpredicateB Bfunction.B BChangingB BanB BarrayB BbyB BsettingB BeachB BitemB BthroughB BaB BfunctionB BusingB BtheB Bmap.B BUseB BreduceB BtoB BmergeB BeveryB BcomponentB BofB BanB BarrayB BtoB BanB BindividualB Bvalue.

Exercises

IllustrateB BaB BJavaScriptB BfunctionB BthatB BtakesB BanB BarrayB BofB BnumbersB BsavedB BandB BsearchB BforB BtheB Bsecond-lowestB BandB BsecondB BhighestB Bnumbers.

Solution

ChapterB B7:B BTheB BSecretB BLifeB B
ofB BObjects

WhenB BitB BcomesB BtoB BProgramingB Blanguages,B BthereB BisB BaB BsetB BtechniqueB BthatB ButilizesB BobjectsB BasB BaB BfundamentalB BideaB BofB BprogramB Borganization,B BandB BtheyB BareB BcalledB BtheB Bobject-orientedB Bprogramming.B BItsB BconceptB BwillB BbeB BexplainedB BfurtherB BinB BthisB Bchapter.

Encapsulation

TheB BprimaryB BimportanceB BofB Bobject-orientedB BprogrammingB BisB BtoB BbreakB BprogramsB BintoB BlittleB BpiecesB BandB BmakesB BsureB BeachB BpieceB BmanagesB BitsB Bsection.B BSeveralB BfragmentsB BofB BsimilarB BprogramsB BcommunicateB BwithB BeachB BotherB BusingB Binterfaces,B BaB BrestrictedB BsetB BofB BfunctionsB BorB BbindingB BthatB BproduceB BessentialB BfunctionalityB BonB BaB BhigherB Blevel,B BhidingB BtheB BspecificB Bexecution.B BIllustrateB BthisB BtypeB BofB BprogramB BpiecesB BthroughB Bobjects,B BandB BtheirB BlayoutB BcontainsB BaB BparticularB BsetB BofB BpropertiesB BandB Bmethods.B BPropertiesB BwithinB BtheB BlayoutB BareB BpublicB BwhileB BtheB BouterB BcodeB BisB Bprivate.B BDefineB BtheB BaccessibleB BlayoutB BinB BcommentsB BorB Bdocumentation.B BItB BregularlyB BusesB BtheB BunderscoreB B(_)B BcharacterB BatB BtheB BbeginningB BofB BpropertyB BnamesB BtoB BsignifyB BprivateB Bproperties.B BMeanwhile,B BdivingB BlayoutsB BfromB BexecutionB BisB BcalledB Bencapsulation.

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 BobjectsB BconsistsB BofB BaB Bprototype.B BThisB BisB BanB BobjectB BusedB BasB BanB BalternativeB BsourceB BofB Bproperties.B BTherefore,B BtheB BprototypeB BofB BthatB BemptyB BobjectB BisB BtheB BinheritedB Bprototype,B BtheB BObject.prototype.

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 BprototypeB BproducesB BsomeB BmethodB BthatB BdisplaysB BinB BeveryB BobjectB BlikeB BtoStringB BthatB BtransformsB BanB BobjectB BtoB BaB BstringB Bexecution.

AB BlotB BofB BobjectsB BdoB BnotB BcontainB BObject.prototypeB BasB BtheirB BprototypeB BbutB BuseB BanotherB BobjectB BthatB BproducesB BaB BseparateB BsetB BofB BdefaultB Bproperties;

FunctionsB BacquiresB BfromB BFunction.prototype,B BandB BarraysB BacquiresB BfromB BArray

.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 Bproperty.B BBelowB BisB BaB Bsample:

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 ByouB BtoB BdescribeB BaB BconstructorB BandB BaB BsetB BofB BmethodsB BinB BaB BparticularB Bplace.B BClassB BdeclarationsB BenablesB Bmethods,B BpropertiesB BthatB BgraspB BfunctionsB BtoB BbeB BincludedB BinB BtheB Bprototype.B BWhenB ByouB BuseB BanB Bexpression,B BitB BdoesB BnotB BdescribeB BaB BbindingB BburB BprovidesB BtheB BconstructorB BasB BaB Bvalue.B BYouB BcanB BexcludeB BtheB BclassB BnameB BinB BanB Bexpression.

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 BprototypeB BorB Bnot,B BtheB BpropertyB BaddsB BtoB BtheB Bobject.B BIfB BthereB BwasB BanB BassignedB BpropertyB BwithB BsimilarB BnamesB BinB BtheB Bprototype,B BitB BdoesB BnotB BinfluenceB BtheB Bobject.

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 BarrayB BprototypesB BaB BseparateB BtoStringB Bmethod.

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 Bcalling.B Bjoin(",")B BonB Bit.B BItB BplacesB BaB BcommaB BbetweenB BtheB BvaluesB BcontainedB BinB BtheB Barray.B BIfB ByouB BcallB BObject.prototype.toStringB BtoB BanB Barray,B BitB BprovidesB BaB BseparateB Bstring.

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 BconsistsB BofB BaB BnamedB BmethodB BwithB BtheB BSymbol.iteratorB BsymbolB BwhenB BtheB BpropertyB BisB Bcalled.B BTheB BmethodB BsendsB BbackB BanB BobjectB BthatB BproducesB BaB BsecondB Blayout.B BItB BcontainsB BaB BnextB BmethodB BthatB BsendsB BbackB BtheB BfollowingB Bresult.B BTheB BresultB BisB BanB BobjectB BwithB BaB BvalueB BpropertyB BthatB BproducesB BtheB BnextB Bvalue,B BSymbol.iteratorB BcanB BbeB BaddedB BtoB BseveralB Bobjects.B BCheckoutB BthisB Blayout:

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 Bclass,B Bacting

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 B×B BheightB Belements.B BTheseB BelementsB BareB BsavedB BrowB BafterB Brow.B BTheB BconstructorB BfunctionB BgetsB BaB Bwidth,B Bheight,B BandB BanB BadditionalB BelementB Bfunction,B BwhichB BisB BusedB BtoB BsetB BtheB BinitialB Bvalues.B BUseB BtheB 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 BvalueB Bproperties.

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,B Bgetters,B BandB Bsetters

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 BtemperatureB BinB BdegreesB BCelsiusB BorB BdegreesB BFahrenheit,B BbutB BitB BsavesB BonlyB BCelsiusB BandB BtransformB BtoB BandB BfromB BCelsiusB BinB BtheB BFahrenheitB BgetterB BandB Bsetter.B BWithinB BaB BclassB Bdeclaration,B BmethodsB BthatB BareB BstaticB BwrittenB BbeforeB BtheirB BnamesB BareB BsavedB BonB BtheB Bconstructor.B BSo,B ByouB BcanB BwriteB BTemperature.fromFahrenheit(100)B BtoB BbuildB BaB BtemperatureB BthroughB BdegreesB BFahrenheit.

Inheritance

SomeB BmatricesB BareB Bsymmetric.B BWhenB ByouB BreflectB BaB BsymmetricB BmatrixB BthroughB BitsB Btop-left-to-bottom-rightB Bdiagonal,B BitB BdoesB BnotB 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 BprototypeB BforB BtheB BnewB BclassB BisB BacquiredB BfromB BtheB BoldB BprototypeB BbutB BsetsB BaB BnewB BdefinitionB BforB BtheB Bmethod.B BThisB BisB BcalledB BinheritanceB BinB Bobject-orientedB BprogrammingB Bterms.B BBelowB BisB BanB Billustration:

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 BTherefore,B BaB BSymmetricMatrixB BisB BanB BinstanceB BofB BMatrix.B BYouB BcanB BalsoB BapplyB BthisB BmethodB BtoB BstandardB BconstructorsB BlikeB BArray.

Summary

InB BthisB Bchapter,B BweB BrealizeB BthatB BobjectsB BcanB BperformB BmoreB BthanB BholdingB BtheirB Bproperties.B BTheyB BconsistB BofB BprototypesB BthatB BareB BobjectsB BasB Bwell.B BTheyB BbehaveB BlikeB BtheyB BcontainB BpropertiesB BthatB BtheyB BdoB BnotB BprovideB BasB BlongB BasB BtheB BprototypeB BhasB BthatB Bproperty.B BSimpleB BobjectsB BuseB BtheB BObject.B BPrototypeB BtoB BrepresentB BtheirB Bprototype.B BWeB BtalkedB BaboutB BConstructorsB Btoo,B BandB BtheyB BareB BfunctionsB BthatB BtheirB BnamesB BoftenB BbeginB BwithB BaB BcapitalB Bletter,B BandB BusedB BwithB BtheB BnewB BoperatorB BtoB BbuildB BnewB Bobjects.B BTheB BnewB Bobject’sB BprototypeB BwouldB BbeB BtheB BobjectB BwithinB BtheB BprototypeB BpropertyB BofB BtheB Bconstructor.B BAB BclassB BnotationB BoffersB BaB BwayB BtoB BdescribeB BaB BconstructorB BandB BitsB Bprototype.B BWeB BalsoB BtouchedB BtheB BGetters,B Bsetters,B BandB BstaticsB BandB BtheB BinstanceofB Boperator.

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BcreateB BanB Barray,B BthroughB BanB BiteratorB BfunctionB BandB BaB BprimaryB BseedB Bvalue.

Solution

ChapterB B8:B BAB BRobot

InB BthisB Bchapter,B BthereB BwillB BbeB BworkB BonB BaB BrobotB Bprogram,B BaB BshortB BprogramB BthatB BexecutesB BaB BtaskB BinB BaB BvirtualB Bworld.B BWeB BwillB BbeB BusingB BaB BmailB BdeliveryB BrobotB BreceivingB BandB BdeliveringB Bparcels.

MeadowB Bfield

TheB BMeadowB BfieldB BvillageB BisB BaB BsmallB BoneB BconsistingB BofB B14B BroadsB BandB B11B Bplaces.B BBelowB BisB BanB BillustrationB BwithB BanB BarrayB BofB Broads:

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 B(villageB Bplaces)B BwithB BlinesB BdividingB BthemB B(roads).B BTheB BgraphB BisB BtheB BworldB BwhereB BourB BrobotB BwalksB Bthrough.B BNowB BletB BusB BtransformB BourB BlistB BtoB BaB BdataB BlayoutB BthatB BeachB BplaceB BdecidesB BwhereB ByouB Bcan.

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 BforB BeachB Bnode,B BsavesB BaB BconnectedB BnodeB BofB BanB Barray.B BItB ButilizesB BtheB BsplitB BmethodB BtoB BgoB BthroughB BtheB BroadB Bstrings,B BthatB BcontainsB BtheB BformB B"Start-End",B BtoB Btwo-elementB BarraysB BwithinB BtheB BstartB BandB BendB BasB BdifferentB Bstrings.

TheB Btask

OurB BrobotB BwillB BwalkB BacrossB BtheB Bvillage.B BThereB BareB BdifferentB BparcelsB BinB BseveralB Bplaces.B BTheB BrobotB BreceivesB BaB BparcelB BwhenB BitB BarrivesB BandB BdeliversB BthemB BwhenB BitB BgetsB BtoB BtheirB Bdestination.B BWhenB BallB BtasksB BhaveB BallB BbeenB Bexecuted,B BallB BparcelsB BmustB BbeB Bdelivered.B BIfB ByouB BwantB BtoB BreplicateB BthisB Bprocess,B BdescribeB BaB BvirtualB BworldB BthatB BcanB BdefineB Bit.B BThisB BmethodB BrevealsB BtheB BrobotB BlocationB BasB BwellB BasB BtheB Bparcels.B BLetB BusB BbringB BdownB BtheB Bvillage'sB BstateB BtoB BaB BspecificB BsetB BofB BvaluesB BthatB BdescribesB Bit.

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 BTheyB BactB BlikeB BstringsB BandB Bnumbers.B BInB BJavaScript,B ByouB BcanB BchangeB BalmostB Beverything.B BThereB BisB BaB BfunctionB BnamedB BObject.freezeB BthatB BtransformsB BanB BobjectB BsoB BthatB BitB BdisregardsB BwritingB BtoB BitsB Bproperties.

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 BdeterminesB BwhatB BdirectionB BitB BmovesB Bto.B BTherefore,B BaB BrobotB BisB BaB BfunctionB BwhichB BtakesB BaB BVillageStateB BobjectB BandB BsendB BbackB BtheB BnameB BofB BaB BnearbyB Bplace.B BTheB BrobotB BsendsB BbackB BanB BobjectB BconsistingB BofB BitsB BintendedB BdirectionB BandB BaB BmemoryB BvalueB BreturnedB BtheB BnextB BtimeB ByouB BcallB Bit.

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 BItB BcanB BrunB BintoB BallB BparcelsB BandB BthenB BgetB BtoB BitsB BdeliveryB Bpoint.B BBelowB BisB BanB Bexample:

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 BfewB Bparcels.

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 BwillB BbeB BinspectedB Bnext,B BtogetherB BwithB BtheB Broute.B BItB BbeginsB BwithB BanB BemptyB BrouteB BandB BtheB BstartB Bposition.B BEveryB BlocationB BcanB BbeB BtouchedB BfromB BeveryB Blocation,B BaB BrouteB BcanB BalsoB BbeB BfoundB BbetweenB BtwoB BpointsB BthereforeB BtheB BrouteB BwillB BnotB Bfail.

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 BtheB BMeadowB BfieldB BvillageB BwhereB BweB BtalkedB BaboutB BaB BvillageB BwithB B11B BplacesB BandB B14B Broads,B BthenB BweB BmovedB BtoB BtheB BPersistentB Bdata,B BwherebyB BDataB BstructuresB BbehaveB BlikeB BstringsB BandB BdoB BnotB Bchange.B BSimulationB BenablesB ByouB BtoB BpassB BmemoryB BtoB BrobotsB BandB BletB BthemB BtoB BsendB BbackB BaB BnewB Bmemory.

Exercise

WriteB BaB BstraightforwardB BJavaScriptB BprogramB BtoB BconnectB BeveryB BelementB BinB BtheB BbelowB BarrayB BintoB BaB Bstring.

"Red,B BGreen,B BWhite,B BBlack"

"Red,B BGreen,B BWhite,B BBlack"

"Red+Green+White+Black"

Solution

B B

ChapterB B9:B BBugsB BandB BErrors

ComputerB BprogramB BflawsB BareB BcalledB Bbugs,B BtheB BmistakesB BmadeB BbyB BaB BcomputerB Bprogram.

StrictB Bmode

YouB BcanB ButilizeB BJavaScriptB BinB BaB BstrictB Bmode.B BThisB BcanB BbeB BachievedB BbyB BaddingB BtheB BstringB B"useB Bstrict"B BrightB BatB BtheB BtopB BofB BaB Bfile.B BBelowB BisB BanB Billustration:

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 BomittingB BtheB BnewB BkeywordB BsoB BitB Bdoesn’tB BintroduceB BaB BnewlyB BcreatedB Bobject:

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 BvalueB BandB BbuiltsB BtheB BglobalB BbindingB Bname.B BInB BstrictB Bmode,B BuseB 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 BpathB BtoB BtakeB BifB ByouB BwantB BtoB BacquireB BadditionalB BinformationB BaboutB BtheB Bexecution.B BWeB BwantB BnB BtoB BgetB BtheB BvaluesB B13,B B1,B BandB BthenB B0.B BWeB BshouldB BstateB BtheB BvalueB BatB BtheB BbeginningB BofB BtheB Bloop'

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 Bbase,B BwhatB BweB BwantB BisB BnB B=B BMath.floor(nB B/B Bbase)B BsoB BthatB BtheB BnumberB BcanB BbeB B“shifted”B BtoB BtheB Bright.

AnotherB BgreatB BwayB BtoB BspecifyB BaB BbreakpointB BisB BtoB BinsertB BaB BdebuggerB BstatementB B(keyword)B BintoB ByourB Bprogram.B BIfB BtheB BdeveloperB BtoolsB BwillB BpickB BitB BupB BandB BpauseB BtheB BprogramB BanytimeB BitB BgetsB BtoB BthatB BstatementB BifB ByourB BbrowserB BisB Bactive.

Exceptions

WhenB BaB BfunctionB BisB BcannotB BgoB Bfurther,B BtheB BexceptionB BhandlingB BisB BtheB BplaceB BthatB BunderstandsB BhowB BtoB BfixB BthatB Bproblem.B BExceptionsB BareB BaB BtoolB BthatB BenablesB BaB BblockB BofB BcodeB BthatB BrunsB BintoB BdifficultiesB BtoB BthrowB BanB Bexception,B BandB BanB BexceptionB BcouldB BbeB BanyB Bvalue.B BYouB BcanB BintentionallyB BcreateB BproblemsB BwithinB ByourB BlineB BofB BcodeB BtoB BcatchB BtheB BexceptionB BduringB BitsB BzoomingB BdownB BtheB BprocessB BsoB BthatB ByouB BcanB BuseB BitB BtoB BsolveB BtheB BproblemB BandB BcontinueB ByourB Bwork.

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 BindicatesB BthatB ByourB BcodeB BcanB BhaveB BdifferentB BsideB Beffects,B BbutB BanB BexceptionB BcouldB BstopB BthemB BfromB Bhappening.B BBelowB BisB BsomeB BbadB BbankingB Bcode:

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 BsuchB BasB BinspectingB BupB BaB BpropertyB BonB Bnull,B BcitingB BaB BnonexistentB Bbinding,B BorB BcallingB BaB Bnon-functionB BwillB BresultB BinB BraisedB Bexceptions.B BTheseB BexceptionsB BcanB BbeB Bcaught.B BJavaScriptB BdoesB BnotB BsupportB BselectiveB BcatchingB BofB Bexceptions.B BBelowB BisB BanB BexampleB BthatB BtriesB BtoB BcontinueB BcallingB BpromptDirectionB BuntilB BitB BprovidesB BaB BvalidB Banswer:

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 BhaveB BaB BvalidB Bdirection,B BbutB BaB BmisspelledB BpromptDirectionB BwillB BoutputB BanB BundefinedB BvariableB Berror.B BIfB ByouB BwantB BtoB BcatchB BaB BparticularB BtypeB BofB Bexception,B BcheckB BinB BtheB BcatchB BblockB BifB BtheB BexceptionB ByouB BhaveB BisB BtheB BsameB BoneB ByouB BwantB BandB BrethrowB Bit.B BLet’sB BdescribeB BaB BnewB BkindB BofB BerrorB BandB ButilizeB BinstanceB BofB BtoB BrecognizeB Bit.

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 Bconstructor,B BitB BinheritsB BtheB BErrorB Bconstructor,B BwhichB BanticipatesB BaB BstringB BmessageB BthatB BweB BcanB BrecognizeB BitB Bwith.

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 BprogrammingB BisB BidentifyingB BandB BfixingB Bbugs.B BSometimes,B ByouB BcanB BsolveB BproblemsB Blocally.B BYouB BcanB BtrackB BthemB BwithB BspecialB BreturnB BvaluesB BorB BtheB BuseB BofB Bexceptions.

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.

ChapterB B10:B BRegularB BExpressions

ProgrammingB BconceptsB BandB BtoolsB BadvancesB BinB BaB BdisorganizedB Bway,B BbutB BitsB BsuccessB BindicatesB BanB BexcellentB BpieceB BofB Btechnology.B BInB BthisB Bchapter,B BweB BwillB BdiscussB BregularB Bexpressions.B BTheyB BareB BusedB BtoB BdefineB BpatternsB BwithinB BaB BstringB Bdata.B BTheyB BcreateB BaB Bsmall,B BdifferentB BlanguageB BthatB BconsistsB BofB BJavaScriptB BasB BwellB BasB BotherB Blanguages.

CreatingB BaB BregularB Bexpression

AB BregularB BexpressionB BisB BconstructedB BwithB BtheB BRegExpB BconstructorB BorB BwrittenB BasB BaB BstrictB BvalueB BbyB BsurroundingB BaB BpatternB BinB Bforward-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 BWhenB ButilizingB BtheB BRegExpB Bconstructor,B BwriteB BtheB BpatternB BasB BaB BnormalB BstringB BsoB BthatB BtheB BrulesB BapplyB BforB Bbackslashes.

TheB BsecondB BnotationB BinfluenceB BbackslashesB Bdifferently,B BfirstB BputB BaB BbackslashB BbeforeB BanyB BforwardB BslashB BbecauseB BtheB BpatternB BdisplaysB BbetweenB BslashB Bcharacters.

TestingB BforB Bmatches

RegularB BexpressionB BobjectsB BcontainB BseveralB Bmethods,B BoneB BofB BwhichB BisB BtheB Btest.B BWhenB ByouB BpassB BaB Bstring,B BitB BreturnsB BaB BBooleanB BdeterminingB BifB BaB BstringB BcontainsB BaB BmatchB BofB BtheB BpatternB BinB BtheB Bexpression.

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 BrepresentB BtheB BsuccessionB BofB Bcharacters.B BIfB BABCB BpapersB BanywhereB BinB BtheB Bstring,B BweB BareB BrunningB BaB Btest,B BtheB BtestB BwillB BreturnB Btrue.

SetsB BofB Bcharacters

RegularB BexpressionsB BenableB BusB BtoB BindicateB BdifficultB Bpatterns.B BIfB ByouB BwantB BtoB BequalB BanyB BnumberB BinB BaB BregularB Bexpression,B BplaceB BaB BsetB BofB BcharactersB Bin-betweenB BsquareB Bbrackets.B BTheB BfollowingB BexpressionsB BequalB BeveryB BstringB BwithinB BaB Bdigit:

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 BusedB BtoB BspecifyB BaB BscopeB BofB BcharactersB BthatB BtheB Bcharacter’sB BUnicodeB BnumbersB BdecideB BtheB Bcommand.B BCharactersB BfromB B0B BtoB B9B BstayB BnextB BtoB BeachB BotherB BinB BthisB BcommandB B(codesB B48B BtoB B57),B BsoB B[0-9]B BwrappingB BthemB BallB BandB BequalsB BanyB Bdigit.B BCommonB BcharacterB BgroupsB BcontainB BindividualB BshortcutsB Bbuilt-in.

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 BexpressionB Bbelow:

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 BForB Binstance,B B[\d.]B BindicatesB BanyB BdigitB BorB BperiodicB BcharacterB BbutB BtheB BperiodB BhasB BnoB BmeaningB BasB BwellB BasB BotherB BuniqueB Bcharacters,B BlikeB 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 Bdigits.B BIfB ByouB BwantB BtoB BmatchB BaB BwholeB BnumberB BorB BaB BsuccessionB BofB BmoreB Bdigits,B BplaceB BaB BplusB BsignB B(+)B BimmediatelyB BafterB BanB BinputB BinB BaB BregularB Bexpression.B BThisB BsignifiesB BthatB BtheB BelementB BcouldB BrepeatB BmoreB BthanB Bonce,B B/\d+/B BequalsB BoneB BorB Bmore-digitB Bcharacters.

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 Bexample,B BtheB BuB BcharacterB BisB BpermittedB BtoB Brise,B BbutB BtheB BpatternB BisB BalsoB BequalB BwhenB BitB BisB BnotB Bfound.

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 Btimes,B ButilizeB BtheB Bbraces,B BinsertingB B{4}B BafterB BanB Belement.B BIfB ByouB BwantB BitB BtoB BexecuteB BpreciselyB BfourB Btimes,B BdefineB BaB BrangeB BlikeB Bthis:

{2,4}B BsignifiesB BthatB BtheB BelementB BmustB BexecuteB BtwiceB BandB BatB BmostB BfourB Btimes.B BBelowB BisB BanotherB BpatternB BofB BtheB BdateB BandB BtimeB Bpattern,B BwhichB BenablesB BbothB BsingleB BandB Bdouble-digitB Bdays,B BmonthsB BandB Bhours.

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 BelementB Bconcurrently,B BuseB BtheB Bparentheses.B BSomeB BpartsB BofB BaB BregularB Bexpression,B BwhichB BisB BcitedB BinB Bparentheses,B BcountsB BasB BanB BindividualB BelementB BasB BlongB BasB BtheB BoperatorsB BareB Bconcerned.

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 BbooB BandB Bhoo.B BTheB BthirdB B+B BindicatesB BtoB BtheB BentireB BgroupB B(hoo+),B BequalingB BoneB BorB BmoreB BsuccessionsB BlikeB Bthat.B BTheB BIB BendingB BtheB BfirstB BexpressionB BinB BtheB BexampleB BisB BusedB BforB BcaseB Binsensitive,B BenablingB BitB BtoB BequalB BtheB BuppercaseB BBB BinB BtheB BinputB Bstring.B BAlthoughB BtheB BpatternB BisB BentirelyB Blowercase.

MatchesB BandB Bgroups

TheB BtestB BmethodB BisB BtheB BbestB BwayB BtoB BequalB BaB BregularB Bexpression,B BitB BdeterminesB BifB BitB BmatchesB Bonly.B BRegularB BexpressionsB BcontainB BanB BexecB B(execute)B Bmethod,B BwhichB BwillB BoutputB BnullB BifB BitB BcouldB BfindB BaB BmatchB BandB BsendsB BbackB BanB BobjectB BcontainingB BdataB BaboutB BtheB Bmatch.

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 BdetermineB BwhatB BpartB BofB BtheB BstringB BtheB BthrivingB BmatchB Bstarts.B BBelowB BisB BtheB BsuccessionB BofB BdigitsB Bneeded:

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 Bparentheses,B BtheB BmatchingB BtextB BwillB BdisplayB BinB BtheB Barray.B BTheB BwholeB BmatchB BisB BtheB Bfirst,B BtheB BnextB BisB BtheB BmatchedB BpartB BbyB BtheB BfirstB Bgroup,B BandB BthenB BtheB BfollowingB Bgroup,B Betc.

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 BquestionB Bmark),B BitB BoutputsB Bundefined.B BWhenB ByouB BmatchB BaB BgroupB BseveralB Btimes,B BonlyB BtheB BlastB BmatchB BfinishesB BinB BtheB Barray.

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 BcalledB BDate.B BIfB ByouB BwantB BtoB BbuildB BaB BdateB BobjectB ButilizingB Bnew,B BfirstB BgetB BtheB BcurrentB BtimeB BandB Bdate.

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 BmonthB BnumbersB BbeginB BatB BzeroB B(therefore,B BDecemberB BisB B11),B BandB BdayB BnumbersB BbeginB BatB B1.

TheB Bhours,B Bminutes,B Bseconds,B BandB BmillisecondsB BargumentsB BareB BvoluntaryB BandB BrecognizedB BasB BzeroB BwhenB BnotB Bspecified.B BTimestampsB BareB BsavedB BasB BtheB BnumberB BofB BmillisecondsB BinB BtheB BUTCB BtimeB Bzone.B BFollowingB BbyB BaB BconventionB BsetB BbyB B“UnixB Btime”.

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 BargumentB BisB BrecognizedB BasB BaB BmillisecondB Bcount.B BDetermineB BtheB BcurrentB BmillisecondB BcountB BbyB BbuildingB BaB BnewB BDateB BobjectB BandB BcallB BgetTimeB BonB BitB BorB BuseB BtheB BDate.nowB Bfunction.B BDateB BobjectsB BproduceB 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)

StringB BandB BWordB Bboundaries

YouB BcanB BensureB BthatB BtheB BmatchB BspansB BtheB BentireB BstringB BbyB BaddingB BtheB BmarkersB B^B BandB B$.B BTheB BcaretB BequalsB BtheB BbeginningB BofB BtheB BinputB 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 BmatchesB 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 BonB BaB BboundaryB Bword,B ButilizeB BtheB BmarkerB B\b.B BAB BwordB BboundaryB BcanB BbeginB BorB BfinishB BstringsB BcontainingB BaB BwordB BcharacterB B(\w)B BonB BoneB BsideB BandB BaB BnonwordB BcharacterB BonB BtheB Bother.

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 BfollowedB BbyB BwordsB BsuchB BasB Bchicken,B Bpig,B BorB Bcow,B Blet’sB BwriteB BthreeB BregularB BexpressionsB BandB BtestB Bthem.B BWeB ButilizeB BtheB BpipeB BcharacterB B(|)B BtoB BmarkB BaB BchoiceB BbetweenB BtheB BpatternB BtoB BtheB BleftB BandB Bright:

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 BpartB BofB BtheB BstringB BwithB BanotherB Bone.

console.log("papa".replace("p",B B"m"));

//B B→B Bmapa

TheB BfirstB BargumentB BcanB BequallyB BbeB BaB BregularB Bexpression.B BItB BreplacesB BtheB BfirstB BmatchB BofB BtheB BregularB Bexpression.B BIfB ByouB BaddB BaB BgB BoptionB B(forB Bglobal)B BtoB BtheB Bexpression,B BeveryB BmatchB BcontainedB BinB BtheB BstringB BisB Breplaced,B BandB BnotB BfirstB Bonly.

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 BisB BbecauseB BitB BrefersB BtoB BmatchedB BgroupsB BinB BtheB BreplacementB Bstring.B BForB Binstance,B ByouB BhaveB BaB BlargeB BstringB BconsistingB BofB Bpeople'sB Bname,B BoneB BnameB BperB Bline,B BusingB BtheB BformatB BLastname,B BFirstname.B BYouB BcanB BasB BwellB BchangeB BandB BremoveB BtheseB Bnames,B BeradicateB BtheB BcommaB BtoB BgetB BaB BFirstnameB BLastnameB Bformat,B BandB ButilizeB BtheB BfollowingB Bcode:

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 BgroupB BinB BparenthesesB BinB Bpattern.B B$1B BisB BrestoredB BbyB BtheB Btext,B BwhichB BmatchesB BopposingB BtheB BfirstB Bgroup,B B$2B BupB BtoB B$9.B BEachB BandB BeveryB BmatchB BcanB BbeB BreferredB BtoB BwithB B$&.B BYouB BcanB BpassB BaB BfunctionB BinsteadB BofB BaB BstringB BasB BtheB BsecondB BargumentB BtoB Brestore.B BForB BeachB Breplacement,B BtheB BfunctionB BisB BcalledB BwithB BtheB BmatchedB BgroupB BasB Barguments,B BandB BincludeB BtheB BreturnB BvalueB BintoB BtheB BnewB Bstring.B BBelowB BisB BanB Bexample:

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 BcommentsB BfromB BaB BblockB BofB BJavaScriptB Bcode.B BLookB Bbelow:

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 BaccompaniedB BwithB BanyB BnumberB BthatB BisB BnotB BaB BnewlineB Bcharacter.B BUseB B[^]B BtoB BmatchB BanyB Bcharacter.

RepetitiveB BOperatorsB B(+,B B*,B BandB B{})B BareB BcalledB BgreedyB BwhichB BmeansB BtheyB BmatchB BandB BtheyB BcanB BalsoB Bbacktrack.B BIfB BaB BquestionB BmarkB BisB BplacedB BafterB BthemB B(+?,B B*?,B B??,B B{}?),B BtheB BgreedB BdisappearsB BandB BbeginB BmatchingB BnoB BmatterB BhowB Bsmall.B BTheB BsmallestB BstretchB BofB BcharactersB BwhichB BbringsB BaB B*/,B BisB BtheB BstarB Bmatch.B BItB BabsorbsB BoneB BblockB BcommentB Bonly.

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

DynamicallyB BcreatingB BRegExpB Bobjects

ThereB BareB BfewB BinstancesB BwherebyB ByouB BwouldB BnotB BunderstandB BtheB BspecificB BpatternB ByouB BshouldB BmatchB BagainstB BwhenB ByourB BcodeB BisB BbeingB Bwritten.B BIfB ByouB BwantB BtoB BsearchB BforB BtheB BuserB BnameB BinB BaB BchunkB BofB BtextB BandB BwrapB BitB BinB BunderscoreB BcharactersB BtoB BmakeB BitB Bunique.B BButB ByouB BcanB BcreateB BaB BstringB BandB ButilizeB BtheB BRegExpB Bconstructor.B BBelowB BisB BanB Bexample:

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 BbackslashesB BbecauseB ByouB BwouldB BwriteB BthemB BinB BaB BnormalB Bstring.B BTheB BsecondB BargumentB BtoB BtheB BRegExpB BconstructorB BconsistsB BofB BtheB BoptionsB BneededB BforB BtheB BregularB Bexpression.B BTheB B"gi"B BrepresentB BglobalB BandB BcaseB Binsensitive.B BBelowB BisB BanB Bexample:

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 Bexpression.B BYouB BcanB BalsoB BuseB BanotherB Bmethod,B BsearchB BwherebyB ByouB BcanB BcallB BtheB BindexOfB BmethodB BaB BregularB Bexpression,B BandB BitB BsendsB BbackB BtheB BfirstB BindexB BwhereB BitB BseesB BtheB BexpressionB BandB BwhenB BitB BdoesB BnotB BseeB BitB BreturnsB B-1.

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 BsearchB BfromB BaB BstatedB BpositionB BinB BtheB Bstring.B BRegularB BexpressionB BobjectsB BcontainB Bproperties.B BOneB BofB BtheB BpropertiesB BisB BcalledB Bsource,B BandB BitB BconsistsB BofB BtheB BstringB BthatB BbuiltB BtheB Bexpression.B BlastIndexB BisB BanotherB Bproperty,B BandB BitB BinfluencesB BsomeB BsmallB Bcircumstances,B BwhereB BtheB BnextB BmatchB BwillB Bbegin.B BTheB BregularB BexpressionB BmustB BcontainB BtheB BglobalB B(g)B BorB BstickyB B(y)B Boption,B BandB BtheB BmatchB BwillB BoccurB BusingB BtheB BexecB Bmethod.B BIllustrationB Bbelow:

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 Bthat,B BwhenB ByouB BenableB Bsticky,B BtheB BmatchB BsucceedsB BifB BitB BbeginsB BatB BlastIndex,B BwhileB BwithB Bglobal,B BitB BwillB BfindB BaB BpositionB BforB BtheB BmatchB BcanB Bbegin.

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 BexecB Bcalls,B BproblemsB BwillB BoccurB BwithB BtheB BautomaticB BupdatesB BtoB BtheB BlastIndexB Bproperty.

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 BonB BstringsB Bworks.

LoopingB BoverB Bmatches

TheB BbestB BthingB BtoB BdoB BisB BtoB BscanB BacrossB BallB BeventsB BofB BaB BpatternB BinB BaB BstringB BgivingB BaccessB BtoB BtheB BmatchB BobjectB BinB BtheB BloopB Bbody.B BUseB BtheB BlastIndexB BandB BexecB BtoB BachieveB Bthis.

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 ButilizingB BmatchB B=B Bnumber.ExecB B(input)B BasB BtheB BconditionB BwithinB BtheB BwhileB Bstatement,B BtheB BmatchB BisB BweB BexecuteB BtheB BmatchB BatB BtheB BbeginningB BofB BeveryB Biteration,B BstoreB BtheB BresultB BwithinB BaB Bbinding,B BandB BstopB BloopingB BwhenB BmatchesB BcanB BnoB BlongerB Bfind.

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 BusuallyB Bcalled

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=B BcharacterB BattachB BaB BsettingB BtoB BtheB BcurrentB Bsection.

·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 BPropertiesB BatB BtheB BtopB BareB BsavedB BstraightB BintoB BthatB Bobject,B BwherebyB BpropertiesB BcanB BbeB BfoundB BinB BsectionsB BareB BsavedB BinB BaB BdifferentB BsectionB Bobject.B BTheB BsectionB BbindingB BpointsB BtoB BtheB BobjectB BforB BtheB BexistingB Bsection.B BThereB BareB BtwoB BtypesB BofB BimportantB Blines—sectionB BheadersB BorB BpropertyB Blines.B BIfB BaB BlineB BisB BalwaysB Bproperty,B BitB BisB BsavedB BinB BtheB BexistingB Bsection.B BIfB BitB BisB BaB BsectionB Bheader,B BbuildB BaB BnewB BsectionB Bobject,B BandB BsetB BsectionB BtoB Bit.

TheB BpatternB BifB B(matchB B=B Bstring.match())B BisB BidenticalB BtoB BtheB BtrickB BofB ButilizingB BanB BassignmentB BasB BtheB BconditionB BforB BaB Bwhile.

InternationalB Bcharacters

BecauseB BofB BJavaScript’sB BinitialB BsimplisticB BimplementationB BandB BthatB BthisB BapproachB BsetB BinB BstoneB BasB BstandardB Bbehavior,B BJavaScript’sB BregularB BexpressionsB BareB BsomewhatB BdumbB BaboutB BcharactersB BthatB Bdon’tB BshowB BinB BtheB BEnglishB Blanguage.B BForB Binstance,B BinB BJavaScript,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 Bdigits,B BandB BtheB BunderscoreB Bcharacter.B BCharactersB BlikeB BéB BorB Bß,B BareB BwordB Bcharacters,B BtheyB BwillB BnotB BmatchB B\w,B BwillB BmatchB BuppercaseB B\W,B BtheB BnonwordB Bcategory.B BItB BindicatesB BthatB BcharactersB BcomposedB BofB BtwoB BcodeB Bunits.

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🍎B BinB BtheB BfirstB BlineB BisB BbeingB BmanagedB BasB BtwoB BcodeB Bunits,B BandB BtheB B{3}B BsectionB BisB BusedB BtoB BtheB BsecondB BoneB Bonly.B BTheB BdotB BalsoB BmatchesB BaB BsingleB BcodeB Bunit.B BAddB BuB BoptionB B(forB BUnicode)B BtoB ByourB BregularB BexpressionB BsoB BthatB BitB BmanagesB BthatB BcharactersB Bproperly.B BTheB BwrongB BbehaviorB BremainB BsetB BasB BtheB Bdefault,B Bunfortunately,B BbecauseB BtransformingB BthatB BcouldB BcreateB BproblemsB BforB BcurrentB BcodeB BthatB BdependsB BonB Bit.

YouB BcanB BuseB B\pB BinB BaB BregularB BexpressionB BtoB BmatchB BeveryB BcharacterB BthatB BUnicodeB BstandardB BgivesB BaB BsetB Bproperty.

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 BsearchingB BforB BtheB BoneB BthatB ByouB BneedB BmayB BnotB BalwaysB BbeB Btrivial.

Summary

WeB BfocusedB BonB BregularB BexpressionsB BinB BthisB Bchapter.B BAnB BobjectB BthatB BstandsB BforB BpatternsB BinB BstringsB BisB BaB BregularB Bexpression.B BTheyB BconsistB BofB BtheirB BlanguageB BandB ButilizeB BitB BforB BtheB BexhibitionB BofB BtheseB Bpatterns.

/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 BstringB BmatchesB Bit.B BItB BalsoB BcontainsB BanB BexecB Bmethod,B BwherebyB BwhenB BitB BfindsB BaB Bmatch,B BitB BsendsB BbackB BanB BarrayB BhavingB BeveryB BmatchedB Bgroup.B BThisB BtypeB BofB BarrayB BcontainsB BanB BindexB BpropertyB BthatB BspecifiesB BwhereB BtheB BmatchB Bstarted.B BStringsB BuseB BaB BmatchingB BmethodB BtoB BmatchB BthemB BinB BoppositionB BtoB BaB BregularB BexpressionB BasB BwellB BasB BaB BsearchB BmethodB BtoB BfindB Bone,B BsendingB BbackB BonlyB BtheB BbeginningB BpositionB BofB BtheB Bmatch.

Exercise

WriteB BaB BJavaScriptB BprogramB BworkingB BasB BaB BtrimB BfunctionB B(string)B ButilizingB BregularB Bexpression.

Solution

ChapterB B11:B BModules

ThisB BparticularB BprogramB BhasB BaB BsimpleB Blayout.B BItB BisB BveryB BtoB BexplainB BitsB Bconcept,B BandB BeveryB BpartB BplaysB BaB BpreciseB Brole.B BTheB BorganizingB BandB BmaintainingB BofB BtheB BlayoutB BcanB BbeB BmuchB BmoreB Bwork,B BbutB BitB BeventuallyB BpaysB BoffB BtheB BnextB BtimeB BsomeoneB BusesB BtheB BprogramB BinB BtheB Bfuture.B BTherefore,B ByouB BcanB BbeB BintriguedB BtoB BneglectB BitB BandB BenableB BtheB BprogramB BpartsB BtoB BbecomeB Bintermixed,B BwhichB BwillB BcreateB BtwoB BpracticalB Bissues.B BFirst,B BwhenB BeverythingB BtouchesB BeverythingB Belse,B BitB BisB BhardB BtoB BlookB BatB BanyB BsetB BpieceB BinB Bseparation.B BYouB BwillB BhaveB BtoB BcreateB BaB BcomprehensiveB BunderstandingB BofB BtheB BfullB Bprogram.B BSecond,B BusingB BanyB BofB BtheB BfunctionalityB BfromB BtheB BprogramB BinB BdifferentB Bsituations,B ByouB BcanB BrewriteB BitB BinsteadB BofB BdisengagingB BitB BfromB BtheB Bcontext.

Modules

AB BModuleB BisB BaB BtypeB BofB BprogramB BthatB BdeterminesB BwhichB BpiecesB BitB BshouldB BdependB BonB BandB BwhatB BfunctionalityB BshouldB BitB BproduceB BforB BotherB BpiecesB BtoB Butilize.B BByB BputtingB BaB BlimitB BonB BtheB BwaysB BmodulesB BcommunicateB BwithB BoneB Banother,B BtheB BsystemB BisB BidenticalB BtoB BLEGO,B BwhereB BpiecesB BcommunicateB BusingB BstraightforwardB Bconnectors,B BandB BnotB BlikeB BmudB BwhereB BtheB BentireB BpiecesB BmixB BwithB Beverything.B BDependenciesB BareB BtheB BrelationshipsB BbetweenB Bmodules.B BWhenB BaB BmoduleB BwantsB BaB BpieceB BfromB BanotherB Bmodule,B BitB BdependsB BonB BthatB Bmodule.B BTheB BmoduleB BitselfB BillustratesB BthisB Bfact,B BandB BitB BisB BusedB BtoB BdetermineB BwhichB BotherB BmodulesB BshouldB BbeB BavailableB BtoB BuseB BaB 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 Bpieces,B BandB BbeingB BableB BtoB BlaunchB BthoseB BpiecesB Bindividually,B BisB BthatB ByouB BcanB BapplyB BtheB BsameB BpieceB BinB BseparateB Bprograms.B BWhenB BtheB BduplicationB BofB BcodeB Bbegins,B BtheB BpackageB BcomesB BinB BtoB Bplay.B BAB BpackageB BisB BaB BblockB BofB BcodeB BthatB BcanB BbeB Bshared.B BItB BmayB BconsistB BofB BoneB BorB BmoreB BmodulesB BandB BholdsB BinformationB BaboutB BtheB BotherB BdependingB Bpackages.B BPackagesB BalsoB BcontainB BdocumentationB BdescribingB BitsB BfunctionsB BsoB BthatB BpeopleB BwhoB Bdidn’tB BwriteB BitB BcanB ButilizeB Bit.B BWhenB BaB BproblemB BoccursB BinB BaB Bpackage,B BorB ByouB BaddB BaB BnewB Bfeature,B BtheB BpackageB BupdatesB Bautomatically.B BNowB BprogramsB BdependingB BonB BitsB BupgradesB BtoB BtheB BlatestB Bversion.B BWorkingB BlikeB Bthis,B ByouB BneedB Binfrastructure.B BAB BplaceB BtoB BsaveB BandB BsearchB BforB BpackagesB BandB BanB BeasyB BwayB BtoB BupgradeB BandB BinstallB Bthem.B BWhenB BitB BcomesB BtoB BJavaScript,B BNPMB BprovidesB Bsupport.B B

DivideB BNPMB BintoB BtwoB Bthings:B BanB BonlineB BserviceB BwhereB ByouB BcanB BuploadB BandB BdownloadB BpackagesB BandB BaB BprogramB BthatB BhandlesB BtheB BinstallationB BandB Bmanagement.B BAlmostB BeveryB BcodeB BonB BNPMB BisB Blicensed.

ImprovisedB Bmodules

BeforeB BtheB ByearB B2015,B BtheB BJavaScriptB BlanguageB BdidB BnotB BcontainB BanyB Bbuilt-inB BmoduleB Bsystem,B BbutB BpeopleB BhaveB BbeenB BcreatingB BlargeB BsystemsB BusingB BJavaScriptB BforB BoverB BaB BdecadeB Bnow,B BandB BtheyB BrequiredB Bmodules.B BTheyB BdevelopedB BtheirB BmoduleB BsystemsB BandB BintegratedB BthemB BintoB BtheB Blanguage.B BYouB BcanB ButilizeB BJavaScriptB BfunctionsB BtoB BbuildB BlocalB BscopesB BandB BobjectsB BtoB BstandB BforB BmoduleB Blayouts.B BUseB BthisB BmoduleB BtoB BoverB BbetweenB BdayB BnamesB BandB Bnumbers.B BItsB BlayoutB BcontainsB BtheB BweekDay.B BNameB BandB BweekDay.

.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 BbutB BitB BdoesB BnotB 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.

EvaluatingB BdataB BasB Bcode

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 BFunctionB Bconstructor.B BItB BtakesB BtwoB BtypesB BofB Bargument,B BaB BstringB BwithB BaB Bcomma,B BdividedB BlistB BofB BargumentB BnamesB BandB BaB BstringB BwithB BtheB BbodyB Bfunction.B BItB BenclosesB BtheB BcodeB BinB BaB BfunctionB BvalueB BtoB BenableB BitB BgetB BitsB BownB Bscope.

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 BsameB BfunctionB BscopeB BasB BaB BmoduleB Bscope.

CommonJS

TheB BcommonB BapproachB BusedB BtoB BgobbleB BonB BJavaScriptB BmodulesB BisB BtheB BCommonJSB Bmodules.B BNode.jsB BusesB BthisB BapproachB BasB BwellB BasB BaB BlotB BofB BpackagesB BonB BNPM.B BTheB BmajorB BideaB BinB BCommonJSB BmodulesB 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 BitsB Binterface.B BTheB BloaderB BcoversB BtheB BmoduleB BcodeB BwithinB BaB Bfunction,B BandB BmodulesB BhaveB BtheirB BlocalB BscopeB Bautomatically.B BYouB BcanB BcallB BrequireB BtoB BseeB BtheirB BdependenciesB BandB BplaceB BtheirB BlayoutB BinB BtheB BobjectB BthatB BexportsB Bthem.B BThisB BexampleB BmoduleB BgivesB BaB Bdate-formattingB Bfunction.B BItB ButilizesB BtwoB BpackagesB BfromB BNPM,B BtheB 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 BsendsB BbackB BitsB BcontentsB BasB BaB Bstring.B BStandardB BJavaScriptB BdoesB BnotB BofferB BsuchB Bfunctionality,B BbutB BseveralB BotherB BJavaScriptB BenvironmentsB BsuchB BasB BNode.jsB BandB BtheB BbrowserB BoffersB BtheirB BuniqueB BwaysB BofB BaccessingB Bfiles.B BTheB BaboveB BexampleB BbluffsB BthatB BreadFileB Bexists.B BToB BkeepB BawayB BfromB BloadingB BtheB BsameB BmoduleB BseveralB Btimes,B ByouB BneedB BaB BstoreB B(cache)B BofB BalreadyB BloadedB Bmodules.B BIfB Bcalled,B BitB BexaminesB BifB BtheB BdemandedB BmoduleB BloadsB Band,B BifB Bnot,B BitB BloadsB Bit.B BItB BrequiresB BreadingB BtheB Bmodule’sB Bcode,B BenclosingB BitB BwithinB BaB BfunctionB BandB BcallingB Bit.B BTheB BlayoutB BofB BtheB BordinalB BpackageB BfromB BearlierB BisB BaB BfunctionB BandB BnotB BanB Bobject.B BTheB BCommonJSB BmodulesB BcreateB BanB BemptyB BlayoutB BobjectB BusingB BtheB BmoduleB BsystemB BforB ByouB BtoB Bexport,B BrestoreB BthatB BwithB BvaluesB BbyB BoverwritingB Bmodule.exports.B BModulesB BdoB BthisB BtoB BexportB BaB BsingleB BvalueB BinsteadB BofB BaB BlayoutB Bobject.B BByB BdescribingB Bexports,B BrequireB BandB BmoduleB BasB BparametersB BforB BtheB BcreatedB BenclosingB BfunctionB B(andB BsettingB BtheB BrightB BvaluesB BwhileB BcallingB Bit),B BtheB BloaderB BensuresB BthatB BtheseB BbindingsB BareB BaccessibleB BwithinB BtheB Bmodule’sB Bscope.B BStringsB BsetB BtoB BrequireB BisB BinterpretedB BtoB BaB BfilenameB BorB BwebB BaddressB BvaryB BinB BseparateB Bsystems.B BWhenB BitB BstartsB BwithB B“.B B/"B Bor.B B“/,"B BitB BisB BusuallyB BtranslatedB BasB BrelativeB BtoB BtheB BexistingB Bmodule’sB Bfilename.B BSoB B“.B B/B Bformat-date"B BwillB BbeB BtheB BfileB BcalledB Bformat-date.jsB BinB BtheB BsameB Bdirectory.

IfB BtheB BnameB BisB BnotB Brelative,B BNode.jsB BwillB BsearchB BforB BaB BpackageB BthatB BisB BinstalledB BbyB BthatB Bname.

Now,B BinsteadB BofB BwritingB ByourB BownB BINIB BfileB Bparser,B ByouB BcanB ButilizeB BoneB BfromB BNPM.

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"}

ECMAScriptB Bmodules

CommonJSB BmodulesB BperformB BwellB BwhileB BcombiningB BwithB BNPM,B BandB BtheyB BenableB BtheB BJavaScriptB BcommunityB BtoB BbeginB BcodesharingB BonB BaB BsubstantialB Bscale.B BTheB BnotationB BisB BquiteB Bweird.B BTheB BthingsB BaddedB BtoB BexportsB BareB BnotB BaccessibleB BwithinB BtheB BlocalB Bscope.B BWithoutB BrunningB BtheB BcodeB BofB BaB Bmodule,B BitB BwillB BbeB BtoughB BtoB BdetermineB BitsB BdependenciesB BbeforeB BtakingB BanyB Bargument.B BThatB BisB BtheB BreasonB BJavaScriptB BstandardB BestablishesB BitsB Bown,B BseparateB BmoduleB Bsystem.B BItB BisB BnamedB BcalledB BESB Bmodules,B BwhereB BESB BrepresentsB BECMAScript.B BTheB BinitialB BideaB BofB BdependenciesB BandB BinterfacesB BstayB BtheB Bsame,B BbutB BtheirB BdetailsB BareB Bdifferent.B BTheB BnotationB BintegratesB BintoB BtheB Blanguage.B BYouB BcanB BnowB BuseB BaB BuniqueB BimportB BkeywordB BtoB BaccessB BaB BdependencyB BinsteadB BofB BcallingB BaB Bfunction.

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 BfrontB BofB BaB Bclass,B BfunctionB BorB BbindingB BdefinitionB B(let,B Bconst,B BorB Bvar).B BAnB BESB Bmodule’sB BlayoutB BdoesB BnotB BrepresentB BaB BsingleB BvalueB BbutB BaB BsetB BofB BnamedB Bbindings.B BTheB BpreviousB BmoduleB BattachesB BformatDateB BtoB BaB Bfunction.B BIfB ByouB BimportB BfromB BaB BdifferentB Bmodule,B BtheB BbindingB BcomesB BwithB Bit,B BandB BnotB BtheB Bvalue,B BwhichB BmeansB BtheB BvalueB BofB BanB BexportingB BmoduleB BcanB BchangeB BtheB BbindingB BanyB Btime,B BandB BtheB BimportingB BmodulesB BwillB BrecognizeB BitsB BnewB Bvalue.B BIfB BaB BbindingB BisB BnamedB Bdefault,B BrecognizesB BitB BasB BtheB Bmodule’sB BmajorB BexportedB Bvalue.B BIfB BaB BmoduleB BlikeB BordinalB BimportsB BinB BtheB Bexample,B BomittingB BtheB BbracesB BacrossB BtheB BbindingB Bname,B ByouB BwillB BfindB BitsB BdefaultB Bbinding.B BToB BdevelopB BaB BdefaultB Bexport,B BwriteB BexportB BdefaultB BaheadB BofB Bexpression,B BaB BclassB BorB BaB BfunctionB Bdeclaration.

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 BbeforeB BaB Bmodule’sB BscriptB BbeginsB BtoB Brun.B BImportB BdeclarationsB BmayB BnotB BdisplayB BwithinB BfunctionsB BorB Bblocks,B BandB BtheB BdependentB BnamesB BshouldB BbeB BquotedB BstringsB BandB BnotB BarbitraryB Bexpressions.B BAB BlotB BofB BprojectsB BareB BwrittenB BthroughB BESB BmodulesB BandB BthenB BchangedB BtoB BsomeB BotherB BformatB BwhenB BitB BisB Bpublished.B BDuringB BaB BtransitionalB Bperiod,B BuseB BtwoB BseparateB BmoduleB BsystemsB BsideB BbyB Bside.

ModuleB Bdesign

ProgramB BstructuringB BisB BoneB BofB BtheB BniceB BfeaturesB BofB Bprogramming.B BAnyB BunknownB BfunctionalityB BcanB BmodelB BinB BdifferentB Bways.B BTheB BgoodB BprogramB BdesignB BisB BaB BpersonalizedB Bone,B BandB BthereB BisB BaB BmatterB BofB BpreferenceB BandB Btaste.B BToB BunderstandB BtheB BvalueB BofB Bwell-organizedB Bdesign,B ByouB BneedB BtoB BreadB BandB BworkB BonB BseveralB BprogramsB BandB BtakeB BnoteB BofB BperformingB BandB Bnon-performingB Bfunctions.B BTheB BmoduleB BdesignB BisB BstraightforwardB BtoB Buse.B BTheB BiniB BpackageB BmoduleB BfollowsB BtheB BstandardB BJSONB BobjectB BbyB BsupplyingB BstringifyB BandB BparseB B(toB BwriteB BanB BINIB Bfile)B Bfunctions,B Band,B BlikeB BJSON,B BchangesB BbetweenB BplainB BobjectsB BandB Bstrings.B BAB BlotB BofB BtheB BINI-fileB BparsingB BmodulesB BonB BNPMB BsupplyB BaB BfunctionB BthatB BreadsB BthatB BtypeB BofB BfileB BfromB BtheB BhardB BdiskB BandB BparsesB Bit.B BConcentratedB BmodulesB BthatB BcalculateB BvaluesB BareB BsuitableB BinB BaB BlargerB BrangeB BofB BprogramsB BthanB BlargerB BmodulesB BthatB BexecuteB BcomplexB BactionsB BthatB BhaveB BsideB Beffects.B BAnB BINIB BfileB BreaderB BthatB BwantB BtoB BreadB BtheB BfileB BfromB BdiskB BisB BnotB BusefulB BinB BcasesB BwherebyB BtheB Bfile’sB BcontentB BcomesB BfromB BanotherB Bsource.B BSimilarly,B BstatefulB BobjectsB BareB BoccasionallyB BnecessaryB BandB Buseful,B BbutB BifB ByouB BcanB BuseB BaB Bfunction,B ButilizeB Bit.B BVariousB BINIB BfileB BreadersB BonB BNPMB BgivesB BaB BlayoutB BstyleB BthatB BneedsB ByouB BtoB BbuildB BanB Bobject,B BthenB BloadB BtheB BfileB BintoB BtheB Bobject,B BandB BuseB BspecificB BmethodsB BtoB BachieveB BtheB BdesiredB Bresults.B BItB BisB BtheB Bobject-orientedB BstyleB BandB Btradition.B BInB BJavaScript,B BthereB BisB BnoB BparticularB BwayB BtoB BrepresentB BaB Bgraph.B BThereB BareB BvariousB BpathfindingB BpackagesB BavailableB BonB BNPM,B BbutB BnoneB ButilizesB BtheB BgraphB Bformat.B BTheyB BoftenB BletB BgraphB BedgesB BcontainB BaB Bweight,B BandB BthatB BisB BtheB BdistanceB BorB Bcost-relatedB BwithB Bit.B BForB Binstance,B BweB BhaveB BtheB BdijkstrajsB Bpackage.B BAB BrecognizedB BwayB BtoB Bpathfinding,B BrelatedB BtoB BtheB BfindRouteB BfunctionB BisB BtheB BDijkstra’sB Balgorithm,B BafterB BEdsgerB BDijkstra,B BtheB BpackageB BfirstB Bwriter.B BTheB BjsB BsuffixB BisB BregularlyB BattachedB BtoB BpackageB BnamesB BtoB BspecifyB BthatB ByouB BcanB BwriteB BinB BJavaScript.B BSo,B BifB ByouB BwantB BtoB BuseB BthatB Bpackage,B BensureB BthatB BtheB BgraphB BsavesB BinB BitsB BexpectedB Bformat.

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 BseparateB BdataB BstructuresB BtoB BdefineB BrelatedB Bthings,B BandB BitB BisB BhardB BtoB BcombineB Bthem.B BTherefore,B BwhenB ByouB BareB BdesigningB BforB Bcomposability,B BknowB BexactlyB BtheB BdataB BstructuresB BothersB BareB BusingB BandB ByouB BcanB BfollowB BtheirB Bexample.

Summary

InB BthisB Bchapter,B BweB BcoveredB BtheB BModules.B BModulesB BgiveB BstructureB BtoB BmoreB BextensiveB BprogramsB BbyB BdifferentiatingB BtheB BcodeB BintoB BbitsB BwithB BunderstandableB BdependenciesB BandB Binterfaces.B BTheB BinterfaceB BisB BaB BmoduleB BwhichB ByouB BcanB BseeB BfromB BotherB Bmodules,B BandB BtheB BdependenciesB BareB BdifferentB BmodulesB BthatB BitB Buses.

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BshowB BtheB BcurrentB BdayB BandB BtimeB BinB BtheB BfollowingB Bformat.

TodayB BisB BTuesday.

CurrentB BtimeB Bis:B B10B BPM:B B30:B B38

Solution

B B

ChapterB B12:B BAsynchronousB BProgramming

TheB BprocessorB BisB BaB BvitalB BpartB BofB BaB BcomputerB BthatB BperformsB BtheB BindividualB BstepsB BthatB BbalanceB BourB Bprograms.B BTheB BspeedB BlevelB BofB BsomethingB BlikeB BaB BloopB BthatB BinfluencesB BnumbersB BcompletionB BdependsB BonB BtheB Bprocessor'sB Bspeed.B BAB BlotB BofB BprogramsB BcommunicateB BwithB BthingsB BoutsideB BofB BtheB Bprocessor.B BForB Binstance,B BtheyB BmayB BinteractB BthroughB BaB BcomputerB BnetworkB BorB BdemandB BforB BdataB BfromB BtheB BhardB Bdisk,B BwhichB BisB BquiteB BslowerB BthanB BobtainingB BitB BfromB Bmemory.B BInB Bpart,B BtheB BoperatingB BsystemB BhandlesB BthisB BpartB BandB BwillB BchangeB BtheB BprocessorB BbetweenB BvariousB BprogramsB BthatB BareB Brunning.

Asynchronicity

InB BtheB BasynchronousB BprogrammingB Bmodel,B BeverythingB BoccursB BoneB BatB BaB Btime.B BIfB ByouB BcallB BaB BfunctionB BthatB BexecutesB BaB BlongB BdurationB Baction,B BresultsB BwillB BreturnB BwhenB BtheB BoperationB BcompletesB Bonly.B BNoB BotherB BactionB BwouldB BbeB BableB BtoB BtakeB BplaceB BduringB Bexecution.B BAnB BasynchronousB BmodelB BenablesB BseveralB BthingsB BtoB BoccurB BatB BtheB BsameB Btime.B BWhenB BanB BactionB Bbegins,B BtheB BprogramB BdoesB BnotB BstopB Brunning.B BWhenB BtheB BtaskB Bcompletes,B BitB BnotifiesB BtheB BprogramB BandB BcanB BaccessB BtheB BresultB B(forB Binstance,B BtheB BinformationB BreadB BfromB Bdisk).B BYouB BcanB BdifferentiateB BbetweenB BsynchronousB BandB BasynchronousB BprogrammingB BthroughB BaB BlittleB Bexample:B BaB BprogramB BthatB BobtainsB BtwoB BresourcesB BfromB BtheB BnetworkB BandB BthenB BunifiesB BtheB Bresults.

InB BanB BasynchronousB Benvironment,B BtheB BrequestB BfunctionB BreturnsB BwhenB BtheB BworkB Bcompletes.B BTheB BsimplestB BwayB BtoB BexecuteB BthisB BtaskB BisB BtoB BcallB BtheB BrequestsB BoneB BafterB Banother.B BItB BconsistsB BofB BtheB BdrawbackB BthatB BbeginsB BtheB BsecondB BrequestB BonlyB BwhenB BtheB BfirstB BtaskB Bcompletes.B BTheB BsumB BofB BbothB BresponseB BtimesB BwillB BbeB BtheB BtotalB BtimeB Btaken.B BToB BsolveB BthisB BproblemB BinB BaB BsynchronousB Bsystem,B BstartB BaddingB BthreadsB BofB Bcontrol.B BAB BthreadB BisB BaB BrunningB BprogramB BthatB BitsB BexecutionB BcouldB BbeB BrenderedB BwithB BotherB BprogramsB BthroughB BtheB BoperatingB BsystemB BbecauseB BmodernB BcomputersB BhaveB BseveralB Bprocessors,B BvariousB BthreadsB BcanB BrunB BatB BonceB BonB BseparateB Bprocessors.B BAB BsecondB BthreadB BmayB BbeginB BtheB BsecondB Brequest,B BandB BthenB BtheB BtwoB BthreadsB BbothB BwaitB BforB BtheirB BresultsB BtoB Breturn,B BafterB Bthat,B BtheyB BresynchronizeB BtoB BunifyB BbothB Bresults.B BInB BtheB BasynchronousB Bmodel,B BtheB BnetworkB BtimeB BisB BpartB BofB BtheB BtimelineB BforB BaB BstatedB BthreadB BofB Bcontrol.B BInB BanB BasynchronousB Bmodel,B BlaunchingB BaB BnetworkB BactionB BnotionalB BcreatesB BaB BdivisionB BinB BtheB Btimeline.B BTheB BprogramB BthatB BcommencesB BtheB BactionB BdoesB BnotB BstopB Brunning,B BandB BthenB BtheB BactionB BoccursB BwithB Bit,B BitB BinformsB BtheB BprogramB BwhenB BitB Bcompletes.

AnotherB BwayB BtoB BdetermineB BtheB BsimilaritiesB BisB BthatB BwaitingB BforB BtasksB BtoB BcompleteB BisB BindirectB BinB BtheB BsynchronousB Bmodel,B BwhileB BitB BisB BdirectlyB BunderB BourB Bcontrol,B BinB BtheB BasynchronousB Bone.

Callbacks

OneB BprocedureB BtoB BasynchronousB BprogrammingB BisB BtoB BenableB BfunctionsB BthatB BexecuteB BaB BslowB BactionB BtoB BgainB BanB BextraB Bargument,B BandB BtheB BargumentB BisB BcalledB BaB BcallbackB Bfunction.B BWhenB BtheB BactionB BbeginsB BandB Bends,B ByouB BshouldB BcallB BtheB BresultB BwithB BtheB BcallbackB Bfunction.B BForB Binstance,B BtheB BsetTimeoutB Bfunction,B BaccessibleB BbothB BinB 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 BTheB BexampleB BattachesB BsupportB BforB B"note"B BrequestsB BthatB BsendsB BaB BnoteB BtoB BaB BstatedB Bnest.B BOurB BimplementationB BcallsB Bconsole.logB BsoB BthatB BweB BcanB BcheckB BifB BtheB BrequestB BhasB Barrived.B BNestsB BconsistB BofB BaB BnameB BpropertyB BthatB BholdsB BitsB Bname.B BTheB BfourthB BargumentB BstatedB BtoB BtheB Bhandler,B Bdone,B BisB BaB BcallbackB BfunctionB BthatB BcallsB BwhenB BitB BhasB BcompletedB BtheB Btask.B BIfB ByouB BuseB BtheB Bhandler’sB BreturnB BvalueB BasB BtheB BvalueB BofB BtheB Bresponse,B BthatB BmeansB BthatB BaB BrequestB BhandlerB Bcan’tB BexecuteB BasynchronousB BactionsB Bitself.B BAB BfunctionB BperformingB BasynchronousB BactionsB BreturnsB BbeforeB BtheB BtaskB Bcompletes,B BhavingB BaB BcallbackB BreadyB BtoB BbeB BcalledB BuponB BwhenB BitB Bfinishes.B BInB BaB Bway,B BasynchronicityB BisB Bcontagious.B BAB BfunctionB BthatB BcallsB BaB BfunctionB BthatB BperformsB BasynchronouslyB BmustB BbeB BasynchronousB Bitself,B ButilizingB BaB BcallbackB BtoB BdeliverB BitsB Bresult.B BCallingB BaB BcallbackB BisB Berror-proneB BandB BmoreB BinvolvedB BthanB BsimplyB BsendingB BbackB BaB Bvalue.

Promises

WorkingB BwithB BabstractB BmethodsB BisB BsimplerB BwhenB BvaluesB BrepresentB BtheB Bmethods.B BInB BtheB BcaseB BofB BasynchronousB Bactions,B BinsteadB BofB BmakingB BpreparationsB BforB BaB BfunctionB BtoB BbeB BcalledB BatB BaB BcertainB BpointB BinB BtheB Bfuture,B BsendB BbackB BanB BobjectB BthatB BstandsB BforB BtheB BfutureB Bevent.B BAB BpromiseB BisB BanB BasynchronousB BactionB BthatB BcanB BfinishB BatB BsomeB BpointB BandB BprovideB Bvalue.B BItB BcanB BnotifyB BanyoneB BinterestedB BwhenB BitsB BvalueB BisB Bavailable.B BTheB BsimplestB BwayB BtoB BbuildB BaB BpromiseB BisB BbyB BcallingB BPromise.resolve.B BThisB BfunctionB BguaranteesB BthatB BtheB BvalueB ByouB BsetB BenclosesB BinB BaB Bpromise.B BIfB BitB BisB BaB BpromiseB 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 BnetworkB BrequestB BcouldB Bfail,B BorB BsomeB BasynchronousB BcodeB BcomputationB BcouldB BbringB BanB Bexception.B BAsynchronousB BprogrammingB BcallbackB BstyleB BmostB BconsistentB BissuesB BareB BthatB BitB BmakesB BitB BveryB BhardB BtoB BensureB BfailuresB BrevealB BcorrectlyB BtoB BtheB Bcallbacks.B BAB BgenerallyB BusedB BmethodB BisB BthatB BtheB BfirstB BargumentB BtoB BtheB BcallbackB BisB BusedB BtoB BspecifyB BtheB BfailedB Baction,B BandB BtheB BsecondB BhasB BtheB BvalueB BprovidedB BbyB BtheB BactionB BwhenB BitB Bcompletes.B BSuchB BcallbackB BfunctionsB BalwaysB BcheckB BifB BtheyB BobtainB BanB BexceptionB BandB BensureB BthatB BanyB BuprisingB Bproblems,B BincludingB BexceptionsB BoutputB BbyB BfunctionsB BtheyB Bcall,B BareB BgivenB BtoB BtheB BcorrectB Bfunction.B BTheyB BcanB BreduceB BwhenB BitB BcompletesB BsuccessfullyB BorB BdeclinedB BwhenB BitB Bfails.B BCallB BReduceB BhandlersB BitB BonlyB BwhenB BtheB BtaskB BcompletesB BsuccessfullyB BandB BdeclinesB BautomaticallyB BgeneratedB BtoB BtheB BreturnedB BnewB Bpromise.B BAndB BwhenB BaB BhandlerB BoutputsB BanB Bexception,B BthisB BautomaticallyB BtriggersB BtheB BpromiseB BprovidedB BbyB BitsB BrecentB BcallB Bdeclines.B BWhenB BanB BelementB BinB BaB BchainB BofB BasynchronousB BactionsB Bfails,B BtheB BoutputB BofB BtheB BwholeB BchainB BdeclinesB BandB BnoB BsuccessB BhandlersB BcallB BpastB BtheB BfailingB Bpoint.B BMuchB BlikeB BsolvingB BaB BpromiseB BproducesB BaB Bvalue,B BrejectingB BoneB BalsoB BprovideB Bone,B BoftenB BcalledB BtheB BrejectionB Breason.B BIfB BanB BexceptionB BinB BaB BhandlerB BfunctionB BcreatesB BtheB Brejection,B BuseB BtheB BexceptionB BvalueB BasB BtheB Breason.B BComparably,B BwhenB BaB BhandlerB BsendsB BbackB BaB BrejectedB Bpromise,B BthatB BrejectionB BgoesB BintoB BtheB BnextB Bpromise.B BThere’sB BaB BPromise.B BRejectB BfunctionB BthatB BdevelopsB BaB Bnew,B BinstantlyB BdeclinedB Bpromise.

IfB BaB BcatchB BhandlerB BoutputB BanB Berror,B BtheB BnewB BpromiseB BisB BequallyB Bdeclined.B BInB Bshorthand,B BthenB BalsoB BtakeB BaB BdeclineB BhandlerB BasB BaB BsecondB Bargument,B BsoB ByouB BshouldB BinstallB BtheB BtwoB BtypesB BofB BhandlersB BinB BanB BindividualB BmethodB Bcall.B BAB BfunctionB BsentB BtoB BtheB BPromiseB BconstructorB BacceptsB BaB BsecondB Bargument,B BtogetherB BwithB BtheB BresolveB Bfunction,B BwhichB BitB BcanB BuseB BtoB BdeclineB BtheB BnewB Bpromise.B BTheB BchainsB BofB BpromiseB BvaluesB BdevelopedB BbyB BcallsB BtoB BthenB BandB BcatchB BrecognizedB BasB BaB BpipelineB BasynchronousB BvaluesB BorB BfailuresB BmoveB Bthrough.B BBecauseB BthoseB BchainsB BbuiltB BbyB BregisteringB Bhandlers,B BeveryB BlinkB BconsistsB BofB BeitherB BbothB BorB BaB BsuccessB BhandlerB BorB BaB BrejectionB BhandlerB BrelatedB BtoB Bit.B BHandlersB BthatB BdoB BnotB BmatchB BtheB BtypeB BofB BoutputB Bdeclined.B BButB BthoseB BthatB BmatchB BgetsB Bcalled,B BandB BtheirB BoutputB BdecidesB BwhatB BtypeB BofB BvalueB BcomesB Bnext,B BsuccessB BwhenB BitB BsendsB BbackB BaB Bnon-promiseB Bvalue,B BrejectionB BwhenB BitB BoutputB BanB Bexception,B BandB BtheB BresultB BofB BaB BpromiseB BwhenB BitB BsendsB BbackB BoneB BofB Bthose.

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 BtoB BconveyB BaB BsignalB BisB BobstructingB BtheB BwayB BofB BtheB Bsignal.B BItB BisB BviableB BforB BaB BsignalB BtoB BbeB BtransferredB BbutB BgotB Bdeclined.B BOften,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.

CollectionsB BofB Bpromises

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 BinformationB BaboutB BtheB Bnetwork,B BdetermineB BwhereB BitB BtransfersB BtheB Bmessage.

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 Bdistance.B BIfB BtheB BmessageB BisB BattachedB BtoB BaB BdirectB Bneighbor,B BitB BisB BconveyedB BasB Busual.B BIfB Bnot,B BitB BisB BwrappedB BinB BanB BobjectB BandB BtransferredB BtoB BaB BneighborB BcloserB BtoB BtheB Btarget,B BthroughB BtheB B"route"B BrequestB Btype,B BthatB BwillB BmakeB BthatB BneighborB BrepeatB BtheB BsameB Bcharacter.

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 BcontainsB BaB BkeyB Bmethod,B BbutB BthatB BsendsB BbackB BanB BiteratorB BinsteadB BofB BanB Barray.B BAnB BiteratorB BcanB BbeB BtransformedB BtoB BanB BarrayB BusingB BtheB BArray.fromB Bfunction.B BVariousB BasynchronousB BactionsB BareB BtiedB BtogetherB BinB BunclearB Bways.B BNowB ByouB BneedB BaB BrecurringB BfunctionB BtoB BmodelB BloopingB BacrossB BtheB Bnests.B BInB BaB BsynchronousB BprogrammingB Bmodel,B BitB BisB BeasyB BtoB Bexpress.B BJavaScriptB BalsoB BletsB ByouB BwriteB Bpseudo-synchronousB BcodeB BtoB BdefineB BasynchronousB Bcomputation.B BAnB BasyncB BfunctionB BisB BaB BfunctionB BthatB BcompletelyB BbringB BbackB BaB BpromiseB BandB BthatB BcanB BwaitB BforB BotherB BpromisesB BinB BaB BsynchronousB Bway.B BRewriteB BfindInStorageB BlikeB Bthis:

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 BfunctionB Bkeyword.B BMethodsB BcanB BalsoB BbecomeB BasyncB BbyB BwritingB BasyncB BbeforeB BtheirB Bname.B BWhenB BtheB BfunctionB BorB BmethodB BisB Bcalled,B BitB BbringsB BbackB BaB Bpromise.B BWhenB BtheB BbodyB BreturnsB Bsomething,B BthatB BpromiseB BisB Bsettled.B BIfB BitB BoutputsB BanB Bexception,B BtheB BpromiseB BisB Bdeclined.B BWithinB BanB BasyncB Bfunction,B BtheB BwordB BawaitB BisB BsetB BinB BfrontB BofB BanB BexpressionB BtoB BawaitB BaB BpromiseB BtoB BgetB BsettledB BandB BonlyB BthenB BproceedsB BtoB BexecuteB BtheB Bfunction.B BSuchB BfunctionsB BcannotB BrunB BfromB BstartB BtoB BfinishB BatB Bonce,B BbutB BitB BcanB BbeB BfrozenB BatB BpointsB BandB BcanB BrestartB Blater.B BForB Bnon-trivialB BasynchronousB Bcode,B BthisB BnotationB BisB BeasierB BthanB BdirectlyB BthroughB Bpromises.

Generators

AsyncB BfunctionsB BdoB BnotB BhaveB BtoB BbeB BpausedB BandB BthenB BresumedB Bagain.B BJavaScriptB BconsistsB BofB BaB BfeatureB BcalledB BgeneratorB Bfunctions.B BTheseB BareB BidenticalB BbutB BdoB BnotB BcontainB BtheB Bpromises.B BWhenB ByouB BcallB BaB BfunctionB BwithB Bfunction*B B(putB BanB BasteriskB BafterB BtheB BwordB Bfunction),B BitB BchangesB BtoB BaB Bgenerator.B BWhenB ByouB BcallB BaB Bgenerator,B BitB BsendsB BbackB BanB Biterator.

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 Bbeginning.B BEachB BtimeB ByouB BcallB BnextB BonB BtheB Biterator,B BtheB BfunctionB BwillB BrunB BuntilB BitB BhitsB BaB ByieldB Bexpression,B BwhichB BwillB BpauseB BitB BandB BmakeB BtheB ByieldedB BvalueB BtheB BnextB BvalueB BprovidedB BbyB BtheB Biterator.B BWhenB BtheB BfunctionB Breturns,B BtheB BiteratorB Bcompletes.B BWritingB 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.

TheB BeventB Bloop

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 BwithB BanB BemptyB Bstack,B ByourB BcatchB BhandlersB BwillB BnotB BbeB BonB BtheB BstackB BwhenB BanB BexceptionB Bruns.

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 BaB BJavaScriptB BenvironmentB BrunsB BoneB BprogramB BatB Bonce.B BWhenB Bthere’sB BnothingB BtoB Bdo,B BtheB BloopB Bstops.B BButB BasB BeventsB BcomeB Bin,B BtheyB BareB BattachedB BtoB BaB Bqueue,B BandB BtheirB BcodeB BperformsB BoneB BafterB Bother.B BBecauseB BtwoB BthingsB BdoB BnotB BrunB BatB Bonce,B Bslow-runningB BcodeB BmayB BholdB BupB BtheB BhandlingB BofB BotherB Bevents.B BTheB BbelowB BexampleB BsetsB BaB BtimeoutB BbutB BalsoB BlingersB BuntilB BafterB BtheB Btimeout’sB BfixedB BpointB BofB Btime,B BmakingB BtheB BtimeoutB BtoB BbeB Blate.

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 BresolvedB Balready,B BwaitingB BforB BitB BwillB BmakeB ByourB BcallbackB BrunB BafterB BtheB BexistingB BscriptB Bcompletes,B BinsteadB BofB Bimmediately.

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 BoccurringB BtransformationB BbesidesB BtheB BonesB BthatB BprogramB Bthemselves.B BButB BwhenB ByouB BrunB BanB BasynchronousB Bprogram,B BthisB BisB BanotherB Bscenario.B BTheyB BcouldB BcontainB BgapsB BduringB BexecutionB BthatB BotherB BcodeB BcanB Butilize.B BBelowB BisB BanB Billustration.B BOneB BofB BourB Bcrow’sB BfavoritesB BisB BtoB BenumerateB BtheB BnumberB BofB BchicksB BthatB BhatchB BduringB BtheB BvillageB BeachB Byear.B BNestsB BkeepB BthisB BcountB BwithinB BtheirB BstorageB Bbulbs.B BTheB BbelowB BcodeB BtriesB BtoB BtallyB BtheB BcountsB BfromB BeveryB BnestB BforB BaB BparticularB Byear:

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 Bawait,B BandB ByouB BshouldB BknowB BwhereB BgapsB BareB BwithinB ByourB Bcode.

Summary

WeB BlearnedB BeverythingB BaboutB BAsynchronousB BprogrammingB BinB BthisB Bchapter.B BAsynchronousB BprogrammingB BenablesB BtheB BexpressionB BwaitingB BforB BactionB BthatB BrunsB BforB BaB BlongB BtimeB BwithoutB BgivingB BtheB BprogramB BproblemsB BthroughoutB BtheB Boperations.B BJavaScriptB BenvironmentsB BgenerallyB ButilizeB BthisB BstyleB BofB BprogrammingB BthroughB Bcallbacks,B BfunctionsB BwhichB BtoB BcallB BwhenB BactionsB Bend.B BWeB BtouchedB BonB BtheB BeventB BloopB BasB Bwell.B BAnB BeventB BloopB BcreatesB BaB BplanB BforB BsuchB BcallbacksB BtoB BbeB BcalledB BwhenB BitB BisB Btime,B BoneB BafterB Banother,B BtoB BavoidB Boverlapping.

Exercise

WriteB BaB BJavaScriptB BprogramB BtoB BtransformB BanB BasynchronousB BfunctionB BtoB BreturnB BaB Bpromise.

Solution

ChapterB B13:B BParsing

DevelopingB Bone'sB BprogrammingB BlanguageB BisB BrelativelyB BeasyB BandB BveryB Bexciting.B BThisB BchapterB BwillB BteachB ByouB BhowB BtoB BbuildB ByourB Blanguage.B BWeB BwillB BcreateB BaB BprogrammingB BlanguageB BcalledB BEgg.B BAB Bsmall,B BsimpleB BlanguageB BisB ByetB BstrongB BenoughB BtoB BexpressB BanyB BthinkableB Bcomputation.B BItB BenablesB BpureB BabstractionB BdeterminedB Bfunctions.

Parsing

TheB BnoticeableB BpartB BofB BaB BprogrammingB BlanguageB BisB BtheB BnotationB BorB Bsyntax.B BAB BparserB BisB BaB BprogramB BthatB BreadsB BtheB BtextB BandB BprovidesB BaB BdataB BlayoutB BthatB BreflectsB BtheB BlayoutB BofB BtheB BprogramB BwithinB BthatB Btext.B BIfB BtheB BtextB BrefusesB BtoB BcreateB BaB BvalidB Bprogram,B BtheB BparserB BwouldB BindicateB BanB Berror.B BOurB BlanguageB BwouldB BcontainB BpreciseB BandB BuniformB Bsyntax.B BEverythingB BincludedB BinB BEggB BisB BanB Bexpression.B BAnB BexpressionB BcouldB BbeB BtheB BbindingB Bname,B Bnumber,B Bstring,B BorB Bapplication.B BUtilizeB BApplicationsB BforB BfunctionB BcallsB BandB BasB BwellB BasB BconstructsB BlikeB BifB BorB Bwhile.

ToB BkeepB BtheB BsimpleB Bparser,B BstringsB BwithinB BtheB BEggB BdoB BnotB BsupportB BbackslashB Bescapes.B BAB BstringB BisB BaB BsuccessionB BofB BcharactersB BthatB BareB BnotB BdoubleB Bquotes,B BenclosedB BinB Bdouble-quotes.B BNameB BBindingB BcanB BcontainB BanyB BcharacterB BthatB Bisn'tB BwhitespaceB BandB BthatB BdoB BnotB BcontainB BaB BuniqueB BmeaningB BinB BtheB Bsyntax.B BWriteB BapplicationsB BinB BJavaScript,B BbyB BplacingB BparenthesesB BafterB BanB BexpressionB BandB BputtingB BanyB BnumberB BofB BargumentsB BwithinB BtheB Bparentheses,B BdifferentiatedB BbyB Bcommas.

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 ButilizedB BsimilarlyB BlikeB BotherB Bfunctions.B BAndB BtheB BsyntaxB BcontainsB BzeroB BblockB Bconcept,B BsoB BaB BconstructB BisB BneededB BtoB BrepresentB BrunningB BseveralB BthingsB BinB Bsuccession.B BTheB BdataB BlayoutB BtheB BparserB ButilizesB BtoB BdefineB BaB BprogramB BcontainingB BexpressionB Bobjects.B BEachB BoneB BcontainsB BaB BtypeB BofB BpropertyB BsignifyingB BtheB BkindB BofB BexpressionB BitB BisB BandB BseveralB BotherB BpropertiesB BtoB BdetermineB BitsB Bcontent.B BExpressionsB BofB BtypeB B"value"B BmeanB BstringsB BorB Bnumbers.B BTheirB BvalueB BpropertyB BconsistsB BofB BtheB BstringB BorB BnumberB BvalueB BthatB BtheyB BstandB Bfor.B BUseB BexpressionsB BofB BtypeB B"word"B BforB BidentifiersB B(names).B BTheseB BtypesB BofB BobjectsB BcontainB BaB BnameB BpropertyB BthatB BholdsB BtheB Bidentifier’sB BtitleB BasB BaB Bstring.B BAndB BthenB BtheB B"apply"B BexpressionsB BstandB BforB Bapplications.B BTheyB BincludeB BanB BoperatorB BpropertyB BthatB BcitesB BtheB BappliedB Bexpression,B BtogetherB BwithB BanB BargsB BpropertyB BthatB BholdsB BanB BarrayB BofB BargumentB Bexpressions.

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 BasB BinputB BandB BsendB BbackB BanB BobjectB BthatB BconsistsB BofB BtheB BdataB BlayoutB BforB BtheB BexpressionB BatB BtheB BbeginningB BofB BtheB Bstring,B BtogetherB BwithB BtheB BstringB BpartB BleftB BafterB BparsingB BthisB Bexpression.B BWhenB ByouB BareB BparsingB Bsubexpressions,B ByouB BcanB BcallB BthisB BfunctionB Bagain,B BcapitulatingB BtheB BargumentB BexpressionB BwithB BtheB BremainingB Btext.B BThisB BtextB BcouldB BconsistB BofB BmoreB BargumentsB BorB BtheB BclosingB BparenthesisB BthatB BendsB BtheB BargumentB Blist.

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 BitB BaB BsyntaxB BtreeB BandB BaB BscopeB BobjectB BthatB BrelateB BnamesB BwithB Bvalues,B BandB BitB BwillB BaccessB BtheB BexpressionB BthatB BtheB BtreeB BstandsB BforB BandB BsendB BbackB BtheB BvalueB BthatB BitB Bprovides.

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 BvalueB BexpressionB BprovidesB BitsB Bvalue.B BToB Bbind,B BcheckB BifB BitB BdescribesB BinB BtheB BscopeB Band,B BifB Byes,B BgetB BtheB BvalueB BofB BtheB Bbinding.B BIfB BitB BcontainsB BaB BuniqueB BformB BthatB BdoesB BnotB BaccessB Banything,B BandB ByetB BtransfersB BtheB BargumentB BexpressionsB BwithB Bscope,B BtoB BtheB BfunctionB BthatB BinfluencesB BtheB Bform.B BIfB BtheB BcallB BisB Btypical,B BaccessB BtheB Boperator,B BdetermineB BifB BitB BisB BaB Bfunction,B BandB BcallB BitB BwithB BtheB BaccessibleB Barguments.B BUtilizeB BtheB BcommonB BJavaScriptB BfunctionB BvaluesB BtoB BstandB BforB BtheB BvalueB BofB BEgg’sB Bfunction.B BTheB BrecursiveB BlayoutB BofB BevaluatingB BisB BaB BsimilarB BlayoutB BofB BtheB Bparser,B BandB BtheB BtwoB BmirrorB BtheB BlayoutB BofB BtheB Blanguage.B BYouB BcanB BcombineB BtheB BparserB BusingB BtheB BevaluatorB BandB BevaluateB BwhenB Bparsing,B BbutB BseparatingB BthemB BgivesB BaB BclearerB BofB BtheB Bprogram.B BItB BisB BallB ByouB BneedB BtoB BcombineB BEgg.

SpecialB Bforms

TheB BspecialFormsB BobjectB BdescribesB BuniqueB BsyntaxB BinB BEgg.B BItB BrelatesB BwordsB BwithB BfunctionsB BthatB BaccessB BsuchB Bforms.B BItB BisB BpresentlyB Bempty.B BLetB BusB BinsertB Bif.

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 BpropertiesB BthatB BhaveB BtheirB BnameB BtallyB BwithB BbindingB Bnames.B BTheirB BvaluesB BareB BinB BaccordanceB BtoB BtheB BvaluesB BthoseB BboundedB Bbindings.B BBelowB BisB BanB BillustrationB BofB BanB BobjectB BtoB BstandB BforB BglobalB Bscope.B BToB BenableB BtheB ButilizationB BofB BtheB BearlierB BdescribedB BifB Bconstruct,B BtheB BBooleanB BvaluesB BmustB BbeB Baccessible.B BTherefore,B BthereB BareB BtwoB BBooleanB BvaluesB Bonly,B BallB ByouB BneedB BtoB BdoB BisB BtoB BbindB BtwoB BnamesB BtoB BtheB BvaluesB BtrueB BandB BfalseB BandB ButilizeB Bthem.

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 Bvalue.

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 Boperators,B BletsB BincludeB BfunctionB BvaluesB BtoB Bscope.B BWeB BwillB BuseB BfunctionB BonB BfewB BoperatorB BfunctionsB BwithinB BaB Bloop,B BandB BnotB BstatingB BthemB BoneB BbyB Bone.

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 BJavaScriptB BprogrammingB Blanguage.B BTheB BinformationB BinB BthisB BbookB BwillB BhelpB ByouB BtoB BunderstandB BandB BpracticeB BtheB BseveralB BJavaScriptB Boperators,B BloopsB BandB BconditionalB Bstatements,B Bfunctions,B BtheB BscopeB BofB Bvariables,B BinventB Btypes,B BandB BsoB Bon.B BAndB BwhileB BedgingB BtowardB BtheB BendB BofB BtheB Bcourse,B ByouB BwillB BhaveB BanB BexcellentB BunderstandingB BofB BtheB BJavaScriptB BlanguageB BasB ByouB BwillB BhaveB BlearnedB BJavaScriptB BandB Bforms,B ByouB BwillB BunderstandB BtheB BbasicsB BofB BjQuery,B BframesB BandB BdebuggingB Bscripts.B BTheB BbestB BadviceB BtoB BgiveB BaB BprogrammerB BisB BtoB BkeepB BpracticingB BbecauseB BthatB BisB BtheB BonlyB BwayB ByouB BcanB BmasterB BwhatB ByouB BhaveB Blearned.B B