Professional Documents
Culture Documents
Ryan roffe
©B BCopyrightB B2023B B–B BRyanB Broffe
AllB BrightsB Breserved.
TheB BcontentB BcontainedB BwithinB BthisB BbookB BmayB BnotB BbeB Breproduced,B Bduplicated,B BorB
transmittedB BwithoutB BdirectB BwrittenB BpermissionB BfromB BtheB BauthorB BorB BtheB Bpublisher.
B
UnderB BnoB BcircumstancesB BwillB BanyB BblameB BorB BlegalB BresponsibilityB BbeB BheldB BagainstB BtheB
publisher,B BorB Bauthor,B BforB BanyB Bdamages,B Breparation,B BorB BmonetaryB BlossB BdueB BtoB BtheB
B
LegalB BNotice:
ThisB BbookB BisB BcopyrightB Bprotected.B BItB BisB BonlyB BforB BpersonalB Buse.B BYouB BcannotB Bamend,B
distribute,B Bsell,B Buse,B BquoteB BorB BparaphraseB BanyB Bpart,B BorB BtheB BcontentB BwithinB BthisB
B
DisclaimerB BNotice:
PleaseB BnoteB BtheB BinformationB BcontainedB BwithinB BthisB BdocumentB BisB BforB BeducationalB BandB
entertainmentB BpurposesB Bonly.B BAllB BeffortB BhasB BbeenB BexecutedB BtoB BpresentB Baccurate,B BupB
B
toB Bdate,B Breliable,B BcompleteB Binformation.B BNoB BwarrantiesB BofB BanyB BkindB BareB BdeclaredB BorB
B
implied.B BReadersB BacknowledgeB BthatB BtheB BauthorB BdoB BnotB BengageB BinB BtheB BrenderingB BofB
B
legal,B Bfinancial,B Bmedical,B BorB BprofessionalB Badvice.B BTheB BcontentB BwithinB BthisB BbookB BhasB
B
beenB BderivedB BfromB BvariousB Bsources.B BPleaseB BconsultB BaB BlicensedB BprofessionalB BbeforeB
B
ByB BreadingB BthisB Bdocument,B BtheB BreaderB BagreesB BthatB BunderB BnoB BcircumstancesB BisB BtheB
authorB BresponsibleB BforB BanyB Blosses,B BdirectB BorB Bindirect,B BthatB BareB BincurredB BasB BaB BresultB
B
ofB BtheB BuseB BofB BtheB BinformationB BcontainedB BwithinB BthisB Bdocument,B Bincluding,B BbutB BnotB
B
BB
TABLE OF CONTENTS
Introduction
Chapter 1: What is JavaScript
Chapter 2: Values, Types, and Operators
Chapter 3: Program Structure
Chapter 4: Functions
Chapter 5: Data Structures: Objects and Arrays
Chapter 6: Higher-Order Functions
Chapter 7: The Secret Life of Objects
Chapter 8: A Robot
Chapter 9: Bugs and Errors
Chapter 10: Regular Expressions
Chapter 11: Modules
Chapter 12: Asynchronous Programming
Conclusion
Introduction
JavaScriptB BisB BaB BdistinguishedB BandB BdecipheredB BprogrammingB BlanguageB
thatB BadheresB BtoB BtheB BECMAScriptB Bspecification.B BTheB BprogrammingB
B
syntax,B
B Btop-qualityB Bfunctions,B BandB Bprototype-basedB Bobject-
orientation.B BAccompaniedB BbyB BHTMLB BandB BCSS,B BJavaScriptB BisB BoneB BofB
theB BsignificantB BtechnologiesB BofB BtheB BWorldB BWideB BWeb.B BJavaScriptB
B
facilitatesB BinterchangeableB BwebB BpagesB BandB BisB BaB BvitalB BpartB BofB BwebB
B
functional,B
B Bevent-driven,B Bprototype-basedB BandB Bobject-orientedB
programmingB Bstyles.B BJavaScriptB BupgradesB BwebB BuserB BinterfaceB BbyB
B
affirmingB BactivitiesB BtakenB BonB BtheB Bclient-sideB BbyB BtheB Buser.B BYouB BcanB
B
TheB BconceptsB BofB BJavaScriptB BareB BexplainedB BfurtherB BinB BthisB BbookB
withB BtheB BgoalB BtoB BhelpB ByouB BlearnB BandB BunderstandB BJavaScriptB
B
webB Bbrowser,B BandB BCSSB BareB BallB Bthat'sB BneededB BtoB BlearnB BJavaScript.B
B
ToB BgetB BtheB BlearningB BprocessB Bstarted,B BoneB BofB BtheB BessentialB BtoolsB BisB
B
aB BtextB Beditor,B BandB BitB BisB BrequiredB BtoB BwriteB Bcodes.B BYou’llB BalsoB BneedB
B
differentB BtypesB BofB BtextB BeditorsB BsuchB BasB BtheB BSublimeB BText,B
B
Notepad++B BandB BbrowsersB BsuchB BasB BFirefox,B BGoogleB BChrome,B BandB BsoB
B
on.B B
B
BB
Chapter 1: What is JavaScript
BB BB BB BB
beenB BadoptedB BbyB BallB BmajorB BwebB Bbrowsers.B BJavaScriptB BcanB BbeB BusedB
B
createB BdifferentB BformsB BofB BactivitiesB BwithinB BwebB BpagesB BandB BisB BoneB
B
ofB BtheB BessentialB BcomponentsB BofB BtheB BWorldB BWideB BWebB B(www),B
B
whichB
B BareB HTMLB
B (HypertextB
B MarkupB
B Language)B
B andB
B CSSB
B
developB BwebB Bpages.B BJavaScriptB BbringsB BaB BpageB BtoB BlifeB BbyB BaddingB
B
specialB BeffectsB BsuchB BasB Bsliders,B Bpop-ups,B BformB Bvalidations,B Betc.B BCSSB
B
Client-Side JavaScript
BB
soB BthatB BtheB BbrowserB BcanB BinterpretB BtheB Bcode.B BItB BenablesB BwebB BpagesB
B
JavaScriptB BcodeB BwhenB BtheyB BwantB BtoB BsubmitB BformsB BandB BalsoB
B
determineB BifB BallB BentriesB BareB BvalidB BbeforeB BitB BtransfersB BthemB BtoB BtheB
B
server.
B
Advantages of JavaScript
BB BB
·B BWithB BJavaScript,B BusersB BcanB BorganizeB BinputB BbeforeB BgettingB BtheB
pageB BsentB BtoB BtheB Bserver,B BwhichB BautomaticallyB BreducesB BloadsB BonB
B
theB Bserver.
B
·B BJavaScriptB BenablesB BswiftB BresponseB BtoB BpageB Bvisitors.B BTheB BpageB BdoesB
notB BhaveB BtoB BreloadB BbeforeB BvisitorsB BcanB BseeB BifB BthereB BwasB BanB BerrorB
B
inB Btyping.
B
·B BJavaScriptB BisB BusedB BtoB BbuildB BaB BreactiveB BinterfaceB BthatB BgivesB BaB
reactionB BwhenB BtheB BmouseB BhoversB BoverB Bthem.
B
Limitations of JavaScript
BB BB
Javascript Placement
BB
likeB Bthis:
B
<html>
<head>
<scriptB Btype="text/JavaScript">
<!--
functionB BsayHi()B B{
alert("HelloB BWorld")
}
//-->
</script>
</head>
<body>
<html>
<head>
</head>
<body>
<scriptB Btype="text/JavaScript">
<!--
document.write("HelloB BWorld")
//-->
</script>
<scriptB Btype="text/JavaScript">
<!--
functionB BsayHi()B B{
alert("HelloB BWorld")
}
//-->
</script>
</head>
<body>
<scriptB Btype="text/JavaScript">
<!--
document.write("HelloB BWorld")
//-->
</script>
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>
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
BOperators
InB BtheB BworldB BofB Bcomputers,B BthereB BisB Bdata.B BYouB BcanB BcreateB BnewB
data,B BreadB BdataB BandB BchangeB Bdata,B BwhichB BareB BallB BstoredB BasB BaB Blook-
B
alikeB BlongB BsuccessionB BofB Bbits.B BDefineB BbitsB BasB BzerosB BandB BonesB BthatB
takeB BaB BstrongB BorB BweakB Bsignal,B BandB BhighB BorB BlowB BelectricalB BchargeB
B
fromB BinsideB BtheB Bcomputer.B BAllB BdataB BandB BpiecesB BofB BinformationB BareB
B
describedB BasB BaB BsuccessionB BofB BzerosB BandB BonesB BandB BrepresentedB BinB
B
bits.
B
Values
TakeB BaB BdeepB BbreathB BandB BthinkB BofB BanB BoceanB BofB Bbits.B BTheB BlatestB BPCsB
containsB BmoreB BthanB B30B BbillionB BbitsB BinB BitsB BdataB Bstorage.B BWeB BuseB
B
becauseB BeveryB BbitB BofB BinformationB BisB BsplitB BintoB Bvalues.B BEveryB BvalueB
B
consistsB BofB BaB BtypeB BthatB BinfluencesB BitsB Brole,B BandB BvaluesB BcanB BbeB
B
numbers,B BtextB BorB Bfunctions,B Betc.B BToB BgenerateB Bvalue,B ByouB BneedB BtoB
B
invokeB BitsB Bname,B BandB BitB BappearsB BfromB BwhereB BitB BwasB Bstored.
B
Arithmetic
ArithmeticB BisB BtheB BmajorB BthingB BtoB BdoB BwithB Bnumbers.B BTheB
multiplication,B Baddition,B BandB BsubtractionB BofB BmoreB BthanB BoneB
B
ThisB BisB BanB BexampleB BofB BwhatB BtheyB BlookB BlikeB BinB BJavaScript:
B
insertedB BbetweenB BtwoB BvaluesB BwillB BproduceB BanotherB Bvalue.B BTheB B-B
B
operatorB BisB BforB BsubtractionB BandB BtheB B/B BoperatorB BisB BforB BtheB Bdivision.B
B
theB BoperatorsB BdecidesB BtheB BwayB BtheyB BareB Bapplied.B BIfB BseveralB
B
operatorsB BwithB BtheB BsameB BprecedenceB BshowB BrightB BnextB BtoB BeachB
B
otherB BlikeB B1B B-B B2B B+B B1,B BapplyB BthemB BleftB BtoB Bright:B B(1B B-B B2)B B+B B1.
B
SpecialB Bnumbers
JavaScriptB BconsistsB BofB BthreeB BuniqueB BvaluesB BthatB BdoB BnotB BactB BlikeB
numbersB BbutB BareB BregardedB BasB Bnumbers.B BInfinityB BandB B-InfinityB BareB
B
theB BfirstB Btwo,B BwhichB BmeanB BtheB BpositiveB BandB BnegativeB Binfinities,B
B
andB BtheB BlastB BvalueB BisB BtheB BNaN.B BNaNB BsaysB B“notB BaB Bnumber,”B
B
Strings
AB BstringB BisB BtheB BsuccessionB BofB Bnumbers.B BTheB BstringB BisB BtheB BnextB
dataB Btype,B BandB BtheyB BrepresentB Btext.B BStringsB BconfineB BtheirB BcontentB
B
inB Bquotes.
B
stringsB Bmatch.B BTheB BelementsB BwithinB BtheB BquotesB BcreateB BaB BstringB
B
stringsB Btogether.
B
Unary operatorsBB
SymbolsB BdoB BnotB BrepresentB BallB BtheB Boperators.B BYouB BcanB BwriteB BsomeB
operatorsB BinB Bwords.B BAB BclearB BexampleB BisB BaB BtypeB BofB Boperator,B BandB
B
thisB BoperatorB BcreatesB BaB BstringB BvalueB BwithB BtheB BnameB BofB BtheB BtypeofB
B
console.log(typeofB B4.5)
//B B→B Bnumber
console.log(typeofB B"x")
//B B→B Bstring
TheB BsecondB BdisplayedB BoperatorB BisB BcalledB BtheB BbinaryB BoperatorB
becauseB BtheyB BuseB BtwoB Bvalues,B BwhileB BoperatorsB BthatB BuseB BoneB BvalueB
B
andB Bfalse.
B
Comparison
operatorsB BinB BaB BBooleanB BvalueB BthatB BdeterminesB BifB BtheB BcontainedB
B
charactersB B(!B B-,B BandB BsoB Bon)B BareB BalsoB BpresentB BinB BtheB Bordering.B
B
HereB BareB BotherB BrelatedB BoperatorsB B<=B B(lessB BthanB BorB BequalB Bto),B B>=B
(greaterB BthanB BorB BequalB Bto),B B==B B(equalB Bto),B Band!=B B(notB BequalB Bto).
B
signifiesB BlogicalB BorB BandB BitsB BresultsB BdependB BonB BwhereB BtheB BvaluesB
B
TheB B||B BconsistsB BofB BtheB BlowestB BprecedenceB BofB BallB Boperators,B BthenB
&&,B BtheB BcomparisonB BoperatorsB B(>,B B==,B Betc.),B BandB BsoB Bon.B BTheB
B
1B B+B B1B B==B B2B B&&B B10B B*B B10B B>B B50
EmptyB Bvalues
NullB BandB BundefinedB BareB BtheB BonlyB BtwoB BtypesB BofB BspecialB BvaluesB BthatB
areB BusedB BtoB BindicateB BtheB Bnon-appearanceB BofB BanB BimportantB Bvalue.B
B
coercionB Brule.B BInB BtheB BfirstB Bexpression,B BtheB BnullB BturnsB BtoB B0,B BandB
B
BtheB B5B BinB BtheB BsecondB BremainsB B5B B(fromB BstringB BtoB Bnumber).B BInB BtheB
BthirdB Bexpression,B BthereB BwasB BaB BstringB BconcatenationB BbeforeB BtheB
numericB Baddition,B BwhichB BconvertsB BtheB B1B BtoB B1B B(fromB BnumberB BtoB BaB
B
string).B BWhenB BoddB BnumbersB BsuchB BasB B"five"B BorB BundefinedB BchangesB
B
toB BtheB Bnumber,B BitB BgetsB BtheB BvalueB BofB BNaN.B BIfB ByouB BwantB BtoB
B
differentiateB BbetweenB BvaluesB BofB BtheB BsameB BtypeB BusingB B==,B BtheB
B
outputB BshouldB BbeB BtrueB BifB BtheB BvaluesB BareB BsimilarB BexceptB BNaN.B BIfB
B
youB BwantB BtoB BtestB BifB BaB BvalueB BcontainsB BaB BrealB Bvalue,B BuseB BtheB B==B
B
(or!B B=)B BoperatorB BtoB BcompareB Bit.B BToB BavertB BunexpectedB BtypeB
B
valuesB BcontainedB BinB BtheB BleftB BsideB BtoB BBooleanB BtypeB BtoB Bdecide,B
B
althoughB BitB BdependsB BonB BtheB BoperatorsB BandB BtheB BtypeB BofB BgeneratedB
B
result,B BbutB BwillB BalwaysB BreinstateB BtheB BleftB BorB Bright-handB Bvalue.B BTheB
B
||B BoperatorB BsendsB BbackB BvalueB BtoB BtheB BleftB BwhenB BitB BcanB BbeB BchangedB
B
toB BtrueB BandB BwillB BreinstateB BtheB BvalueB BtoB BtheB Bright.
B
numbersB BtoB BBooleanB BvalueB BconversionB BrulesB BindicateB BthatB B0,B BNaN,B
B
andB BemptyB BstringB B(")B BcountB BasB BfalseB BwhileB BotherB BvaluesB BareB Btrue.B
B
ThereforeB B0B B||B B-1B BoutputsB B-1,B BandB B""B B||B B"!?"B ByieldsB B"!?".B BTheB B&&B
B
valuesB BtoB BtheB BleftB BcanB BbeB BchangedB BtoB Bfalse,B BreturnB BtheB Bvalue,B BorB
B
itB BsendsB BtheB BvalueB BtoB BtheB Bright.B BBothB BoperatorsB BevaluateB BtheB
B
valueB BtoB BtheB BrightB BonlyB BwhenB BitB BisB Brequired.B BForB Bexample,B BweB
B
haveB BtheB BfollowingB BvaluesB BsetB BasB BtrueB B||B BX,B BtheB BvalueB BofB BXB BwillB
B
beB BtrueB BandB BwillB BnotB BconsiderB Bit.B BTheB BsameB BruleB BappliesB BtoB BtheB
B
falseB B&&B BX,B BwhichB BtheB BxB BisB BfalseB BandB BwillB BoverlookB Bit.B BYouB BcanB
B
Summary
ThisB BchapterB BlooksB BatB BtheB BfourB BtypesB BofB BJavaScriptB Bvalues,B BwhichB
areB Bstrings,B Bnumbers,B BundefinedB BvaluesB BandB BBooleans.B BTheseB BvaluesB
B
areB BdevelopedB BbyB BinsertingB BtheirB BnamesB BasB Btrue,B BnullB BorB BvalueB
B
lookedB BatB BbinaryB BoperatorsB BforB BarithmeticB B(+,B B-,B B*,B B/,B BandB B%),B
B
stringB BconcatenationB B(+),B BcomparisonB B(==,B B!=,B B===,B B!==,B B<,B B>,B B<=,B B>=),B
B
andB BlogicB B(&&,B B||),B BandB BalsoB BvariousB BunaryB BoperatorsB B(-B BtoB BnullifyB
B
aB Bnumber,B B!B BtoB BnullifyB Blogically,B BandB BtypeB BofB BtoB BsearchB BforB BaB
B
value’sB Btype)B BandB BaB BternaryB BoperatorB B(?:)B BtoB BchooseB BoneB BofB BtwoB
B
valuesB BdependingB BonB BaB BthirdB Bvalue.B BYouB BwillB BgetB BsufficientB
B
informationB BtoB BuseB BJavaScriptB BlikeB BaB BsmallB Bcalculator,B BandB ByouB BwillB
B
Exercise
binaryB BoperatorB BsetB BtoB BtwoB BexpressionsB BorB BwithinB BparenthesesB BisB
B
sentence.B BAB BlistB BofB BstatementsB BisB BcalledB BaB Bprogram,B BandB BtheB BmostB
B
accessibleB BtypeB BofB BstatementB BisB BaB BlineB BofB BcodeB BwithB BaB BsemicolonB
B
endingB Bit.
B
ForB Binstance:
1;
!false;
WithB BthisB Bfunction,B BaB BstatementB BcanB BstandB Bindependently,B BandB BitB
canB BaddB BaB BfeatureB BthatB BchangesB BcolorsB BoccasionallyB BtoB BaB BscreenB BorB
B
modifyB BtheB BinnerB BstateB BofB BtheB BmachineB BinfluencingB BtheB BfollowingB
B
Bindings
JavaScriptB BusesB BbindingB BofB BvariablesB BtoB BholdB Bvalues,B BforB Binstance:
GetB BmoneyB B=B B5B B*B B5;
GetB BisB BtheB BkeywordB BinB BthatB Bstatement,B BandB BitB BmeansB BthatB BtheB
sentenceB BwillB BspecifyB BaB BbindingB BtogetherB BwithB BtheB BbindingB BnameB
B
andB BvalueB BcanB BbeB BattachedB BusingB BtheB B=B BoperatorB BandB BanB
B
expression.B BUseB BaB BdefinedB BbindingB BasB BanB Bexpression,B BanB BexpressionB
B
produceB BtheB BundefinedB Bvalue.B BYouB BcanB BdefineB BmultipleB BbindingB BbyB
B
oftenB BusedB BtoB BdeclareB BaB BnameB BtoB BaB BvalueB BtoB BenableB BeasyB
B
BindingB Bnames
AlthoughB BthereB BareB BsomeB BreservedB BwordsB BlikeB Bconst,B Bclass,B Bdefault,B
break,B Bcontinue,B Bdelete,B Bdo,B BelseB ByetB BanyB BwordB BcanB BbeB BcalledB BaB
B
bindingB Bname,B BitB BcanB BalsoB BconsistB BofB BdigitsB BbutB BdoB BnotB BbeginB BtheB
B
statementB BwithB BaB Bfigure.B BAB BbindingB BnameB BcanB BalsoB BcontainB BdollarB
B
signsB B($)B BorB BunderscoresB B(_)B BbutB BdoB BnotB BentertainB BanyB BotherB
B
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
communicateB BwithB BtheB BlaunchedB BwebsiteB BasB BwellB BasB BreadB BtheB
B
Functions
AB BbitB BofB BprogramB BenclosedB BinB BvalueB BisB BcalledB BaB Bfunction,B BandB
theseB BvaluesB BareB BaddedB BtoB BlaunchB BtheB BwrappedB Bprogram.B BForB
B
instance,B BaB BfunctionB BthatB BdisplaysB BaB BsmallB BdialogB BboxB BforB BuserB
B
input.
B
PromptB B("EnterB Bpasscode");
TheB BprocessB BofB BeffectingB BaB BfunctionB BisB BdescribedB BasB BaB Bcalling,B
invoking,B BorB Bapplying.B BCallB BaB BfunctionB BbyB BinsertingB BparenthesesB
B
followingB BanB BexpressionB BthatB BprovidesB BaB BfunctionB Bvalue.B BSetB BtheB
B
itsB BargumentsB BtoB BtheB BdeviceB BthatB BoutputsB BtheB Btext.B BInB BmodernB
B
browsers,B BtheB BoutputB BisB BoftenB BinB BtheB BJavaScriptB BconsoleB BthatB BisB
B
invisibleB BbyB Bdefault;B ByouB BcanB BtapB BtheB BF12B BcommandB BonB ByourB
B
itB BisB BanB BexpressionB BthatB BreclaimsB BtheB BlogB BpropertyB BfromB BtheB
B
ReturnB Bvalues
FunctionsB BareB BusedB BtoB BproduceB BsideB Beffects.B BTheyB BcanB BalsoB BprovideB
valuesB BthatB BdoB BnotB BneedB BsideB Beffects.B BForB Binstance,B BtheB BfunctionB
B
Calculate.maxB BwillB BtakeB BaB BsumB BofB BnumberB BargumentsB BandB BreturnsB
B
theB Bgreatest.
B
console.log(Calculate.max(2,B B4));
//B B→B B4
JavaScriptB BregardsB BanythingB BthatB BprovidesB BvalueB BasB BanB Bexpression,B
whichB BenablesB BfunctionB BcallsB BtoB BattachB BintoB BtheB BsubstantialB
B
expression.B BLet’sB BcallB BtheB BCalculate.min,B BwhichB BisB BaB BdirectB BoppositeB
B
toB BCalculate.max:
B
console.log(Math.min(2,B B4)B B+B B100);
//B B→B B102
ControlB Bflow
WhenB BmoreB BthanB BoneB BstatementB BisB BwithinB BaB Bprogram,B BtheyB
executeB BinB BaB BstoryB BformB BfromB BtheB BbeginningB BofB BtheB BcodeB BtoB BtheB
B
end.B BThisB BtypeB BofB BprogramB BconsistsB BofB BtwoB BtypesB BofB Bstatement;B
B
theB BfirstB BdemandB BnumbersB BfromB BtheB BuserB BwhileB BtheB BsecondB
B
AB BvalueB BisB BchangedB BtoB BaB BnumberB BbyB BtheB BfunctionB BnumberB BandB
outputsB BaB BstringB Bvalue.
B
ConditionalB Bexecution
TheB BkeyboardB BisB BusedB BtoB BdevelopB BconditionalB BexecutionsB BinB
JavaScript.B BYouB BmayB BwantB BsomeB BcodeB BtoB BexecuteB Bif,B BandB BonlyB Bif,B BaB
B
specificB BconditionB BisB Bpositive.B BLetB BusB BdisplayB BtheB BsquareB BofB BtheB
B
TheB BifB BkeywordB BperformsB BorB BevadesB BaB BstatementB BdeterminedB BbyB
theB BBooleanB BexpressionB Bvalue.B BTypeB BtheB BdeterminingB BexpressionB
B
afterB BtheB BkeyboardB BwithinB BtheB BparenthesesB BaccompaniedB BbyB BtheB
B
numberB BfunctionB BreturnsB BNaNB BwhenB BanB BassignedB BstringB BisB BnotB BaB
B
validB Bnumber.B BStatementsB BafterB BtheB BifB BstatementB BisB BenclosedB BinB
B
bracesB B({and}).B BBracesB BareB BusedB BtoB BcategorizeB BdifferentB BnumbersB BofB
B
28
IfB BthereB BareB BmoreB BthanB BtwoB BpathsB BtoB BchooseB Bfrom,B ByouB BcanB
“chain”B Bmultiple
B
}B BelseB B{
console.log("Large");
}
TheB BprogramB BconfirmsB BifB BtheB BnumB BisB BlessB BthanB B10,B BandB BifB BitB Bis,B BitB
selectsB BthatB Bbranch,B BandB BthenB BdisplaysB B"Small".B BButB BifB BtheB BnumB BisB
B
greaterB BthanB B10,B BitB BselectsB BtheB BelseB BbranchB BwhichB BconsistsB BofB BaB
B
ThisB BisB BtheB BwayB BtoB BwriteB BaB BprogramB BthatB BdisplaysB BallB BtheB BevenB
numbersB BfromB B0B BtoB B12.
B
console.log(0);
console.log(2);
console.log(4);
console.log(6);
console.log(8);
console.log(10);
console.log(12);
AB BwayB BtoB BrunB BaB BclockB BofB BcodeB BmultipleB BtimesB BisB BdescribedB BasB BaB
loop.
B
TheB BloopingB BcontrolB BflowB BenablesB BtheB BuserB BtoB BreturnB BtoB BcertainB
pointsB BinB BwrittenB BprogramsB BandB BredoB BitB BwithB BtheB BcurrentB BstateB BofB
B
theB Bprogram.B BIntegrateB BthisB BwithB BaB BbindingB BthatB BenumeratesB BasB
B
follows:
B
//B B→B B0
//B B→B B2
//B B…B Betcetera
AB BstatementB BthatB BbeginsB BwithB BtheB BkeywordB BandB BatB BtheB BsameB BtimeB
producingB BaB Bloop.B BTheB BkeywordB BwhileB BaccompaniedB BbyB BanB
B
expressionB BinB BparenthesesB BfollowedB BbyB BaB BstatementB BlikeB BtheB BifB
B
providesB BaB BvalueB BthatB BstatesB BtrueB BwhenB BtranslatedB BtoB BBoolean.B
B
EachB BtimeB BtheB BloopB Brepeats,B BnumbersB BadoptB BaB BnumberB BtwiceB BofB
B
theirB BpreviousB Bvalue.B BLetB BusB BwriteB BaB BprogramB BthatB BevaluatesB BandB
B
displayB BtheB BvalueB BofB B210B B(2B BraisedB BtoB BtheB BpowerB BofB B10th).B BWeB BwillB
B
utilizeB BtwoB Bbindings.B BOneB BtoB BkeepB BanB BeyeB BonB BourB BresultB BandB BtheB
B
otherB BtoB BcalculateB BhowB BmanyB BtimesB BtheB BvalueB BofB BtwoB BmultipliedB
B
byB BtheB Bresult.B BItB BmultipliesB BuntilB BtheB BsecondB BbindingB BreachesB B10:
B
letB ByourName;
doB B{
yourNameB B=B Bprompt("WhoB BareB Byou?");
}B BwhileB B(!B ByourName);
console.log(yourName);
BB
BB
for loops
BB
AB BlotB BofB BloopsB BfollowB BtheB BwhileB BloopB Bpattern,B BcreatingB BaB BcounterB
bindingB BtoB BtrackB BtheB Bloop'sB Bprogress.B BThenB BaB BwhileB BloopB BwithB BaB
B
testB BexpressionB BtoB BseeB BifB BtheB BcounterB BreachesB BtheB BsetB Bvalue.
B
forB B(letB BnumberB B=B B0;B BnumberB B<=B B10;B BnumberB B=B BnumberB B+B B4)B B{
console.log(number);
}
//B B→B B0
//B B→B B4
//B Betc
TheB BparenthesesB BmustB BconsistB BofB BtwoB BsemicolonsB BafterB BtheB
keyword,B BtheB BfirstB BpartB BthatB BisB BbeforeB BtheB BfirstB BsemicolonB
B
separatesB BtheB BloopB BbyB BdescribingB BaB Bbinding.B BTheB BotherB BpartB BisB BtheB
B
statementB BthatB BdeterminesB BifB BtheB BloopB BshouldB Bcontinue.B BHereB BisB
B
theB BcodeB BthatB BevaluateB B210B BusingB BforB BinsteadB BofB Bwhile:
B
confinedB Bloop.B BTheB BbreakB BstatementB BevaluatesB BthisB BprogramB BifB BtheB
B
firstB Bnumber,B BwhichB BisB BbothB BgreaterB BthanB BorB BequalB BtoB B20,B BandB BcanB
B
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;
}
}
isB Bzero.B BTheB BforB BinB BtheB BexampleB BisB BnotB BcheckedB BatB BtheB BendB BofB
B
theB Bloop,B BwhichB BmeansB BuntilB BtheB BbreakB BstatementB BinsideB BisB
B
order.
B
ForB BcounterB B+=B B1B BandB BcounterB B-=B B1,B BhereB BareB BshorterB Bequivalents:
counter++B BandB Bcounter--.
DispatchingB BonB BaB BvalueB BwithB Bswitch
DispatchingB BonB BaB BvalueB BwithB BswitchB BCodesB BcanB BlookB BlikeB Bthis:
ifB B(xB B==B B"value1")B Baction1();
elseB BifB B(xB B==B B"value2")B Baction2();
elseB BifB B(xB B==B B"value3")B Baction3();
elseB BdefaultAction();
TheB BswitchB BisB BusedB BtoB BexpressB BtheB BaboveB BformB BofB BdispatchB
straightforwardly.B BBelowB BisB BaB BgoodB Bexample:
B
caseB B"sunny":
console.log("BeB BlightB BwithB ByourB Bdressing.");
caseB B"cloudy":
console.log("MoveB Bout.");
break;
default:
NamesB BbindingB BdoB BnotB BallowB Bspaces,B BbutB BitB BsupportsB BtheB BusageB BofB
severalB BwordsB BtoB BdefineB BtheB BbindingB Bvalues.B BHereB BareB BaB BfewB BtypesB
B
thatB BcanB BbeB ButilizedB BwhenB BbindingB BnamesB BwithB BdifferentB Bwords:
B
fuzzylittleturtle
fuzzy_little_turtle
FuzzyLittleTurtle
fuzzyLittleTurtle
Comments
SometimesB BrawB BcodesB BdoB BnotB BtransmitB BeveryB BsingleB BpieceB BofB
informationB BthatB ByouB BwantB BtheB BprogramB BtoB BsendB BtoB BreadersB BorB
B
spreadsB BtheB BmessageB BinB BaB BwayB BpeopleB BwillB BfindB BitB BhardB BtoB
B
decipher.B BOtherB BtimesB ByouB BfeelB BlikeB ByouB BshouldB BattachB BsomeB
B
function.B BAB BcommentB BisB BaB BbitB BchunkB BofB BtheB BtextB BcontainedB BinB BaB
B
program,B BbutB BtheB BcomputerB BignoresB Bit.B BToB BcodeB BaB BsingleB BlineB
B
comment,B BuseB BtheB BtwoB BslashB BcharactersB B(//),B BfollowedB BbyB BtheB
B
commentB Btext.
B
addToReport(accountBalance,B Breport);
B
//B BIt'sB BaB BlargeB Bhallway,B BandB BtheB BlightsB BareB BquiteB Bamazing.
AB B//B BcommentB BappearsB BonlyB BatB BtheB BendB BofB BtheB Bline.B BAnyB BtextB
withinB B/*B BandB B*/B BignoreB Bit,B BandB BitB BdoesB BnotB BmatterB BifB BitB BcontainsB
B
lineB Bbreaks.B BItB BisB BusedB BtoB BattachB BblocksB BofB BinformationB BaboutB BaB
B
Summary
NowB ByouB BunderstandB BthatB ByouB BcanB BdevelopB BaB BprogramB BthroughB BtheB
useB BofB Bstatements,B BwhichB BstatementB BitselfB BcanB BcontainB BseveralB
B
eachB BanotherB BprovidesB BanB BexecutedB BprogramB BfromB BtopB BtoB Bbottom.B
B
DisturbancesB BcanB BalsoB BcomeB BintoB BtheB BflowB BofB BinfluenceB BthroughB
B
conditionalB B(if,B Belse,B BandB Bswitch)B BandB BloopingB B(while,B Bdo,B BandB Bfor)B
B
statements.B BAndB BweB BtouchedB Bbindings,B BtheyB BcategorizeB BbitsB BofB BdataB
B
underB BaB Bname,B BandB BtheyB BcanB BalsoB BtrackB BstateB BwithinB BtheB Bprogram.B
B
summarizeB BaB BpieceB BofB Bprogram.B BYouB BcanB BcallB BthemB BbyB BtypingB
B
Exercise
WriteB BaB BJavaScriptB BprogramB BthatB BdisplaysB BtheB BlargerB BandB BacceptsB
doubleB Bintegers.
B
Solution
ItB BisB BimportantB BtoB BknowB BthatB ByouB BcanB BwriteB B.lengthB BatB BtheB BendB BofB
aB BstringB BtoB BfindB BitsB Blength.
B
//B B→B B3
Chapter 4: FunctionsBB BB
returnB Bresult;
};
console.log(power(2,B B10));
//B B→B B1024
SomeB BfunctionsB BcanB BcreateB BvaluesB BsuchB BasB BsquareB BandB BpowerB BwhileB
BsomeB BresultsB BonlyB BintoB BaB BsideB Beffect.B BAB BreturnB BkeywordB BthatB BdoesB
BnotB BcontainB BanB BexpressionB BatB BtheB BendB BwillB BbeB BreturnedB BasB
Bundefined.
Bindings and scopes
BB BB
EveryB BbindingB BconsistsB BofB BaB BscopeB BthatB BenablesB BtheB BvisibilityB BofB
BtheB Bbinding.B BWheneverB ByouB BcallB BaB Bfunction,B BnewB BillustrationsB BofB
BbindingB BareB Bdeveloped.B BThisB BcreatesB BseparationB BbetweenB Bfunctions,B
BeveryB BfunctionB BcallB BbehavesB BinB BitsB BownB BworldB BandB BisB BeasyB BtoB
Bunderstand.B BFunctionsB BthatB BwereB BdeclaredB BwithB BtheB BvarB BkeywordB
BinB BtheB Bpre-2015B BJavaScriptB BandB BcanB BbeB BseenB BthroughoutB BtheB BglobalB
Bscope.B BTheyB BareB BabsentB BinB BaB Bfunction.
letB BxB B=B B10;
ifB B(true)B B{
letB ByB B=B B20;
varB BzB B=B B30;
console.log(xB B+B ByB B+B Bz);
//B B→B B60
}
TheB BcodeB BwithinB BtheB BcomponentB BfunctionB BcanB BaccessB BtheB BfactorB
BbindingB BfromB BtheB BouterB Bfunction.B BTheB BsetB BofB BbindingsB BaccessibleB
BwithinB BaB BblockB BisB BdecidedB BbyB BtheB BblockB BpositionB BinB BtheB BprogramB
Btext.B BEveryB BlocalB BscopeB BcanB BaccessB BtheB BcontainedB BlocalB BscopeB BandB
BeveryB BscopeB BcanB BasB BwellB BaccessB BtheB BglobalB Bscope.B BThisB BconceptB BisB
BnamedB BlexicalB Bscoping.
FunctionsB BasB Bvalues
AB BfunctionB BbindingB BoftenB BbehavesB BasB BaB BnameB BforB BaB BparticularB
BblockB BofB Bprogram.B BThisB BtypeB BofB BbindingB BdoesB BnotB BchangeB BbecauseB
BitB BisB Bdefined.B BFunctionsB BcanB BbeB BusedB BinB BarbitraryB BexpressionsB BasB
BwellB BasB BusedB BtoB BsaveB BaB BfunctionB BvalueB BintoB BaB BnewB Bbinding.B BAB
BbindingB BthatB BstoresB BaB BfunctionB BisB BaB BsystematicB BbindingB BandB BaB BnewB
BvalueB BcanB BbeB BassignedB Blike:
letB BlaunchMissilesB B=B Bfunction()B B{
missileSystem.launch("now");
};
ifB B(safeMode)B B{
launchMissilesB B=B Bfunction()B B{/*B BdoB BnothingB B*/};
}
DeclarationB Bnotation
ThereB BisB BaB BlittleB BwayB BtoB BgenerateB BaB BfunctionB Bbinding.B BWhenB ByouB
BuseB BtheB BfunctionB BkeywordB BatB BtheB BbeginningB BofB BaB Bstatement,B BitB BwillB
BfunctionB Bdifferently.
functionB Bsquare(x)B B{
returnB BxB B*B Bx;
}
ThisB BstatementB BdescribesB BtheB BbindingB BsquareB BandB BdirectsB BitB BatB BaB
BstatedB Bfunction.B BThisB BtypeB BofB BfunctionB BdefinitionB BconsistsB BofB BoneB
Bprecision.
console.log("MyB BmindB BtellsB BmeB BeveryB Btime:",B Bfuture());
functionB Bfuture()B B{
returnB B"IllB BsurpassB BBillB BGates";
}
ArrowB Bfunctions
FunctionsB BcontainsB BaB BthirdB BnotationB BthatB BdoesB BnotB BlookB BidenticalB
BtoB BtheB Bothers.B BYouB BcanB BuseB BtheB BarrowB B(=>)B BasB BanB BalternativeB BtoB
BtheB BfunctionB Bkeyword.B BTheB BarrowB B(=>)B BcontainsB BanB BequalB BsignB BandB
BtheB BgreaterB BthanB Bcharacter.
constB BpowerB B=B B(base,B Bexponent)B B=>B B{
letB BresultB B=B B1;
forB B(letB BcountB B=B B0;B BcountB B<B Bexponent;B Bcount++)B B{
resultB B*=B Bbase;
}
returnB Bresult;
};
IfB ByouB BhaveB BjustB BoneB BparameterB Bname,B BexcludeB BtheB BparenthesesB
BsurroundingB BtheB BparameterB Blist.B BSometimesB BtheB BbodyB BisB BaB BsingleB
BexpressionB BinsteadB BofB BaB BblockB BofB Bbraces,B BtakingB BbackB BtheB
BexpressionB BfromB BtheB Bfunction.B BTherefore,B BsquareB BdefinitionsB
BperformB BtheB BsameB Btask.
constB Bsquare1B B=B B(x)B B=>B B{returnB BxB B*B Bx;};
constB Bsquare2B B=B BxB B=>B BxB B*B Bx;
WhenB BthereB BisB BnoB BparameterB BonB BanB BarrowB Bfunction,B BitsB BparameterB
BlistB BbecomesB BaB BsetB BofB BunoccupiedB BandB BineffectiveB Bparentheses.
constB BhornB B=B B()B B=>B B{
console.log("Toot");
};
YouB Bdon’tB BhaveB BtoB BuseB BbothB BtheB BfunctionB BexpressionsB BandB BarrowB
BfunctionsB BinB BtheB Blanguage,B BtheyB BofferB BandB BperformB BtheB BsameB
Boperations.
TheB BcallB Bstacks
LetB BusB BtakeB BsomeB BtimeB BtoB BseeB BhowB BcontrolB BgoesB BthroughB
Bfunctions.B BBelowB BisB BaB BsimpleB BprogramB BmakingB BfewB BfunctionB Bcalls:
functionB Bgreet(who)B B{
console.log("HelloB B"B B+B Bwho);
}
greet("Harry");
console.log("Bye");
TheB BgreetingsB BcallB BinfluencesB BtoB BcontrolB BtoB BjumpB BtoB BtheB BbeginningB
BofB BtheB Bfunction.B BTheB BfunctionB BcallB Bconsole.logB BgetsB BitsB BjobB BdoneB
BandB BseizeB Bcontrol,B BandB BthenB BsendB BcontrolB BbackB BtoB BtheB Bfunction.B
BTheB BfunctionB BcycleB BendsB BthereB BandB BtransfersB BbackB BtoB BtheB BplaceB
BthatB BcallsB Bit.B BTheB BflowB BofB BcontrolB BisB Bbelow:
notB BinB Bfunction
inB Bgreet
inB Bconsole.log
inB Bgreet
notB BinB Bfunction
inB Bconsole.log
notB BinB Bfunction
TheB BcomputerB BhasB BtoB BrecollectB BtheB BcontextB BinB BwhichB BtheB BcallB
sequencesB BoccurredB BbecauseB BfunctionsB BgoB BbackB BtoB BwhereB Bit'sB BcalledB
B
position.B BWhenB BConsole.logB Bcompletes,B BitB BmustB BreturnB BtoB BtheB BendB
B
ofB BtheB Bprogram.B BAB BcallB BstackB BisB BaB BplaceB BwhereB BtheB BcomputerB
B
storesB BthisB Bcontext.B BWheneverB ByouB BcallB BaB Bfunction,B BtheB BpresentB
B
contextB BsavesB BatB BtheB BtopB BofB BthisB Bstack.B BByB BtheB BtimeB BaB BfunctionB
B
goesB Bback,B BitB BeradicatesB BtheB BtopB BcontextB BandB ButilizesB BtheB BcontentB
B
TheB BstackB BneedsB BspaceB BtoB BbeB BsavedB BintoB BwithinB BtheB BcomputerB
memory.B BTheB BbelowB BcodeB BexplainsB BthisB BbyB BqueryingB BtheB BcomputerB
B
thatB BcreatesB BzeroB BlimitationB BbetweenB BtwoB BfunctionsB BbackB BandB Bforth.
B
functionB Bchicken()B B{
returnB Begg();
}
functionB Begg()B B{
returnB Bchicken();
}
theB BfirstB Bone.B BJavaScriptB BisB BveryB BtolerantB BaboutB BtheB BamountB BofB
B
argumentsB BbeingB BpassedB BtoB BaB Bfunction.B BTheB BgoodB BsideB BofB BthisB
B
argument.B BIfB ByouB BwantB BtoB BpassB BandB BnotB BproduceB BtheB BsecondB
B
argument,B BtheB BdefaultB BbecomesB BtwoB BandB BtheB BfunctionB BactsB BlikeB BaB
B
square.
B
returnB Bresult;
}
console.log(power(4));
TheB BcapabilityB BtoB BuseB BfunctionsB BasB BvaluesB BisB BcoupledB BwithB BtheB BfactB
thatB BlocalB BbindingsB BareB BcreatedB BagainB BwheneverB ByouB BcallB BaB
B
function.B BTheB BbelowB BcodeB BdisplaysB BthisB Bexample;B BitB BdescribesB BaB
B
wrapB Bvalue,B BaB BfunctionB BthatB BdevelopsB BaB BlocalB BbindingB BandB BthenB
B
sendsB BbackB BaB BfunctionB BthatB BentersB BandB BreturnsB BtheB BlocalB Bbinding.
B
functionB BwrapValue(n)B B{
letB BlocalB B=B Bn;
returnB B()B B=>B Blocal;
}
//B B→B B1
console.log(wrap2());
//B B→B B2
ThisB BconceptB BisB BcalledB Bclosure.B BItB BgivesB BtheB BuserB BtheB BabilityB BtoB
referenceB BaB BparticularB BinstanceB BofB BaB BlocalB BbindingB BwithinB BaB
B
confiningB Bscope.B BAddingB BaB BfewB Bchanges,B BourB BpreviousB BexampleB BcanB
B
turnB BintoB BaB BwayB BtoB BdevelopB BfunctionsB BthatB BaccumulatesB BbyB BanB
B
arbitraryB Bamount.
B
functionB Bmultiplier(factor)B B{
returnB BnumberB B=>B BnumberB B*B Bfactor;
}
AB BfunctionB BcanB BcallB BitselfB BbutB BshouldB BnotB BcallB BitselfB BregularlyB BtoB
avoidB BstackB Boverflow.B BRecursiveB BfunctionB BisB BaB BfunctionB BthatB BcallsB
B
ForB Binstance,B BtheB BbelowB BcodeB BisB BtheB BexecutionB BofB Bpower.
B
console.log(power(2,B B3));
//B B→B B8
ThereB BisB BoneB BproblemB BwithB BthisB Bexecution.B BItB BisB BslowerB BcomparedB
toB BotherB BloopingB Bversions.B BUtilizingB BaB BsingleB BloopB BisB BconsideredB
B
lowB BcostB BthanB BtheB BmultipleB BcallingB BofB Bfunctions.B BAlthoughB BthatB
B
doesB BnotB BmakeB BrecursionB BanB BineffectiveB BoptionB BofB Blooping,B BfewB
B
problemsB BareB BsolvedB BwithB BrecursionB BeasierB BthanB BwithB BtheB BuseB BofB
B
branches.B BCheckB BthisB Bout:B BweB BbeginB BfromB BnumberB B1B BandB
B
continuouslyB BaddB B5B BorB BmultiplyB BbyB B3.B BForB Binstance,B BtheB BnumberB
B
13B BcanB BbeB BobtainedB BbyB BmultiplyingB BbyB B3B BandB BtheB BadditionB BofB B5B
B
twice,B BtherebyB BweB BcannotB BattainB BtheB B15.B BTheB BcodeB BisB BtheB BrecursiveB
B
solution:
B
functionB BfindSolution(target)B B{
functionB Bfind(current,B Bhistory)B B{
ifB B(currentB B==B Btarget)B B{
returnB Bhistory;
}B BelseB BifB B(currentB B>B Btarget)B B{
returnB Bnull;
}B BelseB B{
returnB Bfind(currentB B+B B5,B B`(${history}B B+B B5)`)B B||
find(currentB B*B B3,B B`(${history}B B*B B3)`);
}
}
number.B BIfB BaB BsolutionB BisB Bfound,B BitB BsendsB BbackB BaB BstringB BthatB
B
displaysB BtheB BrouteB BtoB BtheB BtargetB BandB BifB BnoB BsolutionB BisB Bfound,B BtheB
B
returnedB BvalueB BwillB BbeB Bnull.B BToB BachieveB Bthis,B BtheB BfunctionB
B
executesB BoneB BofB BthreeB Bactions.B BIfB ByourB BtargetB BisB BtheB BisB BtheB
B
currentB Bnumber,B ByouB BcanB BattainB BthatB BtargetB BbyB BusingB BtheB BcurrentB
B
historyB BsoB BitB BisB BsentB Bback.B BSometimesB BtheB BnumberB BisB BlargerB BthanB
B
theB Btarget,B BbutB ByouB BdoB BnotB BneedB BtoB BexploreB BthisB BoptionB BbecauseB
B
additionB BandB BsubtractionB BcanB BonlyB BenlargeB BtheB BnumberB BsoB BitB BisB
B
sentB BbackB BasB Bnull.B BIfB ByouB BremainB BbeneathB BtheB BtargetB Bnumber,B
B
bothB BpathsB BthatB BbeginB BtheB BcurrentB BnumberB BisB BtriedB BbyB BcallingB
B
itselfB Btwice,B BoneB BtoB BaddB BandB BtheB BotherB BtoB Bmultiply.B BIfB BtheB BfirstB
B
callB BsendsB BsomethingB BvalidB BbackB BinB Breturn,B BthenB Bgood,B BifB Bnot,B
B
returnB BtheB BsecondB Bcall,B BitB BdoesB BnotB BmatterB BwhetherB BaB BstringB BorB
B
nullB BisB Bprovided.B BBelowB BisB BanB BillustrationB BofB BhowB BfunctionsB
B
provideB Beffects.B BThisB BexampleB BsearchesB BforB BaB BremedyB BforB BtheB
B
numberB B13.
B
find(1,B B"1")
find(6,B B"(1B B+B B5)")
find(11,B B"((1B B+B B5)B B+B B5)")
find(16,B B"(((1B B+B B5)B B+B B5)B B+B B5)")
tooB Bbig
find(33,B B"(((1B B+B B5)B B+B B5)B B*B B3)")
tooB Bbig
find(18,B B"((1B B+B B5)B B*B B3)")
tooB Bbig
find(3,B B"(1B B*B B3)")
find(8,B B"((1B B*B B3)B B+B B5)")
find(13,B B"(((1B B*B B3)B B+B B5)B B+B B5)")
found!
FunctionsB BcanB BbeB BintroducedB BintoB BprogramsB BinB BtwoB Bways.B BTheB BfirstB
isB BbyB BwritingB BsimilarB BcodesB BaB BlotB BofB Btimes,B BwhichB BenablesB BmoreB
B
mistakesB BwhileB BtheB BsecondB BisB BtoB BsearchB BforB BaB BfewB BfunctionalitiesB
B
thatB BhaveB BnotB BbeenB BwrittenB BandB BdeservesB BitsB BownB Bfunction.B BYouB
B
canB BbeginB BbyB BnamingB BtheB BfunctionB BandB BwriteB BtheB Bbody.B BBelowB BisB
B
anB Bexample.B BWeB BwillB BwriteB BaB BprogramB BthatB BreproduceB BtwoB
B
numbers–theB BamountB BofB BchickenB BandB BcowsB BavailableB BonB BaB Bfarm.
B
007B BCows
011B BChickens
functionB BprintFarmInventory(cows,B Bchickens)B B{
letB BcowStringB B=B BString(cows);
whileB B(cowString.lengthB B<B B3)B B{
cowStringB B=B B"0"B B+B BcowString;
}
console.log(`${cowString}B BCows`);
letB BchickenStringB B=B BString(chickens);
whileB B(chickenString.lengthB B<B B3)B B{
chickenStringB B=B B"0"B B+B BchickenString;
}
console.log(`${chickenString}B BChickens`);
}
printFarmInventory(7,B B11);
WritingB BlengthB BafterB BaB BstringB BexpressionB BdeterminesB BtheB BlengthB BofB
theB BparticularB Bstring.B BTheB BloopB BcontinuesB BtoB BaddB BzerosB BatB BtheB
B
beginningB BofB BtheB BnumberB BstringsB BuntilB BtheyB BcompriseB BofB BthreeB
B
characters.
B
console.log(`${numberString}B B${label}`);
}
returnB Bstring;
}
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);
};
setB BinB BaB BspecificB BscopeB BareB BlocalB BandB BinvisibleB BfromB BtheB Boutside.B
B
BindingsB BsetB BwithB BvarB BactB Bdifferently,B BandB BtheyB BresultB BinB BtheB
B
intoB BvariousB BfunctionsB BisB Bimportant.B BYouB BdoB BnotB BneedB BtoB BrepeatB
B
Exercise
WriteB BaB BJavaScriptB BprogramB BtoB BseeB BifB BaB BnumberB BisB BevenB BorB Bnot.
Solution
BB
Chapter 5: Data Structures:
BB BB BB B
chunk.B BObjectsB BenableB BtheB BuserB BtoB BcollateB BvaluesB BtogetherB BwithB
B
otherB BobjectsB BtoB BdevelopB BmoreB BcompoundB Blayouts.B BInB BthisB Bchapter,B
B
youB BwillB BunderstandB BtheB BconceptsB BofB BsolvingB BaB BrealB BproblemB BatB
B
hand.
B
DataB Bsets
IfB ByouB BwantB BtoB BworkB BwithB BaB BlotB BofB BdigitalB Bdata,B ByouB BmustB
representB BtheB BdigitalB BdataB BinB BtheB BmachineB Bmemory.B BForB Binstance,B
B
youB BneedB BtoB BrepresentB BaB BgroupB BofB BnumbersB BlikeB B2,B B3,B B5,B B7,B BandB
B
11.B BNowB Blet’sB BgetB BprolificB BwithB BourB BuseB BofB BstringsB BasB BstringsB BcanB
B
containB BquiteB BaB BlotB BofB Bdata.B BWeB BwillB BuseB B2B B3B B5B B7B B11B BasB BtheB
B
dataB BtypeB BforB BsavingB BsequencesB BofB Bvalues,B BwhichB BisB BcalledB BanB
B
array.B BWriteB BanB BarrayB BasB BaB BlistB BofB BvaluesB BwithinB BtheB BbetweenB
B
//B B→B B5
console.log(listOfNumbers[0]);
//B B→B B2
console.log(listOfNumbers[2B B-B B1]);
//B B→B B3
TheB BnotationB BusedB BtoB BgetB BelementsB BwithinB BanB BarrayB BalsoB ButilizeB
theB BsquareB Bbrackets.B BAB BcompleteB BsquareB BbracketsB BpairB BrightB BafterB
B
startB BcountingB BelementsB BinB BanB Barray,B ByouB BbeginB BfromB BzeroB BandB
B
listOfNumbers[0].
B
Properties
containB Bproperties.B BTheB BfewB BvaluesB BthatB BdoB BnotB BcontainB BpropertiesB
B
areB BnullB BandB Bundefined.B BIfB ByouB BaccessB BaB BpropertyB BwithB BaB
B
null.length;
theB BpropertyB BonB Bvalue,B BnotB BparticularlyB BtheB BsameB Bproperty.B BHowB
B
youB BuseB BxB BisB BdifferentB BfromB BhowB ByouB BuseB BaB Bdot.
B
IfB ByouB BwantB BtoB BuseB BtheB Bdot,B BtheB BtextB ByouB BinputB BafterB BtheB BdotB BisB
theB BnameB BofB BtheB Bproperty.B BAndB BifB Byou'reB BgoingB BtoB BuseB BtheB BsquareB
B
redeemB BtheB BpropertyB Bname.B BValue.xB BdeliversB BtheB BpropertyB BofB BvalueB
B
calledB B“x,”B BwhileB Bvalue[x]B BaccessesB BtheB BexpressionB BxB BandB ButilizeB
B
theB Bresult,B BtransformedB BintoB BaB BstringB BasB BtheB BnameB BofB BtheB
B
property.B BIfB BtheB BpropertyB ByouB BwantB BisB BnamedB Bcolor,B ByouB BshouldB
B
typeB Bvalue.color.B BYouB BcanB BwithdrawB BtheB BpropertyB BthatB BtheB BvalueB
B
calledB BwithinB BtheB BbindingB Bi,B BtypeB Bvalue[i].B BTheB BnameB BofB BpropertiesB
B
areB Bstrings,B BbutB BtheB BdotB BnotationB BperformsB BwithB BonlyB BvalidB
B
bindingB Bnames.B BThereforeB BifB ByouB BwantB BtoB BevaluateB BaB BpropertyB
B
namedB B2B BorB BJohnB BDoe,B BuseB BtheB BsquareB Bbrackets:B Bvalue[2]B BorB
B
value["JohnB BDoe"].
B
TheB BelementsB BwithinB BanB BarrayB BsaveB BasB BtheB BpropertiesB BofB BanB BarrayB
thatB ButilizeB BnumbersB BasB BpropertyB Bnames.B BAnB Barray'sB BlengthB
B
propertyB BdeterminesB BhowB BmanyB BitemsB BitB Bcontains.B BTheB BnameB BofB
B
thatB BpropertyB BisB BaB Bvalid,B BbindingB Bname.B BTypeB Barray.lengthB BtoB
B
determineB BtheB BlengthB BofB BanB Barray,B BitB BisB BmuchB BeasierB BtoB BtypeB BthanB
B
theB Barray["length"].
B
Methods
containingB
B BlettersB transformB
B BintoB Buppercase.B BAlthoughB BtheB
toUpperCaseB BdoB BnotB BgoB BthroughB BanB Bargument,B BtheB BfunctionB BcanB
B
evaluateB BtheB BstringB B"Doh,"B BwhichB BisB BtheB BpropertyB BofB BtheB BvalueB BweB
B
calledB Babove.B BPropertiesB BthatB BconsistB BofB BfunctionsB BareB BknownB BasB
B
methods.B BTheB BbelowB BexampleB BillustratesB BtwoB BmethodsB BthatB BcanB BbeB
B
//B B→B B5
console.log(sequence);
eradicatesB BtheB BlastB BvalueB BwithinB BanB BarrayB BandB BsendsB BitB Bback.B
B
TheseB BareB BgenerationalB BtermsB BofB BoperationsB BonB BaB Bstack.B BAB BstackB BisB
B
aB BdataB BlayoutB BthatB BenablesB BusersB BtoB BpushB BvaluesB BinB BandB BpopB BthemB
B
outB BinB BtheB BoppositeB BdirectionB BsoB BthatB BtheB BaddedB BvalueB BwillB
B
removeB Bfirst.
B
Objects
YouB BcanB BrepresentB BaB BgroupB BofB BlogB BentriesB BasB BanB BarrayB BalthoughB
eachB BstringB BentryB BisB BrequiredB BtoB BsaveB BaB BlistB BofB BactivitiesB BasB BwellB
B
asB BaB BBooleanB BvalueB BthatB BspecifiesB BifB BJacquesB BtransformedB BtoB BaB
B
BsquirrelB BorB Bnot.B BWeB BwillB BgroupB BthisB BintoB BaB BsingleB BvalueB BandB BplaceB
BtheB BgroupedB BvaluesB BwithinB BanB BarrayB BofB BlogB Bentries.B BArbitraryB
collectionsB BofB BpropertiesB BareB BtheB BvalueB BofB BtheB BtypeB Bobject.B BWeB BwillB
B
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);
propertyB BtoB BundefinedB BandB BdeletingB BitB BisB BthatB BtheB BobjectB BconsistsB
B
ofB BaB BpropertyB BandB BtheB BdeletingB BdoesB BnotB BpossessB BtheB Bproperty,B BsoB
B
containedB BinB BanB BobjectB BandB BsendsB BbackB BanB BarrayB BofB BstringsB BwithB
B
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
areB BidenticalB BbyB Bnature.B BTheB BbindingB Bobject3B BpointsB BtoB BaB BseparateB
B
objectB BthatB BconsistsB BofB BsimilarB BpropertiesB BasB BtheB Bobject1B BbutB BhasB BaB
B
differentB Blife.B BBindingsB BcanB BbeB BconstantB BorB Bchangeable,B BbutB BitB BdoesB
B
notB BinfluenceB BtheirB Bvalues.B BAB BconstB BbindingB BanB BobjectB BcannotB BbeB
B
transformedB BandB BrelentlesslyB BpointingB BtoB BtheB BsameB Bobject.B BItB BisB
B
InsteadB BofB BproclaimingB BpropertiesB BsuchB BasB Bevents,B BitB BsetsB BaB
propertyB Bname.
B
SoB Bthen,B BatB B10B Bp.m.B BeveryB BeveningB BorB BoccasionallyB BinB BtheB
followingB Bmorning,B Bafter
B
gettingB BdownB BfromB BtheB BtopB BshelfB BofB ByourB Bbookcase,B ByourB BdailyB
records.
B
UnrelatedB BvariableB BisB BcalledB BaB BzeroB Bcorrelation.B BAB BcorrelationB BofB B1B
B
signifiesB BthatB BtheB BtwoB BareB Brelated.B BNegativeB BmeansB BthatB BtheB
B
variablesB BareB BrelatedB BperfectlyB BbutB BoppositesB BtoB BeachB Bother;B BoneB BisB
B
true,B BandB BtheB BotherB BisB Bfalse.B BToB BcalculateB BtheB BevaluationB BofB BtheB
B
(φ).B BThisB BformulaB BinputB BisB BaB BfrequencyB BtableB BholdingB BtheB BnumberB
B
ofB BtimesB BitB BnoticesB BseveralB BmixturesB BofB BtheB Bvariables.B BTheB
B
formula'sB BoutputB BwillB BbeB BaB BnumberB BbetweenB B-1B BandB B1.B BThatB BisB BtheB
B
LetB BusB BuseB BtheB BeventB BifB BeatingB BpizzaB BasB BanB BexampleB BandB BinsertB BitB
intoB BaB BfrequencyB BtableB BwherebyB BeveryB BnumberB BsignifiesB BtheB BtotalB
B
ofB Btimes,B BandB BweB BusedB BtheB BcombinationB BinB BourB Bmeasurements.B BWeB
B
nameB BtheB BtableB Bn,B BandB BweB BcalculateB BφB BwithB BtheB BbelowB Bformula:
B
φB B=
n11n00B B−B Bn10n01
√
n1•n0•n•1n•0
TheB 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
TheB BpizzaB Btable,B BtheB BtopB BofB BtheB BdivisionB BlineB BwouldB BbeB B1×76−4×9B B=B
40,B BandB BtheB BbelowB BpartB BbelowB BwouldB BbeB BtheB BsquareB BrootB BofB
B
5×85×10×80,B BorB B√340000.B BTheB BresultB BwillB BbeB BφB B≈B B0.069,B BwhichB BisB
B
ComputingB Bcorrelation
JavaScriptB BenablesB BtheB BrepresentationB BofB BaB Btwo-by-twoB BtableB BwithB
fourB BelementB BarraysB B([76,B B9,B B4,B B1]).B BOtherB BrepresentationsB BsuchB BasB
B
anB BarrayB BholdingB BtwoB Btwo-elementB B([[76,B B9],B B[4,B B1]])B BorB BanB BobjectB
B
containingB BpropertyB BnamesB BsuchB BasB B"11"B BandB B"01",B BandB BtheB BflatB
B
array,B BwhichB BproducesB BtheB BexpressionB BthatB BaccessB BtheB BchairB Bshort.B
B
WeB BwillB BexplainB BtheB BindicesB BtoB BtheB BarrayB BasB Btwo-bitB BbinaryB
B
numbers,B BwhereB BtheB BmostB BsignificantB BdigitB BrefersB BtoB BtheB BsquirrelB
B
variableB BwhileB BtheB BleastB BsignificantB BrefersB BtoB BtheB BeventB Btable.B BForB
B
instance,B BtheB BbinaryB BnumberB B10B BrefersB BtoB BtheB B"JacquesB BdidB BturnB
B
intoB BaB Bsquirrel"B BcaseB BbutB BtheB BeventsB Bdidn’tB Bappear.B BItB BoccurredB
B
fourB BtiesB BandB BbinaryB BisB B2B BinB Bdecimal,B BtheB BnumberB BisB BstoredB BasB BanB
B
indexB B2B BofB BtheB Barray.B BThisB BfunctionB BcalculatesB BtheB BφB BcoefficientB
B
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]));
}
ourB BdataB Blayout.B BIfB ByouB BwantB BtoB BextractB BaB Btwo-by-twoB BtableB BforB BaB
B
particularB Bevent,B ByouB BmustB BloopB BacrossB BallB BtheB BentriesB BandB
B
calculateB BtheB BnumberB BofB BtimesB BtheB BeventB BhappenedB BtoB BtheB BsquirrelB
B
transformations.
B
returnB Btable;
}
console.log(tableFor("pizza",B BJOURNAL));
//B B→B B[76,B B9,B B4,B B1]
ArraysB BconsistsB BofB BanB BincludeB Bmethod,B BwhichB BisB BusedB BtoB BcheckB BifB BaB
setB BvalueB BexistsB BinB BtheB Barray.B BThisB BmethodB BisB BusedB BbyB BtheB
B
functionB BtoB BdecideB BifB BtheB BeventB BnameB BisB BinterestedB BtheB BstatedB
B
Array loops
BB
WithB BaB BloopB BlikeB Bthis,B BtheB BloopB BcontinuesB BacrossB BtheB BelementsB BofB
theB BvalueB BspecifiedB BafterB Bof.B BThisB BloopB BisB BusedB BforB BstringsB BandB
B
ofB Bevent.
B
returnB Bevents;
}
console.log(journalEvents(JOURNAL));
event.
B
AB BlotB BofB BcorrelationsB BappearB BtoB BlieB BcloseB BtoB Bzero.B BEatingB Bbread,B
carrotsB BorB BpuddingB BdoesB BnotB BactivateB BtheB Bsquirrel-lycanthropy.B BItB
B
happensB BoftenB BduringB BtheB Bweekends.B BUsingB Bthat,B BbelowB BareB BallB BtheB
B
correlations.
B
therebyB BbrushingB BtheB BteethB BhasB BaB BnotableB BnegativeB Beffect.B BHere'sB
B
something:
B
TheB BaddingB BandB BremovingB BofB BmethodsB BthingsB BatB BtheB BbeginningB BofB
anB BarrayB BareB BcalledB BunshiftB BandB Bshift.
B
functionB BgetTask()B B{
returnB BtodoList.shift();
}
functionB BrememberUrgently(task)B B{
todoList.unshift(task);
}
TheB BaboveB BprogramB BorganizesB BaB BchainB BofB Btasks.B BYouB BcanB BaddB BtasksB
BtoB BtheB BendB BofB BtheB BqueueB BbyB BcallingB Bremember("groceries"),B BandB
whenB ByouB BwantB BtoB BgetB BsomethingB Bdone,B BcallB BgetTask()B BtoB BgetB B(andB
B
remove)B BitemB BfromB BtheB Bqueue.B BIfB ByouB BwantB BtoB BsearchB BforB BaB
B
findsB BitsB BwayB BthroughB BtheB BarrayB BfromB BtheB BbeginningB BtoB BtheB BendB
B
andB BsendsB BbackB BtheB BindexB BtheB BvalueB Brequested,B BifB BitB BwasB BfoundB BitB
B
returnsB B—orB B-1B BifB BitB Bwasn’tB Bfound.B BToB BsearchB BfromB BtheB BbeginningB
B
slice,B BthisB BmethodB BbeginsB BandB BendsB BtheB BindicesB BandB BsendB BbackB BanB
B
stick.
B
//B B→B B5
AB Bstring’sB BindexOfB BcanB BlookB BforB BaB BstringB BholdingB BmoreB BthanB BoneB
character,B BwhileB BtheB BcorrespondingB BarrayB BmethodB BsearchB BforB BaB
B
singleB Belement.
B
console.log("oneB BtwoB Bthree".indexOf("ee"));
//B B→B B11
TheB BtrimB BmethodB BeradicatesB BwhitespaceB BfromB BtheB BbeginningB BtoB BtheB
endB BofB BaB Bstring.
B
console.log(String(6).padStart(3,B B"0"));
//B B→B B006
YouB BcanB BbreakB BaB BstringB BonB BeveryB BdevelopmentB BofB BanotherB BstringB
withB BsplitB BandB BthenB BjoinB BthemB BtogetherB BwithB Bjoin.
B
console.log("LA".repeat(3));
//B B→B B3
console.log(string[1]);
//B B→B Bb
RestB Bparameters
ItB BisB BimportantB BforB BaB BfunctionB BtoB BreceiveB BanyB BnumberB BofB
arguments.B BIfB ByouB BwantB BtoB BwriteB BsuchB BaB Bfunction,B BaddB BthreeB BdotsB
B
returnB Bresult;
}
theB BthreeB BdotB BnotationB BtoB BcallB BfunctionsB BwithinB BanB BarrayB BofB
B
arguments.
B
//B B→B B7
SpreadB BtheB BarrayB BoutB BintoB BaB BfunctionB Bcall,B BpassB BtheB BelementB
differentB Barguments,B BlikeB BmaxB B(9,B B...numbers,B B2).B BTheB BSquareB
B
bracketB BarrayB BnotationB BenablesB BtheB Btriple-dotB BoperatorB BbringB
B
functionsB BandB BfunctionsB BwithoutB BglobalB Bbindings.B BThisB BisB BtheB BoldB
B
wayB BtoB BwriteB BtheB BconstantB BvalueB BnameB BinB BallB Bcaps.
B
functionB BrandomPointOnCircle(radius)B B{
letB BangleB B=B BMath.random()B B*B B2B B*B BMath.PI;
returnB B{x:B BradiusB B*B BMath.cos(angle),
y:B BradiusB B*B BMath.sin(angle)};
}
console.log(randomPointOnCircle(2));
console.log(Math.random());
Math.random.
B
Math.floorB BroundsB Bdown,B BtheB BoutputB BwillB BbeB BanyB BnumberB BfromB B0B
B
throughB B9.B BTheB BmathB BobjectB BcontainsB BseveralB BfunctionsB BlikeB BtheB
B
Math.ceil,B BwhichB BroundsB BupB BtoB BaB BwholeB Bnumber,B BandB BtheB
B
Math.round,B BwhichB BroundsB BupB BtoB BtheB BnearestB BwholeB Bnumber,B BandB
B
Math.abs,B BthisB BfunctionB BtakesB BtheB BentireB BvalueB BofB BaB Bnumber.
B
Destructuring
OneB BofB BtheB BfewB BreasonsB BthisB BfunctionB BisB BhardB BtoB BreadB BisB BbecauseB
thereB BisB BaB BbindingB BdirectedB BtoB BtheB Barray,B BbutB BweB BwantB BbindingsB
B
forB BtheB BelementsB BofB BtheB Barray,B BthatB Bis,B BletB Bn00B B=B Btable[0]B BandB BsoB
B
on.B BAlthough,B BthereB BisB BaB BbetterB BwayB BtoB BgetB BthisB BdoneB BinB
B
JavaScript.
B
array,B ButilizeB BtheB BsquareB BbracketsB BtoB BcheckB BforB BtheB BvalueB BofB BitsB
B
bindingB Bcontents.B BUseB BtheB BsameB BconceptB BforB Bobjects,B ButilizeB BtheB
B
JSONB BrepresentsB BJavaScriptB BObjectB BNotationB BandB BitB BisB ButilizedB BasB BaB
communicationB BformatB BandB BdataB BstorageB BforB BtheB Bweb.B BJSONB BisB
B
veryB BsimilarB BtoB BJavaScriptB BinB BitsB BwritingB BstyleB BofB BarraysB BandB
B
beB BenclosedB BwithinB BdoubleB Bquotes,B BitB BallowsB BonlyB BsimpleB BdataB
B
HereB BisB BaB BsampleB BofB BaB BjournalB BentryB BrepresentedB BasB BJSONB Bdata:
{
"squirrel":B Bfalse,
"events":B B["work",B B"touchedB Btree",B B"pizza",B B"running"]
}
JSON.parseB BtakesB BaB BstringB BandB BtransformsB BitB BtoB BitsB BencodedB Bvalue.
B
Summary
WeB BcoveredB BtheB BobjectsB BandB BarraysB BinB BthisB Bchapter,B BandB BtheyB
createB BwaysB BtoB BcategorizeB BvariousB BvaluesB BinB BaB BsingleB Bvalue.B
B
Fancifully,B BthisB BenablesB ByouB BtoB BinsertB BseveralB BassociatedB BitemsB BinB BaB
B
bagB BandB BmoveB BaboutB BwithB BtheB Bbag,B BratherB BthanB BenclosingB ByourB
B
armsB BaroundB BeveryB BsingularB BthingB BandB BtryingB BtoB BkeepB BthemB
B
differently.B BAB BlotB BofB BvaluesB BinB BJavaScriptB BcontainB Bproperties,B BtheB
B
usingB BtheB Bvalue.propB BorB Bvalue["prop"].B BYouB BcanB BuseB BnamesB BforB
B
objectsB BpropertiesB BandB BsaveB BaB BdefinedB BsetB BofB Bthem.B BArrays,B BasB
B
utilizeB BtheB BnumbersB B(beginningB BfromB B0)B BasB BtheB Bproperty’sB Bnames.B
B
ArraysB BcontainB BfewB BsetsB BofB Bproperties,B BwhichB BareB BtheB BlengthB BandB
B
propertiesB BandB BbehaveB BonB BtheB BvalueB BtheyB BareB BitsB Bproperty.B BYouB
B
canB BloopB BacrossB BarraysB BthroughB BaB BuniqueB BtypeB BofB BforB Bloop—forB
B
Exercise
WriteB BaB BJavaScriptB BfunctionB BtoB BobtainB BtheB BfirstB BitemB BinB BanB Barray.B
SettingB BaB BparameterB B'n'B BwillB BsendB BbackB BtheB BfirstB B'n'B BelementsB BofB
B
theB Barray.
B
Data:
B Functions
AB BlargeB BprogramB BtakesB BtimeB BtoB BdevelopB BandB BproducesB BaB BlotB BofB
spaceB BforB BbugsB BtoB Bhide,B BwhichB BinB BturnB BmakesB BthemB BhardB BtoB Bfind.B
B
TheB BfirstB BisB Bself-contained,B BandB BtheB BstatementB BisB BsixB BlinesB Blong.
letB BtotalB B=B B0,B BcountB B=B B1;
whileB B(countB B<=B B10)B B{
totalB B+=B Bcount;
countB B+=B B1;
}
console.log(total);
TheB BsecondB BdependsB BonB BtwoB BexternalB Bfunctions,B BandB BtheB BstatementB
isB BoneB BlineB Blong.
B
console.log(sum(range(1,B B10)));
Abstraction
givesB BtheB BuserB BtheB BcapabilityB BtoB BtalkB BaboutB BproblemsB BonB BaB BhigherB
B
level.B BLetB BusB BdifferentiateB BtwoB BrecipesB BforB BpeaB Bsoup.B BFirst:
B
PerB Bperson,B BplaceB B1B BcupB BofB BdriedB BpeasB BwithinB BaB Bcontainer.B BPutB
enoughB BwaterB BtoB BcoverB BtheB Bpeas,B BletB BitB BsoakB BforB BaboutB B12B Bhours.B
B
RemoveB BitB BfromB BtheB BwaterB BandB BplaceB BitB BinB BaB BpotB BusedB BforB
B
cookingB BwithB BtheB BadditionB BofB BwaterB BfourB BcupsB BofB BwaterB B(4B Bcups).B
B
LetB BitB BboilB BforB BaboutB BtwoB Bhours,B Bper-personB BholdB BhalfB BofB BanB
B
onion,B BsliceB BitB BusingB BaB Bknife,B BandB BpourB BitB BintoB BtheB Bpeas,B BletB BitB
B
DipB BtheB BpeasB BintoB BtheB BwaterB BforB BaboutB B12B Bhours.B BBoilB BitB BforB BaboutB
2B BhoursB BinB BwaterB B(4B Bcups),B BattachB BandB BsliceB Bvegetables.B BCookB BitB
B
TheB BcomputerB BperformsB BtasksB BoneB BbyB Bone,B BfromB BblindB BtoB Bhigh-
levelB Bconcepts.
AbstractingB Brepetition
PlainB BfunctionsB BareB BusedB BtoB BcreateB Babstractions.B BItB BisB BhabitualB BforB
aB BprogramB BtoB BrepeatB BaB BparticularB BfunctionB BaB BspecifiedB BamountB BofB
B
time.B ByouB BcanB BachieveB BthatB BwithB BaB BloopB BlikeB Bthis:
B
83
HereB BweB BwriteB BaB BfunctionB BthatB BcallsB Bconsole.logB BNB Btimes.
functionB BrepeatLog(n)B B{
forB B(letB BIB B=B B0;B BIB B<B Bn;B BI++)B B{
console.log(I);
}
}
IfB ByouB BwantB BtoB BperformB BaB BtaskB BdifferentB BfromB BloggingB BinB Bnumbers,B
youB BcanB BrollB BactionB BasB BaB BfunctionB Bvalue.
B
functionB Brepeat(n,B Baction)B B{
forB B(letB BIB B=B B0;B BIB B<B Bn;B BI++)B B{
action(i);
}
}
repeat(3,B Bconsole.log);
//B B→B B0
//B B→B B1
//B B→B B2
SometimesB ByouB BdoB BnotB BneedB BtoB BrollB BinB BaB BpredefinedB BfunctionB BtoB
BrepeatB BinB BaB Bloop,B BcreateB BaB BfunctionB BvalueB BasB BanB Balternative:
letB BlabelsB B=B B[];
repeat(5,B BiB B=>B B{
labels.push(`UnitB B${iB B+B B1}`);
});
console.log(labels);
//B B→B B["UnitB B1",B B"UnitB B2",B B"UnitB B3",B B"UnitB B4",B B"UnitB B5"]
ThisB BmethodB BlayoutB BlooksB BsimilarB BtoB BaB Bloop;B BitB BdefinesB BtheB BtypeB BofB
BloopB BandB BthenB BproduceB BaB Bbody.B BAlthoughB BtheB BbodyB BisB BwrittenB BinB
BfunctionB BenclosedB BinB BparenthesesB BofB BtheB BcallB BtoB Brepeat.
Higher-orderB Bfunctions
Higher-orderB BfunctionsB BareB BfunctionsB BthatB BworkB BonB BotherB BfunctionsB
BwhetherB BbyB BargumentsB BorB BbyB BsendingB BthemB Bback.B BThisB BtypeB BofB
BfunctionB BenablesB BuserB BtoB BabstractB BoverB Bactions.B BForB Binstance,B ByouB
BhaveB BaB BfunctionB BthatB BcanB BproduceB Bfunctions
functionB BgreaterThan(n)B B{
returnB BmB B=>B BmB B>B Bn;
}
returnB Bpassed;
}
TheB BmapB BmethodB BchangesB BanB BarrayB BbyB BsettingB BaB BfunctionB BtoB BeachB
andB BeveryB BofB BitsB BelementsB BandB BcreatingB BaB BnewB BarrayB BfromB BtheB
B
returnedB Bvalues.B BTheB BnewB BarrayB BconsistsB BofB BtheB BsameB BlengthB BwithB
B
theB BinputB BarrayB BbutB BwillB BmapB BoutB BitsB BcontentB BtoB BaB BrenewedB BforB
B
returnB Bmapped;
}
combinationB BandB BbeginB BaB Bvalue.B BThisB BfunctionB BisB BmuchB BeasierB BtoB
B
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);
}
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);
theB BaverageB ByearB BforB BlivingB BandB BdeadB BinB Bhumans’B BscriptsB BinB BtheB
B
dataB Bset.
B
functionB Baverage(array)B B{
returnB Barray.reduce((a,B Bb)B B=>B BaB B+B Bb)B B/B Barray.length;
}
console.log(Math.round(average(
Let’sB BbeginB BwithB BtheB BentireB Bscript,B BfilterB BoutB BtheB BdeadB B(orB Bliving),B
eradicateB BtheirB Byears,B BaverageB BthemB BandB BcompleteB BtheB Bresult.B BYouB
B
canB BasB BwellB BwriteB BtheseB BcalculationsB BasB BaB BbigB Bloop:
B
numbersB Bonly.
B
OneB BofB BtheB BsignificantB BuseB BofB BdataB BsetB BisB BtoB BfindB BoutB BwhatB BscriptB
aB BblockB BofB BtextB BisB Busing.B BBelowB BisB BaB BprogramB BthatB BperformsB BthatB
B
task.
B
EveryB BscriptB BcontainsB BanB BarrayB BofB BcharacterB BcodeB BrangesB BrelatedB
withB Bit.B BSo,B BifB ByouB BareB BgivenB BaB BcharacterB Bcode,B ButilizeB BthisB
B
functionB 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 B4
console.log(horseShoe[0]);
theB BargumentB BsentB BtoB BcodePointAtB BremainsB BanB BindexB BintoB BtheB
B
successionB BofB BcodeB Bunits.B BIfB ByouB BuseB BtheB BcodePointAtB BtoB BloopB
B
acrossB BaB Bstring,B BitB BproducesB BrealB BcharactersB BandB BnotB BcodeB Bunits.
🌹🐉";
B
//B B→B B
// → 🐉
BB BB
RecognizingB Btext
YouB BhaveB BtheB BcharacterB BScriptB BfunctionB BandB BaB BwayB BtoB BloopB BacrossB
charactersB Bcorrectly,B BnowB BcalculateB BtheB BcharactersB BeachB BscriptB
B
returnB Bcounts;
}
console.log(countBy([0,1,B B2,B B3,B B4,B B5],B BnB B=>B BnB B>B B2));
//B B→B B[{number:B Bfalse,B Bcount:B B2},B B{number:B Btrue,B Bcount:B B3}]
TheB BcountByB BfunctionB BanticipatesB BaB BcollectionB B(aB BgroupB BofB
numbers,B BelementB BorB BanythingB BthatB ByouB BcanB BloopB BoverB BwithB
B
for/of)B BandB BaB BfunctionB BthatB BcalculatesB BaB BgroupB BnameB BforB BaB
B
specifiedB Belement.B BItB BsendsB BbackB BaB BlistB BofB Bobjects.B BEachB BofB BtheB
B
objectsB BnamesB BaB BgroupB BandB BdeterminesB BtheB BnumberB BofB BelementsB
B
TheB BmethodB BfindIndexB BisB BsimilarB BtoB BindexOf.B BThisB BmethodB BisB BusedB
toB BsearchB BforB BtheB BfirstB BvalueB BforB BwhichB BtheB BstatedB BfunctionB BsendsB
B
backB BtrueB BandB BreturnsB B-1B BwhenB BzeroB BelementsB BisB Bfound.B BYouB BcanB
B
useB BtheB BcountByB BtoB BdetermineB BwhichB BscriptB BisB ButilizedB BinB BaB BblockB
B
ofB Btext.
B
functionB BtextScripts(text)B B{
letB BscriptsB B=B BcountBy(text,B BcharB B=>B B{
letB BscriptB B=B BcharacterScript(char.codePointAt(0));
returnB Bscript?B Bscript.nameB B:B B"none";
}).filter(({name})B B=>B BnameB B!=B B"none");
letB BtotalB B=B Bscripts.reduce((n,B B{count})B B=>B BnB B+B Bcount,B B0);
ifB B(totalB B==B B0)B BreturnB B"NoB BscriptsB Bfound";
returnB Bscripts.map(({name,B Bcount})B B=>B B{
returnB B`${Math.round(countB B*B B100B B/B Btotal)}%B B${name}`;
}).join(",B B");
}
stringB B"none"B BforB BcharactersB BwithoutB BanyB Bscript.B BIfB ByouB BwantB BtoB
B
calculateB Bpercentages,B ByouB BneedB BtoB BdetermineB BtheB BtotalB BamountB BofB
B
charactersB BbelongingB BtoB BaB BscriptB BthatB BtheB BreduceB BmethodB BcanB
B
reduce.B BIfB BitB BfindsB BzeroB Bcharacters,B BtheB BfunctionB BsendsB BbackB BtheB
B
"none"B Bstring.
B
Summary
HavingB BtheB BabilityB BtoB BsendB BfunctionB BvaluesB BtoB BseveralB BfunctionsB BisB
anB BessentialB BaspectB BofB BJavaScript.B BItB BenablesB BwritingB BfunctionsB BthatB
B
declaresB BtheseB BfunctionsB BcanB BcontainB BtheB BgapsB BbyB BgivingB BfunctionB
B
UseB BforEachB BtoB BloopB BacrossB BelementsB BwithinB BanB Barray.B BUseB BtheB
B
BfilterB BmethodB BtoB BsendB BbackB BaB BnewB BarrayB BthatB BhasB BelementsB BthatB
BconveyB BtheB BpredicateB Bfunction.B BChangingB BanB BarrayB BbyB BsettingB BeachB
itemB BthroughB BaB BfunctionB BusingB BtheB Bmap.B BUseB BreduceB BtoB BmergeB
B
Exercises
IllustrateB BaB BJavaScriptB BfunctionB BthatB BtakesB BanB BarrayB BofB BnumbersB
savedB BandB BsearchB BforB BtheB Bsecond-lowestB BandB BsecondB BhighestB
B
numbers.
B
Solution
Chapter 7: The Secret Life
BB BB BB BB BB
of Objects
BB
WhenB BitB BcomesB BtoB BProgramingB Blanguages,B BthereB BisB BaB BsetB BtechniqueB
thatB ButilizesB BobjectsB BasB
B B aB fundamentalB
B ideaB
B ofB
B programB
B
organization,B
B andB
B BtheyB areB
B BcalledB theB
B object-orientedB
B
chapter.
B
Encapsulation
communicateB BwithB BeachB BotherB BusingB Binterfaces,B BaB BrestrictedB BsetB BofB
B
higherB Blevel,B BhidingB BtheB BspecificB Bexecution.B BIllustrateB BthisB BtypeB BofB
B
layoutB BareB BpublicB BwhileB BtheB BouterB BcodeB BisB Bprivate.B BDefineB BtheB
B
theB BunderscoreB B(_)B BcharacterB BatB BtheB BbeginningB BofB BpropertyB BnamesB
B
Methods
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}'`);
}
console.log(Object.getPrototypeOf({})B B==
Object.prototype);
likeB BtoStringB BthatB BtransformsB BanB BobjectB BtoB BaB BstringB Bexecution.
B
defaultB Bproperties;
B
.prototype.
console.log(Object.getPrototypeOf(Math.max)B B==
Function.prototype);
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;
}
Bfunction.
functionB BRabbit(type)B B{
this.typeB B=B Btype;
}
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}'`);
}
}
thatB BgraspB BfunctionsB BtoB BbeB BincludedB BinB BtheB Bprototype.B BWhenB ByouB
B
useB BanB Bexpression,B BitB BdoesB BnotB BdescribeB BaB BbindingB BburB BprovidesB
B
theB BconstructorB BasB BaB Bvalue.B BYouB BcanB BexcludeB BtheB BclassB BnameB BinB
B
anB Bexpression.
B
letB BobjectB B=B BnewB BclassB B{getWord()B B{B BreturnB B"hello";B B}B B};
console.log(object.getWord());
anB BassignedB BpropertyB BwithB BsimilarB BnamesB BinB BtheB Bprototype,B BitB
B
console.log(Array.prototype.toStringB B==
Object.prototype.toString);
containedB BinB BtheB Barray.B BIfB ByouB BcallB BObject.prototype.toStringB BtoB BanB
B
console.log(Object.prototype.toString.call([1,B B3]));
//B B→B B[objectB BArray]
Maps
AB BmapB BisB BaB BdataB BlayoutB BthatB BconnectB BvaluesB BwithB BotherB Bvalues.B BIfB
ByouB BwantB BtoB BmapB BnamesB BtoB Bages,B BwriteB ByourB BcodeB BlikeB Bthis:
letB BagesB B=B B{
Boris:B B39,
Liang:B B22,
Júlia:B B62
};
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));
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]);
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]());
whenB BtheB BpropertyB BisB Bcalled.B BTheB BmethodB BsendsB BbackB BanB BobjectB
B
thatB BproducesB BaB BsecondB Blayout.B BItB BcontainsB BaB BnextB BmethodB BthatB
B
sendsB BbackB BtheB BfollowingB Bresult.B BTheB BresultB BisB BanB BobjectB BwithB BaB
B
TheB BcontentB BofB BtheB BclassB BisB BsavedB BinB BanB BindividualB BarrayB BofB BwidthB
× heightB Belements.B BTheseB BelementsB BareB BsavedB BrowB BafterB Brow.B BTheB
B BB
elementB Bfunction,B BwhichB BisB BusedB BtoB BsetB BtheB BinitialB Bvalues.B BUseB BtheB
B
BgetB BmethodB BandB BsetB BmethodB BtoB BrecoverB BandB BupdateB BelementsB
BwithinB BtheB Bmatrix.B BBelowB BisB BtheB BlayoutB BofB BobjectsB BwithB Bx,B By,B BandB
valueB Bproperties.
B
classB BMatrixIteratorB B{
constructor(matrix)B B{
this.xB B=B B0;
this.yB B=B B0;
this.matrixB B=B Bmatrix;
}
next()B B{
ifB B(this.yB B==B Bthis.matrix.height)B BreturnB B{done:B Btrue};
letB BvalueB B=B B{x:B Bthis.x,
y:B Bthis.y,
value:B Bthis.matrix.get(this.x,B Bthis.y)};
this.x++;
ifB B(this.xB B==B Bthis.matrix.width)B B{
this.xB B=B B0;
this.y++;
}
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);
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);
}
}
onlyB BCelsiusB BandB BtransformB BtoB BandB BfromB BCelsiusB BinB BtheB BFahrenheitB
B
getterB BandB Bsetter.B BWithinB BaB BclassB Bdeclaration,B BmethodsB BthatB BareB
B
staticB BwrittenB BbeforeB BtheirB BnamesB BareB BsavedB BonB BtheB Bconstructor.B
B
Inheritance
Bchange.B BTheB BvalueB BsetB BatB Bx,yB BremainsB BtheB BsameB BasB BtheB By,x.B BUseB
BtheB BJavaScript’sB BprototypeB BsystemB BtoB BbuildB BaB BnewB Bclass,B BtheB
prototypeB BforB BtheB BnewB BclassB BisB BacquiredB BfromB BtheB BoldB BprototypeB
B
butB BsetsB BaB BnewB BdefinitionB BforB BtheB Bmethod.B BThisB BisB BcalledB
B
illustration:
B
Summary
InB BthisB Bchapter,B BweB BrealizeB BthatB BobjectsB BcanB BperformB BmoreB BthanB
holdingB BtheirB Bproperties.B BTheyB BconsistB BofB BprototypesB BthatB BareB
B
objectsB BasB Bwell.B BTheyB BbehaveB BlikeB BtheyB BcontainB BpropertiesB BthatB
B
theyB BdoB BnotB BprovideB BasB BlongB BasB BtheB BprototypeB BhasB BthatB Bproperty.B
B
functionsB BthatB BtheirB BnamesB BoftenB BbeginB BwithB BaB BcapitalB Bletter,B BandB
B
usedB BwithB BtheB BnewB BoperatorB BtoB BbuildB BnewB Bobjects.B BTheB BnewB
B
propertyB BofB BtheB Bconstructor.B BAB BclassB BnotationB BoffersB BaB BwayB BtoB
B
describeB BaB BconstructorB BandB BitsB Bprototype.B BWeB BalsoB BtouchedB BtheB
B
Exercise
WriteB BaB BJavaScriptB BprogramB BtoB BcreateB BanB Barray,B BthroughB BanB
iteratorB BfunctionB BandB BaB BprimaryB BseedB Bvalue.
B
Solution
Chapter 8: A Robot BB BB BB
InB BthisB Bchapter,B BthereB BwillB BbeB BworkB BonB BaB BrobotB Bprogram,B BaB BshortB
programB BthatB BexecutesB BaB BtaskB BinB BaB BvirtualB Bworld.B BWeB BwillB BbeB
B
MeadowB Bfield
TheB BMeadowB BfieldB BvillageB BisB BaB BsmallB BoneB BconsistingB BofB B14B BroadsB
andB B11B Bplaces.B BBelowB BisB BanB BillustrationB BwithB BanB BarrayB BofB Broads:
B
TheB BvillageB BroadsB BcreateB BaB Bgraph.B BAB BgraphB BisB BaB BgroupB BofB BpointsB
(villageB Bplaces)B BwithB BlinesB BdividingB BthemB B(roads).B BTheB BgraphB BisB BtheB
B
worldB BwhereB BourB BrobotB BwalksB Bthrough.B BNowB BletB BusB BtransformB BourB
B
listB BtoB BaB BdataB BlayoutB BthatB BeachB BplaceB BdecidesB BwhereB ByouB Bcan.
B
functionB BbuildGraph(border)B B{
letB BgraphB B=B BObject.create(Null);
functionB BaddBorders(from,B Bto)B B{
ifB B(graph[from]B B==B Bnull)B B{
graph[from]B B=B B[to];
}B BelseB B{
graph[from].push(to);
}
}
returnB Bgraph;
}
theB BsplitB BmethodB BtoB BgoB BthroughB BtheB BroadB Bstrings,B BthatB BcontainsB
B
theB BformB B"Start-End",B BtoB Btwo-elementB BarraysB BwithinB BtheB BstartB BandB
B
The task
BB
OurB BrobotB BwillB BwalkB BacrossB BtheB Bvillage.B BThereB BareB BdifferentB BparcelsB
inB BseveralB Bplaces.B BTheB BrobotB BreceivesB BaB BparcelB BwhenB BitB BarrivesB
B
andB BdeliversB BthemB BwhenB BitB BgetsB BtoB BtheirB Bdestination.B BWhenB BallB
B
tasksB BhaveB BallB BbeenB Bexecuted,B BallB BparcelsB BmustB BbeB Bdelivered.B BIfB
B
youB BwantB BtoB BreplicateB BthisB Bprocess,B BdescribeB BaB BvirtualB BworldB BthatB
B
canB BdefineB Bit.B BThisB BmethodB BrevealsB BtheB BrobotB BlocationB BasB BwellB BasB
B
theB Bparcels.B BLetB BusB BbringB BdownB BtheB Bvillage'sB BstateB BtoB BaB BspecificB
B
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.
transformsB BanB BobjectB BsoB BthatB BitB BdisregardsB BwritingB BtoB BitsB
B
properties.
B
//B B→B B5
Simulation
AB BdeliveryB BrobotB BtakesB BaB BgoodB BglanceB BatB BtheB BworldB BandB
determinesB BwhatB BdirectionB BitB BmovesB Bto.B BTherefore,B BaB BrobotB BisB BaB
B
functionB BwhichB BtakesB BaB BVillageStateB BobjectB BandB BsendB BbackB BtheB
B
nameB BofB BaB BnearbyB Bplace.B BTheB BrobotB BsendsB BbackB BanB BobjectB
B
consistingB BofB BitsB BintendedB BdirectionB BandB BaB BmemoryB BvalueB BreturnedB
B
TheB BrobotB BcanB BwalkB BthroughB BinB BdifferentB BdirectionsB BatB BeveryB Bturn.B
ItB BcanB BrunB BintoB BallB BparcelsB BandB BthenB BgetB BtoB BitsB BdeliveryB Bpoint.B
B
functionB BrandomPick(array)B B{
letB BchoiceB B=B BMath.floor(Math.random()B B*B Barray.length);
returnB Barray[choice];
}
functionB BrandomRobot(state)B B{
returnB B{direction:B BrandomPick(roadGraph[state.place])};
}
IfB ByouB BwantB BtoB BtestB BthisB BuniqueB Brobot,B BcreateB BaB BnewB BstateB BwithB
fewB Bparcels.
B
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;
}
TheB BrobotB BisB BfasterB Bnow.B BItB BtakesB BaB BmaximumB BofB B26B BturnsB B(twiceB
BtheB B13-stepB Broute)B BbutB BmoreB BoftenB Bless.
Pathfinding
AnB BinterestingB BapproachB BisB BtoB BdevelopB BroutesB BfromB BtheB BstartingB
Bpoint,B BandB BinspectB BeveryB BavailableB BplaceB BthatB BhasB BnotB BbeenB BvisitedB
BuntilB BitB BattainsB BitsB Bgoal.B BTheB BbelowB BillustrationB BexplainsB Bthat:
functionB BfindRoute(graph,B Bfrom,B Bto)B B{
letB BworkB B=B B[{at:B Bfrom,B Broute:B B[]}];
forB B(letB BiB B=B B0;B BiB B<B Bwork.length;B Bi++)B B{
letB B{at,B Broute}B B=B Bwork[i];
forB B(letB BlocationB BofB Bgraph[at])B B{
ifB B(placeB B==B Bto)B BreturnB Broute.concat(location);
ifB B(!work.some(wB B=>B Bw.atB B==B Blocation))B B{
work.push({at:B Bplace,B Broute:B Broute.concat(location)});
}
}
}
}
TheB BfunctionB BsavesB BaB BworkB Blist.B BThisB BisB BanB BarrayB BofB BplacesB BthatB
willB BbeB BinspectedB Bnext,B BtogetherB BwithB BtheB Broute.B BItB BbeginsB BwithB BanB
B
emptyB BrouteB BandB BtheB BstartB Bposition.B BEveryB BlocationB BcanB BbeB
B
touchedB BfromB BeveryB Blocation,B BaB BrouteB BcanB BalsoB BbeB BfoundB BbetweenB
B
InB BthisB BchapterB BweB BtouchedB BonB BrobotsB BusingB BJavaScript.B BWeB BgotB BtoB
theB BMeadowB BfieldB BvillageB BwhereB BweB BtalkedB BaboutB BaB BvillageB BwithB
B
11B BplacesB BandB B14B Broads,B BthenB BweB BmovedB BtoB BtheB BPersistentB Bdata,B
B
wherebyB BDataB BstructuresB BbehaveB BlikeB BstringsB BandB BdoB BnotB Bchange.B
B
SimulationB BenablesB ByouB BtoB BpassB BmemoryB BtoB BrobotsB BandB BletB BthemB
B
BB
Chapter 9: Bugs and Errors
BB BB BB BB
ComputerB BprogramB BflawsB BareB BcalledB Bbugs,B BtheB BmistakesB BmadeB BbyB BaB
computerB Bprogram.
B
StrictB Bmode
YouB BcanB ButilizeB BJavaScriptB BinB BaB BstrictB Bmode.B BThisB BcanB BbeB BachievedB
byB BaddingB BtheB BstringB B"useB Bstrict"B BrightB BatB BtheB BtopB BofB BaB Bfile.B
B
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();
createdB Bobject:
B
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}`);
}
WhenB BaB BprogramB BdisplaysB BanB Berror,B BtheB BnextB BthingB BisB BtoB
BdetermineB BtheB BproblemB BandB BgetB BitB Bfixed.B BTheB BerrorB BmessageB BwillB
BpointB BdirectlyB BatB BaB BparticularB BlineB BinB ByourB BblockB BofB Bcode.B BTakeB BaB
BlookB BatB BtheB BerrorB Bdescription,B BandB ByouB BwillB BfindB BtheB BproblematicB
Bline.B BThisB BexampleB BprogramB BtriesB BtoB BtransformB BaB BwholeB BnumberB
BintoB BaB BstringB BwithinB BsetB BbaseB B(decimal,B Bbinary,B BandB BsoB Bon)B BbyB
BcontinuouslyB BselectingB BoutB BtheB BlastB BdigitB BandB BdividingB BtheB BnumberB
BtoB BeradicateB BtheB Bdigit.
functionB BnumberToString(n,B BbaseB B=B B10)B B{
letB BresultB B=B B"",B BsignB B=B B"";
ifB B(nB B<B B0)B B{
signB B=B B"-";
nB B=B B-n;
}
doB B{
resultB B=B BString(nB B%B Bbase)B B+B Bresult;
nB B/=B Bbase;
}B BwhileB B(nB B>B B0);
returnB BsignB B+B Bresult;
}
console.log(numberToString(13,B B10));
//B B→B B1.5e-3231.3e-3221.3e-3211.3e-3201.3e-3191.3e…-3181.3
AddingB BsomeB Bconsole.logB BcallsB BintoB BtheB BprogramB BisB BanB BexcellentB
pathB BtoB BtakeB BifB ByouB BwantB BtoB BacquireB BadditionalB BinformationB BaboutB
B
theB Bexecution.B BWeB BwantB BnB BtoB BgetB BtheB BvaluesB B13,B B1,B BandB BthenB B0.B
B
WeB BshouldB BstateB BtheB BvalueB BatB BtheB BbeginningB BofB BtheB Bloop'
B
13
1.3
0.13
0.013…
1.5e-323
DividingB B13B BbyB BwillB BnotB BprovideB BaB BwholeB Bnumber.B BInsteadB BofB BnB B/=B
base,B BwhatB BweB BwantB BisB BnB B=B BMath.floor(nB B/B Bbase)B BsoB BthatB BtheB
B
AnotherB BgreatB BwayB BtoB BspecifyB BaB BbreakpointB BisB BtoB BinsertB BaB BdebuggerB
statementB B(keyword)B BintoB ByourB Bprogram.B BIfB BtheB BdeveloperB BtoolsB
B
willB BpickB BitB BupB BandB BpauseB BtheB BprogramB BanytimeB BitB BgetsB BtoB BthatB
B
Exceptions
WhenB BaB BfunctionB BisB BcannotB BgoB Bfurther,B BtheB BexceptionB BhandlingB BisB
theB BplaceB BthatB BunderstandsB BhowB BtoB BfixB BthatB Bproblem.B BExceptionsB
B
areB BaB BtoolB BthatB BenablesB BaB BblockB BofB BcodeB BthatB BrunsB BintoB BdifficultiesB
B
toB BthrowB BanB Bexception,B BandB BanB BexceptionB BcouldB BbeB BanyB Bvalue.B
B
YouB BcanB BintentionallyB BcreateB BproblemsB BwithinB ByourB BlineB BofB BcodeB
B
toB BcatchB BtheB BexceptionB BduringB BitsB BzoomingB BdownB BtheB BprocessB BsoB
B
thatB ByouB BcanB BuseB BitB BtoB BsolveB BtheB BproblemB BandB BcontinueB ByourB
B
work.
B
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);
}
exceptionB BcouldB BstopB BthemB BfromB Bhappening.B BBelowB BisB BsomeB BbadB
B
bankingB Bcode:
B
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;
}
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:
SelectiveB Bcatching
WhenB BanB BexceptionB BmakesB BitB BtoB BtheB BbottomB BofB BaB BblockB BofB BcodeB
BwithoutB Berrors,B BitB BisB BhandledB BbyB BtheB Benvironment.B BInvalidB BusesB
suchB BasB BinspectingB BupB BaB BpropertyB BonB Bnull,B BcitingB BaB BnonexistentB
B
binding,B BorB BcallingB BaB Bnon-functionB BwillB BresultB BinB BraisedB Bexceptions.B
B
selectiveB BcatchingB BofB Bexceptions.B BBelowB BisB BanB BexampleB BthatB BtriesB
B
answer:
B
forB B(;;)B B{
tryB B{
letB BdirB B=B BpromtDirection("Where?");B B//B B←B Btypo!
console.log("YouB BselectB B",B Bdir);
break;
}B BcatchB B(e)B B{
console.log("InvalidB Bdirection.B BTryB Bagain.");
}
}
TheB BforB B(;;)B BconstructB BisB BusedB BtoB BbuildB BaB BloopB BthatB BcannotB BbeB
BterminatedB BonB BitsB Bown.B BYouB BcanB BbreakB BoutB BofB BtheB BloopB BwhenB ByouB
outputB BanB BundefinedB BvariableB Berror.B BIfB ByouB BwantB BtoB BcatchB BaB
B
particularB BtypeB BofB Bexception,B BcheckB BinB BtheB BcatchB BblockB BifB BtheB
B
exceptionB ByouB BhaveB BisB BtheB BsameB BoneB ByouB BwantB BandB BrethrowB Bit.B
B
Let’sB BdescribeB BaB BnewB BkindB BofB BerrorB BandB ButilizeB BinstanceB BofB BtoB
B
recognizeB Bit.
B
TheB BnewB BerrorB BclassB BprolongsB Berror.B BItB BdoesB BnotB BdescribeB BitsB BownB
constructor,B BitB BinheritsB BtheB BErrorB Bconstructor,B BwhichB BanticipatesB BaB
B
}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
solveB BproblemsB Blocally.B BYouB BcanB BtrackB BthemB BwithB BspecialB BreturnB
B
Exercise
chapter,B BweB BwillB BdiscussB BregularB Bexpressions.B BTheyB BareB BusedB BtoB
B
defineB BpatternsB BwithinB BaB BstringB Bdata.B BTheyB BcreateB BaB Bsmall,B
B
differentB BlanguageB BthatB BconsistsB BofB BJavaScriptB BasB BwellB BasB BotherB
B
languages.
B
determiningB BifB BaB BstringB BcontainsB BaB BmatchB BofB BtheB BpatternB BinB BtheB
B
expression.
B
console.log(/abc/.test("abcde"));
//B B→B Btrue
console.log(/abc/.test("abxde"));
theB Bstring,B BweB BareB BrunningB BaB Btest,B BtheB BtestB BwillB BreturnB Btrue.
B
Sets of characters
BB BB
RegularB BexpressionsB BenableB BusB BtoB BindicateB BdifficultB Bpatterns.B BIfB ByouB
wantB BtoB BequalB BanyB BnumberB BinB BaB BregularB Bexpression,B BplaceB BaB BsetB
B
ofB
B charactersB
B Bin-betweenB BsquareB Bbrackets.B BTheB followingB
B
console.log(/[0123456789]/.test("inB B1992"));
//B B→B Btrue
console.log(/[0-9]/.test("inB B1992"));
//B B→B Btrue
AB BhyphenB B(-)B BbetweenB BtwoB BcharactersB BinsideB BsquareB BbracketsB BisB
usedB BtoB BspecifyB BaB BscopeB BofB BcharactersB BthatB BtheB Bcharacter’sB
B
UnicodeB BnumbersB BdecideB BtheB Bcommand.B BCharactersB BfromB B0B BtoB B9B
B
stayB BnextB BtoB BeachB BotherB BinB BthisB BcommandB B(codesB B48B BtoB B57),B BsoB B[0-
B
9]B BwrappingB BthemB BallB BandB BequalsB BanyB Bdigit.B BCommonB BcharacterB
groupsB BcontainB BindividualB BshortcutsB Bbuilt-in.
B
DigitsB BareB BpartB BofB Bthem:B B\dB BmeansB BtheB BexactB BthingB BasB B[0-9].
\dB BAnyB BcharacterB Bdigit
\wB BanB BalphanumericB BcharacterB B(“wordB Bcharacter”)
\sB BAnyB BwhitespaceB BcharacterB B(space,B Btabs,B Bnewline,B BandB Bsimilar)
\DB BAB BcharacterB BwhichB BisB BnotB BaB Bdigit
\WB BAB BnonalphanumericB Bcharacter
\SB BAB BnonwhitespaceB Bcharacter
.B BAnyB BcharacterB BwithoutB BforB Bnewline
So,B BmatchB BaB BdateB BandB BtimeB BformatB BlikeB B01-30-2003B B15:20B BwithB BtheB
expressionB Bbelow:
B
theB BperiodB BhasB BnoB BmeaningB BasB BwellB BasB BotherB BuniqueB Bcharacters,B
B
likeB B+.
B
moreB Bdigits,B BplaceB BaB BplusB BsignB B(+)B BimmediatelyB BafterB BanB BinputB BinB
B
console.log(/'\d+'/.test("'123'"));
//B B→B Btrue
console.log(/'\d+'/.test("''"));
wantB BitB BtoB BexecuteB BpreciselyB BfourB Btimes,B BdefineB BaB BrangeB BlikeB Bthis:
B
{2,4}B BsignifiesB BthatB BtheB BelementB BmustB BexecuteB BtwiceB BandB BatB BmostB
fourB Btimes.B BBelowB BisB BanotherB BpatternB BofB BtheB BdateB BandB BtimeB
B
andB Bhours.
B
regularB Bexpression,B BwhichB BisB BcitedB BinB Bparentheses,B BcountsB BasB BanB
B
equalingB BoneB BorB BmoreB BsuccessionsB BlikeB Bthat.B BTheB BIB BendingB BtheB
B
firstB BexpressionB BinB BtheB BexampleB BisB BusedB BforB BcaseB Binsensitive,B
B
enablingB BitB BtoB BequalB BtheB BuppercaseB BBB BinB BtheB BinputB Bstring.B
B
execB B(execute)B Bmethod,B BwhichB BwillB BoutputB BnullB BifB BitB BcouldB BfindB BaB
B
matchB BandB BsendsB BbackB BanB BobjectB BcontainingB BdataB BaboutB BtheB Bmatch.
B
//B B→B B8
AB BsentB BbackB BobjectB BfromB BexecB BcontainsB BanB BindexB Bproperty,B BwhichB
determineB BwhatB BpartB BofB BtheB BstringB BtheB BthrivingB BmatchB Bstarts.B
B
wholeB BmatchB BisB BtheB Bfirst,B BtheB BnextB BisB BtheB BmatchedB BpartB BbyB BtheB
B
severalB Btimes,B BonlyB BtheB BlastB BmatchB BfinishesB BinB BtheB Barray.
B
console.log(/bad(ly)?/.exec("bad"));
console.log(newB BDate());
//B B→B BMonB BNovB B11B B2023B B16:19:11B BGMT+0100B B(CET)
YouB BcanB BasB BwellB BBuildB BanB BobjectB BforB BaB BparticularB Btime.
console.log(newB BDate(2008,B B11,B B8));
//B B→B BWedB BDecB B08B B2008B B00:00:00B BGMT+0100B B(CET)
console.log(newB BDate(2008,B B11,B B9,B B12,B B59,B B59,B B999));
//B B→B BWedB BDecB B08B B2009B B12:59:59B BGMT+0100B B(CET)
YouB BshouldB BfollowB BtheB BJavaScriptB BdateB BnamingB BconventionB BwhereB
monthB BnumbersB BbeginB BatB BzeroB B(therefore,B BDecemberB BisB B11),B BandB
B
areB BsavedB BasB BtheB BnumberB BofB BmillisecondsB BinB BtheB BUTCB BtimeB Bzone.B
B
currentB BmillisecondB BcountB BbyB BbuildingB BaB BnewB BDateB BobjectB BandB BcallB
B
getTimeB BonB BitB BorB BuseB BtheB BDate.nowB Bfunction.B BDateB BobjectsB BproduceB
B
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);
inputB Bstring,B BwhileB BtheB BdollarB BsignB BequalsB BtheB Bend.B BTherefore,B
B
/^\d+$/B BmatchesB BaB BstringB BcontinuingB BmultipleB BorB BoneB Bdigits,B B/^!B B/B
B
matchesB BanyB BstringB BthatB BbeginsB BwithB BanB BexclamationB Bmark,B BandB
B
/x^/B BmatchesB BnoB Bstring.B BIfB ByouB BwantB BtheB BdateB BtoB BbeginB BandB BendB
B
onB BaB BboundaryB Bword,B ButilizeB BtheB BmarkerB B\b.B BAB BwordB BboundaryB
B
canB BbeginB BorB BfinishB BstringsB BcontainingB BaB BwordB BcharacterB B(\w)B BonB
B
console.log(/cat/.test("concatenate"));
regularB BexpressionsB BandB BtestB Bthem.B BWeB ButilizeB BtheB BpipeB BcharacterB
B
(|)B BtoB BmarkB BaB BchoiceB BbetweenB BtheB BpatternB BtoB BtheB BleftB BandB Bright:
B
gB BoptionB B(forB Bglobal)B BtoB BtheB Bexpression,B BeveryB BmatchB BcontainedB BinB
B
console.log("Borobudur".replace(/[ou]/,B B"a"));
//B B→B BBarobudur
console.log("Borobudur".replace(/[ou]/g,B B"a"));
//B B→B BBarabadar
TheB BmajorB BimportanceB BofB ButilizingB BregularB BexpressionsB BwithB BreplaceB
isB BbecauseB BitB BrefersB BtoB BmatchedB BgroupsB BinB BtheB BreplacementB Bstring.B
B
ForB Binstance,B ByouB BhaveB BaB BlargeB BstringB BconsistingB BofB Bpeople'sB Bname,B
B
oneB BnameB BperB Bline,B BusingB BtheB BformatB BLastname,B BFirstname.B BYouB
B
canB BasB BwellB BchangeB BandB BremoveB BtheseB Bnames,B BeradicateB BtheB
B
commaB BtoB BgetB BaB BFirstnameB BLastnameB Bformat,B BandB ButilizeB BtheB
B
followingB Bcode:
B
console.log(
whichB BmatchesB BopposingB BtheB BfirstB Bgroup,B B$2B BupB BtoB B$9.B BEachB BandB
B
everyB BmatchB BcanB BbeB BreferredB BtoB BwithB B$&.B BYouB BcanB BpassB BaB
B
functionB BinsteadB BofB BaB BstringB BasB BtheB BsecondB BargumentB BtoB Brestore.B
B
ForB BeachB Breplacement,B BtheB BfunctionB BisB BcalledB BwithB BtheB BmatchedB
B
groupB BasB Barguments,B BandB BincludeB BtheB BreturnB BvalueB BintoB BtheB BnewB
B
YouB BcanB BuseB BreplaceB BtoB BwriteB BaB BfunctionB BthatB BeradicatesB BallB
commentsB BfromB BaB BblockB BofB BJavaScriptB Bcode.B BLookB Bbelow:
B
functionB BstripComments(code)B B{
returnB Bcode.replace(/\/\/.*|\/\*[^]*\*\//g,B B"");
}
RepetitiveB BOperatorsB B(+,B B*,B BandB B{})B BareB BcalledB BgreedyB BwhichB BmeansB
theyB BmatchB BandB BtheyB BcanB BalsoB Bbacktrack.B BIfB BaB BquestionB BmarkB BisB
B
placedB BafterB BthemB B(+?,B B*?,B B??,B B{}?),B BtheB BgreedB BdisappearsB BandB
B
beginB BmatchingB BnoB BmatterB BhowB Bsmall.B BTheB BsmallestB BstretchB BofB
B
charactersB BwhichB BbringsB BaB B*/,B BisB BtheB BstarB Bmatch.B BItB BabsorbsB BoneB
B
functionB BstripComments(code)B B{
returnB Bcode.replace(/\/\/.*|\/\*[^]*?\*\//g,B B"");
}
ThereB BareB BfewB BinstancesB BwherebyB ByouB BwouldB BnotB BunderstandB BtheB
specificB BpatternB ByouB BshouldB BmatchB BagainstB BwhenB ByourB BcodeB BisB
B
beingB Bwritten.B BIfB ByouB BwantB BtoB BsearchB BforB BtheB BuserB BnameB BinB BaB
B
chunkB BofB BtextB BandB BwrapB BitB BinB BunderscoreB BcharactersB BtoB BmakeB BitB
B
unique.B BButB ByouB BcanB BcreateB BaB BstringB BandB ButilizeB BtheB BRegExpB
B
TheB BsecondB BargumentB BtoB BtheB BRegExpB BconstructorB BconsistsB BofB BtheB
B
youB BcanB BcallB BtheB BindexOfB BmethodB BaB BregularB Bexpression,B BandB BitB
B
sendsB BbackB BtheB BfirstB BindexB BwhereB BitB BseesB BtheB BexpressionB BandB
B
objectsB BcontainB Bproperties.B BOneB BofB BtheB BpropertiesB BisB BcalledB Bsource,B
B
andB BitB BconsistsB BofB BtheB BstringB BthatB BbuiltB BtheB Bexpression.B BlastIndexB
B
whereB BtheB BnextB BmatchB BwillB Bbegin.B BTheB BregularB BexpressionB BmustB
B
containB BtheB BglobalB B(g)B BorB BstickyB B(y)B Boption,B BandB BtheB BmatchB BwillB
B
//B B→B B4
console.log(pattern.lastIndex);
//B B→B B5
TheB BdissimilarityB BbetweenB BtheB BglobalB BandB BtheB BstickyB BoptionsB BisB
that,B BwhenB ByouB BenableB Bsticky,B BtheB BmatchB BsucceedsB BifB BitB BbeginsB BatB
B
lastIndex,B BwhileB BwithB Bglobal,B BitB BwillB BfindB BaB BpositionB BforB BtheB BmatchB
B
canB Bbegin.
B
lastIndexB Bproperty.
B
LetB BinputB B=B B"AB BstringB BwithB BthreeB BnumbersB BinB Bit...B B42B BandB B88.";
letB BnumberB B=B B/\b\d+\b/g;
letB Bmatch;
whileB B(matchB B=B Bnumber.exec(input))B B{
console.log("Found",B Bmatch[0],B B"at",B Bmatch.index);
}
whileB Bstatement,B BtheB BmatchB BisB BweB BexecuteB BtheB BmatchB BatB BtheB
B
beginningB BofB BeveryB Biteration,B BstoreB BtheB BresultB BwithinB BaB Bbinding,B
B
fullname=LarryB BDoe
type=kindergartenB Bbully
website=http://www.google.com/google/
[davaeorn]
fullname=Davaeorn
type=evilB Bwitch
outputdir=/home/margin/enemy/davaeorn
TheB BrulesB BforB BthisB BformatB B(whichB BisB BaB BgenerallyB BusedB Bformat,B
usuallyB Bcalled
B
returnB Bresult;
}
console.log(parseINI(`
name=Vasilis
[address]
city=Tessaloniki`));
propertiesB BcanB BbeB BfoundB BinB BsectionsB BareB BsavedB BinB BaB BdifferentB
B
sectionB Bobject.B BTheB BsectionB BbindingB BpointsB BtoB BtheB BobjectB BforB BtheB
B
headersB BorB BpropertyB Blines.B BIfB BaB BlineB BisB BalwaysB Bproperty,B BitB BisB
B
savedB BinB BtheB BexistingB Bsection.B BIfB BitB BisB BaB BsectionB Bheader,B BbuildB BaB
B
TheB BpatternB BifB B(matchB B=B Bstring.match())B BisB BidenticalB BtoB BtheB BtrickB BofB
utilizingB BanB BassignmentB BasB BtheB BconditionB BforB BaB Bwhile.
B
InternationalB Bcharacters
BecauseB BofB BJavaScript’sB BinitialB BsimplisticB BimplementationB BandB BthatB
thisB BapproachB BsetB BinB BstoneB BasB BstandardB Bbehavior,B BJavaScript’sB
B
don’tB BshowB BinB BtheB BEnglishB Blanguage.B BForB Binstance,B BinB BJavaScript,B
B
BregularB Bexpressions,B BaB B“wordB Bcharacter”B BisB BjustB BoneB BofB BtheB B26B
BcharactersB BinB BtheB BLatinB BalphabetB B(lowercaseB BorB Buppercase),B BdecimalB
digits,B BandB BtheB BunderscoreB Bcharacter.B BCharactersB BlikeB BéB BorB Bß,B BareB
B
wordB Bcharacters,B BtheyB BwillB BnotB BmatchB B\w,B BwillB BmatchB BuppercaseB
B
console.log(/ 🍎{3}/.test("🍎🍎🍎"));
//B B→B Bfalse
🌹>"));
console.log(/<.>/.test("<
managedB BasB BtwoB BcodeB Bunits,B BandB BtheB B{3}B BsectionB BisB BusedB BtoB BtheB
B
secondB BoneB Bonly.B BTheB BdotB BalsoB BmatchesB BaB BsingleB BcodeB Bunit.B BAddB BuB
B
optionB B(forB BUnicode)B BtoB ByourB BregularB BexpressionB BsoB BthatB BitB
B
YouB BcanB BuseB B\pB BinB BaB BregularB BexpressionB BtoB BmatchB BeveryB BcharacterB
thatB BUnicodeB BstandardB BgivesB BaB BsetB Bproperty.
B
console.log(/\p{Script=Greek}/u.test("α"));
Summary
WeB BfocusedB BonB BregularB BexpressionsB BinB BthisB Bchapter.B BAnB BobjectB BthatB
standsB BforB BpatternsB BinB BstringsB BisB BaB BregularB Bexpression.B BTheyB
B
consistB BofB BtheirB BlanguageB BandB ButilizeB BitB BforB BtheB BexhibitionB BofB
B
theseB Bpatterns.
B
whenB BitB BfindsB BaB Bmatch,B BitB BsendsB BbackB BanB BarrayB BhavingB BeveryB
B
matchedB Bgroup.B BThisB BtypeB BofB BarrayB BcontainsB BanB BindexB BpropertyB
B
thatB BspecifiesB BwhereB BtheB BmatchB Bstarted.B BStringsB BuseB BaB BmatchingB
B
methodB BtoB BmatchB BthemB BinB BoppositionB BtoB BaB BregularB BexpressionB BasB
B
wellB BasB BaB BsearchB BmethodB BtoB BfindB Bone,B BsendingB BbackB BonlyB BtheB
B
Exercise
WriteB BaB BJavaScriptB BprogramB BworkingB BasB BaB BtrimB BfunctionB B(string)B
utilizingB BregularB Bexpression.
B
Solution
Chapter 11: Modules BB BB
ThisB BparticularB BprogramB BhasB BaB BsimpleB Blayout.B BItB BisB BveryB BtoB BexplainB
itsB Bconcept,B BandB BeveryB BpartB BplaysB BaB BpreciseB Brole.B BTheB BorganizingB
B
andB BmaintainingB BofB BtheB BlayoutB BcanB BbeB BmuchB BmoreB Bwork,B BbutB BitB
B
eventuallyB BpaysB BoffB BtheB BnextB BtimeB BsomeoneB BusesB BtheB BprogramB BinB
B
theB Bfuture.B BTherefore,B ByouB BcanB BbeB BintriguedB BtoB BneglectB BitB BandB
B
everythingB Belse,B BitB BisB BhardB BtoB BlookB BatB BanyB BsetB BpieceB BinB Bseparation.B
B
YouB BwillB BhaveB BtoB BcreateB BaB BcomprehensiveB BunderstandingB BofB BtheB
B
fullB Bprogram.B BSecond,B BusingB BanyB BofB BtheB BfunctionalityB BfromB BtheB
B
programB BinB BdifferentB Bsituations,B ByouB BcanB BrewriteB BitB BinsteadB BofB
B
Modules
AB BModuleB BisB BaB BtypeB BofB BprogramB BthatB BdeterminesB BwhichB BpiecesB BitB
shouldB BdependB BonB BandB BwhatB BfunctionalityB BshouldB BitB BproduceB BforB
B
otherB BpiecesB BtoB Butilize.B BByB BputtingB BaB BlimitB BonB BtheB BwaysB BmodulesB
B
communicateB BwithB BoneB Banother,B BtheB BsystemB BisB BidenticalB BtoB BLEGO,B
B
notB BlikeB BmudB BwhereB BtheB BentireB BpiecesB BmixB BwithB Beverything.B
B
moduleB BwantsB BaB BpieceB BfromB BanotherB Bmodule,B BitB BdependsB BonB BthatB
B
module.B BTheB BmoduleB BitselfB BillustratesB BthisB Bfact,B BandB BitB BisB BusedB BtoB
B
determineB BwhichB BotherB BmodulesB BshouldB BbeB BavailableB BtoB BuseB BaB
B
OneB BsignificantB BbenefitB BofB BbuildingB BaB BprogramB BoutB BofB BdifferentB
pieces,B BandB BbeingB BableB BtoB BlaunchB BthoseB BpiecesB Bindividually,B BisB BthatB
B
youB BcanB BapplyB BtheB BsameB BpieceB BinB BseparateB Bprograms.B BWhenB BtheB
B
duplicationB BofB BcodeB Bbegins,B BtheB BpackageB BcomesB BinB BtoB Bplay.B BAB
B
packageB BisB BaB BblockB BofB BcodeB BthatB BcanB BbeB Bshared.B BItB BmayB BconsistB BofB
B
oneB BorB BmoreB BmodulesB BandB BholdsB BinformationB BaboutB BtheB BotherB
B
dependingB
B Bpackages.B BPackagesB alsoB
B containB
B BdocumentationB
describingB BitsB BfunctionsB BsoB BthatB BpeopleB BwhoB Bdidn’tB BwriteB BitB BcanB
B
utilizeB Bit.B BWhenB BaB BproblemB BoccursB BinB BaB Bpackage,B BorB ByouB BaddB BaB
B
dependingB BonB BitsB BupgradesB BtoB BtheB BlatestB Bversion.B BWorkingB BlikeB
B
this,B ByouB BneedB Binfrastructure.B BAB BplaceB BtoB BsaveB BandB BsearchB BforB
B
packagesB BandB BanB BeasyB BwayB BtoB BupgradeB BandB BinstallB Bthem.B BWhenB BitB
B
DivideB BNPMB BintoB BtwoB Bthings:B BanB BonlineB BserviceB BwhereB ByouB BcanB
uploadB BandB BdownloadB BpackagesB BandB BaB BprogramB BthatB BhandlesB BtheB
B
licensed.
B
ImprovisedB Bmodules
BeforeB BtheB ByearB B2015,B BtheB BJavaScriptB BlanguageB BdidB BnotB BcontainB BanyB
built-inB BmoduleB Bsystem,B BbutB BpeopleB BhaveB BbeenB BcreatingB BlargeB
B
systemsB BusingB BJavaScriptB BforB BoverB BaB BdecadeB Bnow,B BandB BtheyB
B
BfunctionsB BtoB BbuildB BlocalB BscopesB BandB BobjectsB BtoB BstandB BforB BmoduleB
Blayouts.B BUseB BthisB BmoduleB BtoB BoverB BbetweenB BdayB BnamesB BandB
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;
}
//B B→B B1
AB BlessB BcomplicatedB BwayB BtoB BexplainB BdataB BasB BcodeB BisB BusingB BtheB
FunctionB Bconstructor.B BItB BtakesB BtwoB BtypesB BofB Bargument,B BaB BstringB
B
withB BaB Bcomma,B BdividedB BlistB BofB BargumentB BnamesB BandB BaB BstringB BwithB
B
theB BbodyB Bfunction.B BItB BenclosesB BtheB BcodeB BinB BaB BfunctionB BvalueB BtoB
B
//B B→B B5
YouB BcanB BencloseB BtheB Bmodule'sB BcodeB BinB BaB BfunctionB BandB ButilizeB BthatB
sameB BfunctionB BscopeB BasB BaB BmoduleB Bscope.
B
CommonJS
TheB BcommonB BapproachB BusedB BtoB BgobbleB BonB BJavaScriptB BmodulesB BisB
theB BCommonJSB Bmodules.B BNode.jsB BusesB BthisB BapproachB BasB BwellB BasB BaB
B
lotB BofB BpackagesB BonB BNPM.B BTheB BmajorB BideaB BinB BCommonJSB BmodulesB
B
BisB BtheB BfunctionB BnamedB Brequire.B BIfB ByouB BcallB BthisB BtogetherB BwithB BtheB
Bdependency'sB BmoduleB Bname,B BitB BloadsB BtheB BmoduleB BandB BsendsB BbackB
itsB Binterface.B BTheB BloaderB BcoversB BtheB BmoduleB BcodeB BwithinB BaB
B
canB BcallB BrequireB BtoB BseeB BtheirB BdependenciesB BandB BplaceB BtheirB BlayoutB
B
inB BtheB BobjectB BthatB BexportsB Bthem.B BThisB BexampleB BmoduleB BgivesB BaB
B
TheB BlayoutB BofB BtheB BordinalB BisB BaB BsingleB Bfunction,B BwherebyB BtheB Bdate-
namesB BexportsB BanB BobjectB BthatB BconsistsB BofB BseveralB BotherB Bthings,B
BmonthsB BandB BdaysB BareB BarraysB BofB Bnames.B BRestructuringB BisB BquiteB BeasyB
BwhenB BbuildingB BbindingsB BforB BimportedB Blayouts.B BTheB BmoduleB BattachesB
BitsB BlayoutB BfunctionB BtoB BexportsB BsoB BthatB BmodulesB BthatB BrelyB BonB BitB
BhaveB BaccessB BtoB Bit.B BUtilizeB BtheB BmoduleB BthisB Bway:
constB B{formatDate}B B=B Brequire(“.B B/format-date");
console.log(formatDate(newB BDate(2017,B B9,B B13),
"ddddB BtheB BDo"));
//B B→B BFridayB BtheB B13th
WeB BcanB BdefineB Brequire,B BinB BitsB BmostB BminimalB Bform,B BlikeB Bthis:
require.cacheB B=B BObject.create(null);
functionB Brequire(name)B B{
ifB B(!B B(nameB BinB Brequire.cache))B B{
letB BcodeB B=B BreadFile(name);
letB BmoduleB B=B B{exports:B B{}};
require.cache[name]B B=B Bmodule;
letB BwrapperB B=B BFunction("require,B Bexports,B Bmodule",B Bcode);
wrapper(require,B Bmodule.exports,B Bmodule);
}
returnB Brequire.cache[name].exports;
}
InB BthisB Bcode,B BreadFileB BisB BaB BpoweredB BfunctionB BthatB BreadsB BaB BfileB BandB
sendsB BbackB BitsB BcontentsB BasB BaB Bstring.B BStandardB BJavaScriptB BdoesB BnotB
B
suchB BasB BNode.jsB BandB BtheB BbrowserB BoffersB BtheirB BuniqueB BwaysB BofB
B
accessingB Bfiles.B BTheB BaboveB BexampleB BbluffsB BthatB BreadFileB Bexists.B BToB
B
keepB BawayB BfromB BloadingB BtheB BsameB BmoduleB BseveralB Btimes,B ByouB
B
needB BaB BstoreB B(cache)B BofB BalreadyB BloadedB Bmodules.B BIfB Bcalled,B BitB
B
examinesB BifB BtheB BdemandedB BmoduleB BloadsB Band,B BifB Bnot,B BitB BloadsB Bit.B
B
ItB BrequiresB BreadingB BtheB Bmodule’sB Bcode,B BenclosingB BitB BwithinB BaB
B
functionB BandB BcallingB Bit.B BTheB BlayoutB BofB BtheB BordinalB BpackageB BfromB
B
earlierB BisB BaB BfunctionB BandB BnotB BanB Bobject.B BTheB BCommonJSB BmodulesB
B
createB BanB BemptyB BlayoutB BobjectB BusingB BtheB BmoduleB BsystemB BforB ByouB
B
ModulesB BdoB BthisB BtoB BexportB BaB BsingleB BvalueB BinsteadB BofB BaB BlayoutB
B
forB BtheB BcreatedB BenclosingB BfunctionB B(andB BsettingB BtheB BrightB BvaluesB
B
whileB BcallingB Bit),B BtheB BloaderB BensuresB BthatB BtheseB BbindingsB BareB
B
accessibleB BwithinB BtheB Bmodule’sB Bscope.B BStringsB BsetB BtoB BrequireB BisB
B
interpretedB BtoB BaB BfilenameB BorB BwebB BaddressB BvaryB BinB BseparateB
B
systems.B BWhenB BitB BstartsB BwithB B“.B B/"B Bor.B B“/,"B BitB BisB BusuallyB
B
translatedB BasB BrelativeB BtoB BtheB BexistingB Bmodule’sB Bfilename.B BSoB B“.B B/B
B
format-date"B BwillB BbeB BtheB BfileB BcalledB Bformat-date.jsB BinB BtheB BsameB
B
directory.
B
IfB BtheB BnameB BisB BnotB Brelative,B BNode.jsB BwillB BsearchB BforB BaB BpackageB
thatB BisB BinstalledB BbyB BthatB Bname.
B
Now,B BinsteadB BofB BwritingB ByourB BownB BINIB BfileB Bparser,B ByouB BcanB ButilizeB
oneB BfromB BNPM.
B
substantialB Bscale.B BTheB BnotationB BisB BquiteB Bweird.B BTheB BthingsB BaddedB
B
toB BexportsB BareB BnotB BaccessibleB BwithinB BtheB BlocalB Bscope.B BWithoutB
B
runningB BtheB BcodeB BofB BaB Bmodule,B BitB BwillB BbeB BtoughB BtoB BdetermineB BitsB
B
TheB BinitialB BideaB BofB BdependenciesB BandB BinterfacesB BstayB BtheB Bsame,B
B
butB BtheirB BdetailsB BareB Bdifferent.B BTheB BnotationB BintegratesB BintoB BtheB
B
language.B BYouB BcanB BnowB BuseB BaB BuniqueB BimportB BkeywordB BtoB BaccessB BaB
B
var).B BAnB BESB Bmodule’sB BlayoutB BdoesB BnotB BrepresentB BaB BsingleB BvalueB
B
butB BaB BsetB BofB BnamedB Bbindings.B BTheB BpreviousB BmoduleB BattachesB
B
formatDateB BtoB BaB Bfunction.B BIfB ByouB BimportB BfromB BaB BdifferentB Bmodule,B
B
theB BbindingB BcomesB BwithB Bit,B BandB BnotB BtheB Bvalue,B BwhichB BmeansB BtheB
B
valueB BofB BanB BexportingB BmoduleB BcanB BchangeB BtheB BbindingB BanyB Btime,B
B
andB BtheB BimportingB BmodulesB BwillB BrecognizeB BitsB BnewB Bvalue.B BIfB BaB
B
bindingB BisB BnamedB Bdefault,B BrecognizesB BitB BasB BtheB Bmodule’sB BmajorB
B
exportedB Bvalue.B BIfB BaB BmoduleB BlikeB BordinalB BimportsB BinB BtheB Bexample,B
B
omittingB BtheB BbracesB BacrossB BtheB BbindingB Bname,B ByouB BwillB BfindB BitsB
B
defaultB Bbinding.B BToB BdevelopB BaB BdefaultB Bexport,B BwriteB BexportB BdefaultB
B
//B B→B B7
AnotherB BmajorB BdifferenceB BisB BthatB BtheB BESB BmoduleB BimportsB BoccurB
beforeB BaB Bmodule’sB BscriptB BbeginsB BtoB Brun.B BImportB BdeclarationsB BmayB
B
notB BdisplayB BwithinB BfunctionsB BorB Bblocks,B BandB BtheB BdependentB BnamesB
B
shouldB BbeB BquotedB BstringsB BandB BnotB BarbitraryB Bexpressions.B BAB BlotB BofB
B
projectsB BareB BwrittenB BthroughB BESB BmodulesB BandB BthenB BchangedB BtoB
B
someB BotherB BformatB BwhenB BitB BisB Bpublished.B BDuringB BaB BtransitionalB
B
ModuleB Bdesign
ProgramB BstructuringB BisB BoneB BofB BtheB BniceB BfeaturesB BofB Bprogramming.B
AnyB BunknownB BfunctionalityB BcanB BmodelB BinB BdifferentB Bways.B BTheB
B
goodB BprogramB BdesignB BisB BaB BpersonalizedB Bone,B BandB BthereB BisB BaB
B
matterB BofB BpreferenceB BandB Btaste.B BToB BunderstandB BtheB BvalueB BofB Bwell-
B
organizedB Bdesign,B ByouB BneedB BtoB BreadB BandB BworkB BonB BseveralB
programsB BandB BtakeB BnoteB BofB BperformingB BandB Bnon-performingB
B
functions.B BTheB BmoduleB BdesignB BisB BstraightforwardB BtoB Buse.B BTheB BiniB
B
stringifyB BandB BparseB B(toB BwriteB BanB BINIB Bfile)B Bfunctions,B Band,B BlikeB
B
JSON,B BchangesB BbetweenB BplainB BobjectsB BandB Bstrings.B BAB BlotB BofB BtheB BINI-
B
fileB BparsingB BmodulesB BonB BNPMB BsupplyB BaB BfunctionB BthatB BreadsB BthatB
typeB BofB BfileB BfromB BtheB BhardB BdiskB BandB BparsesB Bit.B BConcentratedB
B
modulesB BthatB BcalculateB BvaluesB BareB BsuitableB BinB BaB BlargerB BrangeB BofB
B
haveB BsideB Beffects.B BAnB BINIB BfileB BreaderB BthatB BwantB BtoB BreadB BtheB BfileB
B
fromB BdiskB BisB BnotB BusefulB BinB BcasesB BwherebyB BtheB Bfile’sB BcontentB BcomesB
B
necessaryB BandB Buseful,B BbutB BifB ByouB BcanB BuseB BaB Bfunction,B ButilizeB Bit.B
B
VariousB BINIB BfileB BreadersB BonB BNPMB BgivesB BaB BlayoutB BstyleB BthatB BneedsB
B
youB BtoB BbuildB BanB Bobject,B BthenB BloadB BtheB BfileB BintoB BtheB Bobject,B BandB
B
useB BspecificB BmethodsB BtoB BachieveB BtheB BdesiredB Bresults.B BItB BisB BtheB
B
graphB Bformat.B BTheyB BoftenB BletB BgraphB BedgesB BcontainB BaB Bweight,B BandB
B
thatB BisB BtheB BdistanceB BorB Bcost-relatedB BwithB Bit.B BForB Binstance,B BweB BhaveB
B
toB BtheB BfindRouteB BfunctionB BisB BtheB BDijkstra’sB Balgorithm,B BafterB BEdsgerB
B
Dijkstra,B BtheB BpackageB BfirstB Bwriter.B BTheB BjsB BsuffixB BisB BregularlyB
B
attachedB BtoB BpackageB BnamesB BtoB BspecifyB BthatB ByouB BcanB BwriteB BinB
B
JavaScript.B BSo,B BifB ByouB BwantB BtoB BuseB BthatB Bpackage,B BensureB BthatB BtheB
B
InB BthisB Bchapter,B BweB BcoveredB BtheB BModules.B BModulesB BgiveB BstructureB
toB BmoreB BextensiveB BprogramsB BbyB BdifferentiatingB BtheB BcodeB BintoB BbitsB
B
aB BmoduleB BwhichB ByouB BcanB BseeB BfromB BotherB Bmodules,B BandB BtheB
B
Exercise
WriteB BaB BJavaScriptB BprogramB BtoB BshowB BtheB BcurrentB BdayB BandB BtimeB BinB
theB BfollowingB Bformat.
B
Programming
B
TheB BprocessorB BisB BaB BvitalB BpartB BofB BaB BcomputerB BthatB BperformsB BtheB
individualB BstepsB BthatB BbalanceB BourB Bprograms.B BTheB BspeedB BlevelB BofB
B
dependsB
B onB
B B theB processor'sB
B speed.B
B AB
B lotB
B ofB
B programsB
B
theyB BmayB BinteractB BthroughB BaB BcomputerB BnetworkB BorB BdemandB BforB
B
dataB BfromB BtheB BhardB Bdisk,B BwhichB BisB BquiteB BslowerB BthanB BobtainingB BitB
B
fromB Bmemory.B BInB Bpart,B BtheB BoperatingB BsystemB BhandlesB BthisB BpartB
B
andB BwillB BchangeB BtheB BprocessorB BbetweenB BvariousB BprogramsB BthatB BareB
B
running.
B
Asynchronicity
action,B BresultsB BwillB BreturnB BwhenB BtheB BoperationB BcompletesB Bonly.B BNoB
B
otherB BactionB BwouldB BbeB BableB BtoB BtakeB BplaceB BduringB Bexecution.B BAnB
B
asynchronousB BmodelB BenablesB BseveralB BthingsB BtoB BoccurB BatB BtheB BsameB
B
time.B BWhenB BanB BactionB Bbegins,B BtheB BprogramB BdoesB BnotB BstopB
B
running.B BWhenB BtheB BtaskB Bcompletes,B BitB BnotifiesB BtheB BprogramB BandB
B
canB BaccessB BtheB BresultB B(forB Binstance,B BtheB BinformationB BreadB BfromB
B
disk).B
B YouB
B canB
B B differentiateB betweenB
B B synchronousB andB
B
thatB BobtainsB BtwoB BresourcesB BfromB BtheB BnetworkB BandB BthenB BunifiesB
B
theB Bresults.
B
InB BanB BasynchronousB Benvironment,B BtheB BrequestB BfunctionB BreturnsB
whenB BtheB BworkB Bcompletes.B BTheB BsimplestB BwayB BtoB BexecuteB BthisB BtaskB
B
isB BtoB BcallB BtheB BrequestsB BoneB BafterB Banother.B BItB BconsistsB BofB BtheB
B
drawbackB BthatB BbeginsB BtheB BsecondB BrequestB BonlyB BwhenB BtheB BfirstB BtaskB
B
completes.B BTheB BsumB BofB BbothB BresponseB BtimesB BwillB BbeB BtheB BtotalB
B
timeB Btaken.B BToB BsolveB BthisB BproblemB BinB BaB BsynchronousB Bsystem,B BstartB
B
addingB BthreadsB BofB Bcontrol.B BAB BthreadB BisB BaB BrunningB BprogramB BthatB
B
itsB BexecutionB BcouldB BbeB BrenderedB BwithB BotherB BprogramsB BthroughB BtheB
B
operatingB
B systemB
B BbecauseB modernB
B computersB
B haveB
B severalB
B
processors.B BAB BsecondB BthreadB BmayB BbeginB BtheB BsecondB Brequest,B BandB
B
thenB BtheB BtwoB BthreadsB BbothB BwaitB BforB BtheirB BresultsB BtoB Breturn,B BafterB
B
that,B
B theyB
B resynchronizeB
B BtoB unifyB
B bothB
B results.B
B InB
B theB
B
asynchronousB Bmodel,B BtheB BnetworkB BtimeB BisB BpartB BofB BtheB BtimelineB BforB
B
aB BnetworkB BactionB BnotionalB BcreatesB BaB BdivisionB BinB BtheB Btimeline.B BTheB
B
programB BthatB BcommencesB BtheB BactionB BdoesB BnotB BstopB Brunning,B BandB
B
thenB BtheB BactionB BoccursB BwithB Bit,B BitB BinformsB BtheB BprogramB BwhenB BitB
B
completes.
B
AnotherB BwayB BtoB BdetermineB BtheB BsimilaritiesB BisB BthatB BwaitingB BforB
tasksB BtoB BcompleteB BisB BindirectB BinB BtheB BsynchronousB Bmodel,B BwhileB BitB
B
Callbacks
andB BtheB BargumentB BisB BcalledB BaB BcallbackB Bfunction.B BWhenB BtheB BactionB
B
beginsB BandB Bends,B ByouB BshouldB BcallB BtheB BresultB BwithB BtheB BcallbackB
B
noteB BtoB BaB BstatedB Bnest.B BOurB BimplementationB BcallsB Bconsole.logB BsoB
B
thatB BweB BcanB BcheckB BifB BtheB BrequestB BhasB Barrived.B BNestsB BconsistB BofB BaB
B
nameB BpropertyB BthatB BholdsB BitsB Bname.B BTheB BfourthB BargumentB BstatedB
B
toB BtheB Bhandler,B Bdone,B BisB BaB BcallbackB BfunctionB BthatB BcallsB BwhenB BitB
B
hasB BcompletedB BtheB Btask.B BIfB ByouB BuseB BtheB Bhandler’sB BreturnB BvalueB BasB
B
theB BvalueB BofB BtheB Bresponse,B BthatB BmeansB BthatB BaB BrequestB BhandlerB
B
callbackB BreadyB BtoB BbeB BcalledB BuponB BwhenB BitB Bfinishes.B BInB BaB Bway,B
B
asynchronicityB BisB Bcontagious.B BAB BfunctionB BthatB BcallsB BaB BfunctionB BthatB
B
callbackB BtoB BdeliverB BitsB Bresult.B BCallingB BaB BcallbackB BisB Berror-proneB
B
Promises
makingB BpreparationsB BforB BaB BfunctionB BtoB BbeB BcalledB BatB BaB BcertainB
B
pointB BinB BtheB Bfuture,B BsendB BbackB BanB BobjectB BthatB BstandsB BforB BtheB
B
futureB Bevent.B BAB BpromiseB BisB BanB BasynchronousB BactionB BthatB BcanB
B
finishB BatB BsomeB BpointB BandB BprovideB Bvalue.B BItB BcanB BnotifyB BanyoneB
B
interestedB BwhenB BitsB BvalueB BisB Bavailable.B BTheB BsimplestB BwayB BtoB BbuildB
B
thatB BtheB BvalueB ByouB BsetB BenclosesB BinB BaB Bpromise.B BIfB BitB BisB BaB BpromiseB
B
Balready,B BitB Breturns.B BOtherwise,B BaB BnewB BpromiseB BwillB BbeB BcreatedB
BinstantlyB BwithB ByourB BvalueB BasB BaB Bresult.
storage(bigOak,B B"enemies")
.then(valueB B=>B Bconsole.log("Got",B Bvalue));
ThisB BasynchronousB BfunctionB BreturnsB BaB BsignificantB Bvalue.
Failure
callbackB BstyleB BmostB BconsistentB BissuesB BareB BthatB BitB BmakesB BitB BveryB
B
hardB BtoB BensureB BfailuresB BrevealB BcorrectlyB BtoB BtheB Bcallbacks.B BAB
B
generallyB BusedB BmethodB BisB BthatB BtheB BfirstB BargumentB BtoB BtheB BcallbackB
B
isB BusedB BtoB BspecifyB BtheB BfailedB Baction,B BandB BtheB BsecondB BhasB BtheB
B
valueB BprovidedB BbyB BtheB BactionB BwhenB BitB Bcompletes.B BSuchB BcallbackB
B
functionsB BalwaysB BcheckB BifB BtheyB BobtainB BanB BexceptionB BandB BensureB
B
functionsB BtheyB Bcall,B BareB BgivenB BtoB BtheB BcorrectB Bfunction.B BTheyB BcanB
B
reduceB BwhenB BitB BcompletesB BsuccessfullyB BorB BdeclinedB BwhenB BitB Bfails.B
B
CallB BReduceB BhandlersB BitB BonlyB BwhenB BtheB BtaskB BcompletesB BsuccessfullyB
B
declines.B BWhenB BanB BelementB BinB BaB BchainB BofB BasynchronousB BactionsB
B
fails,B BtheB BoutputB BofB BtheB BwholeB BchainB BdeclinesB BandB BnoB BsuccessB
B
handlersB BcallB BpastB BtheB BfailingB Bpoint.B BMuchB BlikeB BsolvingB BaB BpromiseB
B
producesB BaB Bvalue,B BrejectingB BoneB BalsoB BprovideB Bone,B BoftenB BcalledB BtheB
B
rejectionB Breason.B BIfB BanB BexceptionB BinB BaB BhandlerB BfunctionB BcreatesB
B
theB Brejection,B BuseB BtheB BexceptionB BvalueB BasB BtheB Breason.B BComparably,B
B
whenB BaB BhandlerB BsendsB BbackB BaB BrejectedB Bpromise,B BthatB BrejectionB
B
goesB BintoB BtheB BnextB Bpromise.B BThere’sB BaB BPromise.B BRejectB BfunctionB
B
IfB BaB BcatchB BhandlerB BoutputB BanB Berror,B BtheB BnewB BpromiseB BisB BequallyB
declined.B BInB Bshorthand,B BthenB BalsoB BtakeB BaB BdeclineB BhandlerB BasB BaB
B
secondB Bargument,B BsoB ByouB BshouldB BinstallB BtheB BtwoB BtypesB BofB BhandlersB
B
inB BanB BindividualB BmethodB Bcall.B BAB BfunctionB BsentB BtoB BtheB BPromiseB
B
function,B BwhichB BitB BcanB BuseB BtoB BdeclineB BtheB BnewB Bpromise.B BTheB
B
chainsB BofB BpromiseB BvaluesB BdevelopedB BbyB BcallsB BtoB BthenB BandB BcatchB
B
linkB BconsistsB BofB BeitherB BbothB BorB BaB BsuccessB BhandlerB BorB BaB BrejectionB
B
handlerB BrelatedB BtoB Bit.B BHandlersB BthatB BdoB BnotB BmatchB BtheB BtypeB BofB
B
outputB Bdeclined.B BButB BthoseB BthatB BmatchB BgetsB Bcalled,B BandB BtheirB
B
outputB BdecidesB BwhatB BtypeB BofB BvalueB BcomesB Bnext,B BsuccessB BwhenB BitB
B
sendsB BbackB BaB Bnon-promiseB Bvalue,B BrejectionB BwhenB BitB BoutputB BanB
B
exception,B BandB BtheB BresultB BofB BaB BpromiseB BwhenB BitB BsendsB BbackB BoneB
B
ofB Bthose.
B
viableB BforB BaB BsignalB BtoB BbeB BtransferredB BbutB BgotB Bdeclined.B BOften,B
B
BtransmissionB BfailuresB BareB BunexpectedB Baccidents,B BlikeB BaB Bcar’sB
BheadlightB BobstructB BtheB BlightB Bsignals,B BandB BresendingB BtheB BrequestB
BcouldB BmakeB BitB Bsucceed.B BSo,B Blet’sB BcreateB BourB BrequestB Bfunction,B BandB
BconsequentlyB BretryB BtheB BsendingB BofB BtheB BrequestB BmoreB BtimeB BbeforeB
BitB Bstops.B BAnd,B BsinceB BweB BhaveB BestablishedB BthatB BpromisesB BareB Bgood,B
Bwe’llB BalsoB BensureB BourB BrequestB BfunctionB BsendsB BbackB BaB Bpromise.B
BWhenB BitB BcomesB BtoB BwhatB BtheyB BcanB Bindicate,B BpromisesB BandB BcallbacksB
BareB Bequal.B BCallback-basedB BfunctionsB BareB BenclosedB BtoB BuncoverB BaB
Bpromise-basedB BlayoutB BandB BviceB Bversa.B BEvenB BwhenB BaB BrequestB BandB
BitsB BreplyB BconveyB Bsuccessfully,B BtheB BreplyB BcouldB BspecifyB Bfailure,B BforB
Binstance,B BifB BtheB BrequestB BtriesB BtoB ButilizeB BaB BrequestB BtypeB BthatB BhasB
BnotB BbeenB BdescribedB BorB BtheB BhandlerB BoutputB BanB Berror.B BToB BaidB Bthis,B
BsendB BandB BdefineRequestTypeB BfollowB BtheB BconventionB BdeclaredB
Bearlier,B BwhereB BtheB BfirstB BargumentB BsentB BtoB BcallbacksB BisB BtheB BreasonB
BforB BfailureB BifB Bany,B BandB BtheB BsecondB BisB BtheB BDefiniteB Bresult.B BTheyB BareB
BinterpretedB BtoB BpromiseB BresolutionB BandB BrejectionB BbyB BourB Bwrapper.
classB BTimeoutB BextendsB BErrorB B{}
functionB Brequest(nest,B Btarget,B Btype,B Bcontent)B B{
returnB BnewB BPromise((resolve,B Breject)B B=>B B{
letB BdoneB B=B Bfalse;
functionB Battempt(n)B B{
nest.send(target,B Btype,B Bcontent,B B(failed,B Bvalue)B B=>B B{
doneB B=B Btrue;
ifB B(failed)B Breject(failed);
elseB Bresolve(value);
});
setTimeout(()B B=>B B{
ifB B(done)B Breturn;
elseB BifB B(nB B<B B3)B Battempt(nB B+B B1);
elseB Breject(newB BTimeout("TimedB Bout"));
},B B250);
}
attempt(1);
});
}
BecauseB BpromisesB BcanB BbeB BacceptedB BorB BdeclinedB BonceB Bonly,B BitB BwillB
Bwork.B BTheB BfirstB BtimeB BresolveB BorB BrejectB BcallB BdecidesB BtheB BresultB BofB
BtheB Bpromise,B BandB BanyB BotherB Bcalls,B BareB Bdisregarded.B BToB BcreateB BanB
BasynchronousB Bloop,B BforB BtheB Bretries,B BuseB BaB BrecursiveB Bfunction,B BanB
BefficientB BloopB BdoesB BnotB BallowB BusB BtoB BstopB BandB BwaitB BforB BanB
BasynchronousB Baction.B BTheB BattemptB BfunctionB BcreatesB BaB BsingleB
BattemptB BtoB BtransferB BaB Brequest.B BItB BalsoB BspecifiesB BaB BtimeoutB Bthat,B BifB
BthereB BisB BcomebackB BresponseB BafterB B250B Bmilliseconds,B BbeginsB BtheB
BnextB BattemptB Bor,B BifB BitB BisB BtheB BfourthB Btry,B BdeclinesB BtheB BpromiseB
BwithB BanB BinstanceB BofB BTimeoutB BbeingB BtheB Breason.B BRetryingB BeachB
Bquarter-secondB BandB BstopsB BwhenB BthereB BisB BnoB BresponseB BafterB BaB
BsecondB BisB BcertainlyB BarbitraryB BifB BtheB BrequestB BshowsB Bup,B BbutB BtheB
BhandlerB BtakesB BlongerB BforB BrequestsB BtoB BtransferB BseveralB Btimes.B BCreateB
ByourB BhandlersB BwithB BthatB BproblemB BinB Bmind,B BandB BcoupledB BmessagesB
Promise.resolveB BisB BusedB BtoB BtransformB BtheB BreturnedB BvalueB BbyB BtheB
BhandlerB BtoB BaB BpromiseB BifB BitB BisB BnotB Bready.
Collections of promises
BB BB
EveryB BnestB BcomputerB BstoresB BanB BarrayB BofB BotherB BnestsB BinsideB
BtransmissionB BdistanceB BinB BitsB Bneighbor’sB Bproperty.B BToB BexamineB
BwhichB BisB Breachable,B BwriteB BaB BfunctionB BthatB BtriesB BtoB BtransferB BaB
B"ping"B BrequestB B(requestB BthatB BdemandsB BaB Bresponse)B BtoB BallB BofB BthemB
BandB BcheckB BforB BwhichB BonesB BcomeB Bback.B BIfB Byou'reB BworkingB BwithB BaB
BgroupB BofB BpromisesB BrunningB BatB Bonce,B BtheB BPromise.allB BfunctionB BisB
BveryB Bimportant.B BItB BsendsB BbackB BaB BpromiseB BthatB BholdsB BonB BforB BallB BofB
BtheB BpromisesB BinB BtheB BarrayB BtoB BreconcileB BandB BthenB BsettleB BtoB BanB
BarrayB BofB BtheB BvaluesB BthatB BtheseB BpromisesB Bprovided.B BIfB BanyB BpromiseB
BisB Bdeclined,B BtheB BresultB BofB BPromise.allB BisB BalsoB Bdeclined.
requestType("ping",B B()B B=>B B"pong");
functionB BavailableNeighbors(nest)B B{
letB BrequestsB B=B Bnest.neighbors.map(neighborB B=>B B{
returnB Brequest(nest,B Bneighbor,B B"ping")
.then(()B B=>B Btrue,B B()B B=>B Bfalse);
});
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[];
});
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);
});
message.
B
returnB Bnull;
}
YouB BcanB BnowB BcreateB BaB BfunctionB BthatB BcanB BsendB BmessagesB BtoB BlongB
distance.B BIfB BtheB BmessageB BisB BattachedB BtoB BaB BdirectB Bneighbor,B BitB BisB
B
conveyedB BasB Busual.B BIfB Bnot,B BitB BisB BwrappedB BinB BanB BobjectB BandB
B
transferredB BtoB BaB BneighborB BcloserB BtoB BtheB Btarget,B BthroughB BtheB
B
"route"B BrequestB Btype,B BthatB BwillB BmakeB BthatB BneighborB BrepeatB BtheB
B
sameB Bcharacter.
B
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());
}
returnB Bnext();
}
Object.keysB BcannotB BworkB BonB BconnectionsB BbecauseB BitB BisB BaB BMap.B BItB
containsB BaB BkeyB Bmethod,B BbutB BthatB BsendsB BbackB BanB BiteratorB BinsteadB
B
ofB BanB Barray.B BAnB BiteratorB BcanB BbeB BtransformedB BtoB BanB BarrayB BusingB
B
togetherB BinB BunclearB Bways.B BNowB ByouB BneedB BaB BrecurringB BfunctionB BtoB
B
model,B BitB BisB BeasyB BtoB Bexpress.B BJavaScriptB BalsoB BletsB ByouB BwriteB
B
asyncB BfunctionB BisB BaB BfunctionB BthatB BcompletelyB BbringB BbackB BaB
B
promiseB BandB BthatB BcanB BwaitB BforB BotherB BpromisesB BinB BaB BsynchronousB
B
AnB BasyncB BfunctionB BisB BmarkedB BwithB BtheB BwordB BasyncB BandB BthenB BtheB
functionB Bkeyword.B BMethodsB BcanB BalsoB BbecomeB BasyncB BbyB BwritingB
B
asyncB BbeforeB BtheirB Bname.B BWhenB BtheB BfunctionB BorB BmethodB BisB Bcalled,B
B
itB BbringsB BbackB BaB Bpromise.B BWhenB BtheB BbodyB BreturnsB Bsomething,B BthatB
B
promiseB BisB Bsettled.B BIfB BitB BoutputsB BanB Bexception,B BtheB BpromiseB BisB
B
declined.B BWithinB BanB BasyncB Bfunction,B BtheB BwordB BawaitB BisB BsetB BinB
B
frontB BofB BanB BexpressionB BtoB BawaitB BaB BpromiseB BtoB BgetB BsettledB BandB
B
cannotB BrunB BfromB BstartB BtoB BfinishB BatB Bonce,B BbutB BitB BcanB BbeB BfrozenB BatB
B
pointsB BandB BcanB BrestartB Blater.B BForB Bnon-trivialB BasynchronousB Bcode,B
B
Generators
AsyncB BfunctionsB BdoB BnotB BhaveB BtoB BbeB BpausedB BandB BthenB BresumedB
again.B BJavaScriptB BconsistsB BofB BaB BfeatureB BcalledB BgeneratorB Bfunctions.B
B
TheseB BareB BidenticalB BbutB BdoB BnotB BcontainB BtheB Bpromises.B BWhenB ByouB
B
callB BaB BfunctionB BwithB Bfunction*B B(putB BanB BasteriskB BafterB BtheB BwordB
B
function),B BitB BchangesB BtoB BaB Bgenerator.B BWhenB ByouB BcallB BaB Bgenerator,B
B
function*B Bpowers(n)B B{
forB B(letB BcurrentB B=B Bn;;B BcurrentB B*=B Bn)B B{
yieldB Bcurrently;
}
}
//B B→B B3
//B B→B B9
//B B→B B27
Normally,B BifB ByouB BcallB Bpowers,B BtheB BfunctionB BisB BfrozenB BatB BtheB
beginning.B BEachB BtimeB ByouB BcallB BnextB BonB BtheB Biterator,B BtheB BfunctionB
B
willB BrunB BuntilB BitB BhitsB BaB ByieldB Bexpression,B BwhichB BwillB BpauseB BitB BandB
B
makeB BtheB ByieldedB BvalueB BtheB BnextB BvalueB BprovidedB BbyB BtheB Biterator.B
B
There’sB BnoB BneedB BtoB BbuildB BanB BobjectB BtoB BholdB BtheB BiterationB Bstate,B
BandB BgeneratorsB BstoreB BtheirB BlocalB BstateB BimmediatelyB BandB BtheyB ByieldB
BeveryB Btime.B BThisB ByieldB BexpressionB BcanB BhappenB BonlyB BdirectlyB BwithinB
BtheB BgeneratorB BfunctionB BandB BnotB BinB BanB BinnerB BfunctionB BthatB ByouB BsetB
BwithinB Bit.B BTheB BgeneratorB BsavesB BwhenB Byielding.B BThisB BisB BitsB BlocalB
BenvironmentB BandB BtheB BpositionB BwhereB BitB Byields.B BAnB BasyncB BfunctionB
BisB BaB BuniqueB BkindB BofB Bgenerator.B BItB BcreatesB BaB BpromiseB BwhenB Bit’sB
Bcalled,B BwhichB BresolvesB BwhenB BitB BcompletesB BandB BdeclinesB BwhenB BitB
BoutputsB BanB Bexception.B BAnytimeB BitB ByieldsB BaB Bpromise,B BtheB BresultB BofB
BthatB BpromiseB BwillB BbeB BtheB BresultB BofB BtheB BawaitB Bexpression.
The event loop
BB BB
tryB B{
setTimeout(()B B=>B B{
throwB BnewB BError("Woosh");
},B B20);
}B BcatchB B(_)B B{
//B BThisB BwillB BnotB Brun
console.log("Caught!");
}
NoB BmatterB BhowB BeventsB BlikeB BtimeoutsB BorB BincomingB BrequestsB Boccur,B
aB BJavaScriptB BenvironmentB BrunsB BoneB BprogramB BatB Bonce.B BWhenB
B
there’sB BnothingB BtoB Bdo,B BtheB BloopB Bstops.B BButB BasB BeventsB BcomeB Bin,B
B
theyB BareB BattachedB BtoB BaB Bqueue,B BandB BtheirB BcodeB BperformsB BoneB BafterB
B
other.B BBecauseB BtwoB BthingsB BdoB BnotB BrunB BatB Bonce,B Bslow-runningB BcodeB
B
mayB BholdB BupB BtheB BhandlingB BofB BotherB Bevents.B BTheB BbelowB BexampleB
B
setsB BaB BtimeoutB BbutB BalsoB BlingersB BuntilB BafterB BtheB Btimeout’sB BfixedB
B
Promise.resolve("Done").then(console.log);
console.log("MeB Bfirst!");
//B B→B BMeB Bfirst!
//B B→B BDone
AsynchronousB Bbugs
WhenB ByouB BrunB ByourB BprogramB Bsynchronously,B BthereB BisB BnoB BgivenB
occurringB
B B transformationB besidesB
B theB
B onesB
B thatB
B programB
B
themselves.B BButB BwhenB ByouB BrunB BanB BasynchronousB Bprogram,B BthisB BisB
B
otherB BcodeB BcanB Butilize.B BBelowB BisB BanB Billustration.B BOneB BofB BourB
B
crow’sB BfavoritesB BisB BtoB BenumerateB BtheB BnumberB BofB BchicksB BthatB BhatchB
B
duringB BtheB BvillageB BeachB Byear.B BNestsB BkeepB BthisB BcountB BwithinB BtheirB
B
storageB Bbulbs.B BTheB BbelowB BcodeB BtriesB BtoB BtallyB BtheB BcountsB BfromB
B
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}`);
});
Summary
waitingB BforB BactionB BthatB BrunsB BforB BaB BlongB BtimeB BwithoutB BgivingB BtheB
B
programB
B problemsB
B BthroughoutB BtheB operations.B
B JavaScriptB
B
callbacks,B BfunctionsB BwhichB BtoB BcallB BwhenB BactionsB Bend.B BWeB BtouchedB
B
onB BtheB BeventB BloopB BasB Bwell.B BAnB BeventB BloopB BcreatesB BaB BplanB BforB
B
suchB BcallbacksB BtoB BbeB BcalledB BwhenB BitB BisB Btime,B BoneB BafterB Banother,B BtoB
B
avoidB Boverlapping.
B
Exercise
Solution
Chapter 13: Parsing
BB BB
language.B BWeB BwillB BcreateB BaB BprogrammingB BlanguageB BcalledB BEgg.B BAB
B
small,B BsimpleB BlanguageB BisB ByetB BstrongB BenoughB BtoB BexpressB BanyB
B
functions.
B
Parsing
TheB BnoticeableB BpartB BofB BaB BprogrammingB BlanguageB BisB BtheB BnotationB BorB
syntax.B BAB BparserB BisB BaB BprogramB BthatB BreadsB BtheB BtextB BandB BprovidesB
B
aB BdataB BlayoutB BthatB BreflectsB BtheB BlayoutB BofB BtheB BprogramB BwithinB BthatB
B
text.B BIfB BtheB BtextB BrefusesB BtoB BcreateB BaB BvalidB Bprogram,B BtheB BparserB
B
wouldB BindicateB BanB Berror.B BOurB BlanguageB BwouldB BcontainB BpreciseB BandB
B
uniformB Bsyntax.B BEverythingB BincludedB BinB BEggB BisB BanB Bexpression.B BAnB
B
application.B BUtilizeB BApplicationsB BforB BfunctionB BcallsB BandB BasB BwellB BasB
B
ToB BkeepB BtheB BsimpleB Bparser,B BstringsB BwithinB BtheB BEggB BdoB BnotB BsupportB
backslashB Bescapes.B BAB BstringB BisB BaB BsuccessionB BofB BcharactersB BthatB BareB
B
containB BanyB BcharacterB BthatB Bisn'tB BwhitespaceB BandB BthatB BdoB BnotB
B
containB BaB BuniqueB BmeaningB BinB BtheB Bsyntax.B BWriteB BapplicationsB BinB
B
byB Bcommas.
B
do(define(x,B B10),
if(>(x,B B5),
print("large"),
print("small")))
TheB BconsistencyB BofB BtheB BEggB BlanguageB BmeansB BthatB BoperatorsB BinB
BJavaScriptB B(likeB BtheB B>)B BareB BcalledB BbindingsB BinB BthisB Blanguage,B
zeroB BblockB Bconcept,B BsoB BaB BconstructB BisB BneededB BtoB BrepresentB
B
runningB BseveralB BthingsB BinB Bsuccession.B BTheB BdataB BlayoutB BtheB BparserB
B
oneB BcontainsB BaB BtypeB BofB BpropertyB BsignifyingB BtheB BkindB BofB BexpressionB
B
itB BisB BandB BseveralB BotherB BpropertiesB BtoB BdetermineB BitsB Bcontent.B
B
ExpressionsB BofB BtypeB B"value"B BmeanB BstringsB BorB Bnumbers.B BTheirB BvalueB
B
propertyB BconsistsB BofB BtheB BstringB BorB BnumberB BvalueB BthatB BtheyB BstandB
B
for.B BUseB BexpressionsB BofB BtypeB B"word"B BforB BidentifiersB B(names).B BTheseB
B
typesB BofB BobjectsB BcontainB BaB BnameB BpropertyB BthatB BholdsB BtheB
B
identifier’sB BtitleB BasB BaB Bstring.B BAndB BthenB BtheB B"apply"B BexpressionsB
B
citesB BtheB BappliedB Bexpression,B BtogetherB BwithB BanB BargsB BpropertyB BthatB
B
TheB B>(x,B B5)B BpartB BofB BtheB BnewB BprogramB BwouldB BbeB BlikeB Bthis:
{
type:B B"apply",
operator:B B{type:B B"word",B Bname:B B">"},
args:B B[
{type:B B"word",B Bname:B B"x"},
{type:B B"value",B Bvalue:B B5}
]
}
WeB BdescribeB BaB BfunctionB BparseExpression,B BwhichB BrecognizeB BaB BstringB
asB BinputB BandB BsendB BbackB BanB BobjectB BthatB BconsistsB BofB BtheB BdataB
B
layoutB BforB BtheB BexpressionB BatB BtheB BbeginningB BofB BtheB Bstring,B BtogetherB
B
withB BtheB BstringB BpartB BleftB BafterB BparsingB BthisB Bexpression.B BWhenB ByouB
B
ThisB BtextB BcouldB BconsistB BofB BmoreB BargumentsB BorB BtheB BclosingB
B
functionB BskipSpace(string)B B{
letB BfirstB B=B Bstring.search(/\S/);
ifB B(firstB B==B B-1)B BreturnB B"";
returnB Bstring.slice(first);
}
TheB Bevaluator
TheB BevaluatorB BisB BusedB BtoB BrunB BtheB BsyntaxB BtreeB BforB BaB Bprogram.B BSetB
itB BaB BsyntaxB BtreeB BandB BaB BscopeB BobjectB BthatB BrelateB BnamesB BwithB
B
values,B BandB BitB BwillB BaccessB BtheB BexpressionB BthatB BtheB BtreeB BstandsB BforB
B
TheB BevaluatorB BcontainsB BcodesB BforB BeveryB BexpressionB Btype.B BAB BliteralB
valueB BexpressionB BprovidesB BitsB Bvalue.B BToB Bbind,B BcheckB BifB BitB BdescribesB
B
inB BtheB BscopeB Band,B BifB Byes,B BgetB BtheB BvalueB BofB BtheB Bbinding.B BIfB BitB
B
containsB BaB BuniqueB BformB BthatB BdoesB BnotB BaccessB Banything,B BandB ByetB
B
thatB BinfluencesB BtheB Bform.B BIfB BtheB BcallB BisB Btypical,B BaccessB BtheB
B
operator,B BdetermineB BifB BitB BisB BaB Bfunction,B BandB BcallB BitB BwithB BtheB
B
valuesB BtoB BstandB BforB BtheB BvalueB BofB BEgg’sB Bfunction.B BTheB BrecursiveB
B
layoutB BofB BevaluatingB BisB BaB BsimilarB BlayoutB BofB BtheB Bparser,B BandB BtheB
B
twoB BmirrorB BtheB BlayoutB BofB BtheB Blanguage.B BYouB BcanB BcombineB BtheB
B
separatingB BthemB BgivesB BaB BclearerB BofB BtheB Bprogram.B BItB BisB BallB ByouB
B
Special forms BB
TheB BspecialFormsB BobjectB BdescribesB BuniqueB BsyntaxB BinB BEgg.B BItB BrelatesB
wordsB BwithB BfunctionsB BthatB BaccessB BsuchB Bforms.B BItB BisB BpresentlyB
B
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");
}
//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");
}
valuesB BareB BinB BaccordanceB BtoB BtheB BvaluesB BthoseB BboundedB Bbindings.B
B
BelowB BisB BanB BillustrationB BofB BanB BobjectB BtoB BstandB BforB BglobalB Bscope.B
B
ToB BenableB BtheB ButilizationB BofB BtheB BearlierB BdescribedB BifB Bconstruct,B BtheB
B
BooleanB BvaluesB Bonly,B BallB ByouB BneedB BtoB BdoB BisB BtoB BbindB BtwoB BnamesB BtoB
B
functionB BonB BfewB BoperatorB BfunctionsB BwithinB BaB Bloop,B BandB BnotB BstatingB
B
forB B(letB BopB BofB B["+",B B"-",B B"*",B B"/",B B"==",B B"<",B B">"])B B{
topScope[op]B B=B BFunction("a,B Bb",B B`returnB BaB B${op}B Bb;`);
}
weB BwillB BencloseB Bconsole.logB BinB BaB BfunctionB BtoB BoutputB BtheB Bvalues
andB BcallB BitB Bprint.
topScope.printB B=B BvalueB B=>B B{
console.log(value);
returnB Bvalue;
};
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))
`);
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");
}
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");
}
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(`
WriteB BaB BJavaScriptB BfunctionB BtoB BcalculateB BtheB BfactorsB BofB BaB BpositiveB
Binteger.
Solution
Conclusion
willB BhelpB ByouB BtoB BunderstandB BandB BpracticeB BtheB BseveralB BJavaScriptB
B
ofB Bvariables,B BinventB Btypes,B BandB BsoB Bon.B BAndB BwhileB BedgingB BtowardB
B
theB BendB BofB BtheB Bcourse,B ByouB BwillB BhaveB BanB BexcellentB BunderstandingB
B
ofB BtheB BJavaScriptB BlanguageB BasB ByouB BwillB BhaveB BlearnedB BJavaScriptB
B
andB Bforms,B ByouB BwillB BunderstandB BtheB BbasicsB BofB BjQuery,B BframesB BandB
B
debuggingB Bscripts.B BTheB BbestB BadviceB BtoB BgiveB BaB BprogrammerB BisB BtoB
B
keepB BpracticingB BbecauseB BthatB BisB BtheB BonlyB BwayB ByouB BcanB BmasterB
B