Onprogramming
BesidesexplainingJavaScript,Iwillintroducethebasicprinciplesofprogramming.Programming,itturnsout,ishard.Thefundamentalrulesaresimple andclear,butprogramsbuiltontopoftheserulestendtobecomecomplex enoughtointroducetheirownrulesandcomplexity.You’rebuildingyourown maze,inaway,andyoucaneasilygetlostinit.
Therewillbetimeswhenreadingthisbookfeelsterriblyfrustrating.Ifyou arenewtoprogramming,therewillbealotofnewmaterialtodigest.Muchof thismaterialwillthenbe combined inwaysthatrequireyoutomakeadditional connections.
Itisuptoyoutomakethenecessaryeffort.Whenyouarestrugglingto followthebook,donotjumptoanyconclusionsaboutyourowncapabilities. Youarefine—youjustneedtokeepatit.Takeabreak,rereadsomematerial, andmakesureyoureadandunderstandtheexampleprogramsandexercises. Learningishardwork,buteverythingyoulearnisyoursandwillmakefurther learningeasier.
Whenactiongrowsunprofitable,gatherinformation;wheninformationgrowsunprofitable,sleep.
—UrsulaK.LeGuin,TheLeftHandofDarkness
Aprogramismanythings.Itisapieceoftexttypedbyaprogrammer,itis thedirectingforcethatmakesthecomputerdowhatitdoes,itisdatainthe computer’smemory,andatthesametimeitcontrolstheactionsperformed onthismemory.Analogiesthattrytocompareprogramstofamiliarobjects tendtofallshort.Asuperficiallyfittingoneistocompareaprogramtoa machine—lotsofseparatepartstendtobeinvolved,andtomakethewhole thingtick,wehavetoconsiderthewaysinwhichthesepartsinterconnectand contributetotheoperationofthewhole.
Acomputerisaphysicalmachinethatactsasahostfortheseimmaterial machines.Computersthemselvescandoonlystupidlystraightforwardthings. Thereasontheyaresousefulisthattheydothesethingsatanincredibly highspeed.Aprogramcaningeniouslycombineanenormousnumberofthese simpleactionstodoverycomplicatedthings.
Aprogramisabuildingofthought.Itiscostlesstobuild,itisweightless, anditgrowseasilyunderourtypinghands.Butasaprogramgrows,sodoes itscomplexity.Theskillofprogrammingistheskillofbuildingprograms thatdon’tconfuseyourself.Thebestprogramsarethosethatmanagetodo somethinginterestingwhilestillbeingeasytounderstand.
Someprogrammersbelievethatthiscomplexityisbestmanagedbyusing onlyasmallsetofwell-understoodtechniquesintheirprograms.Theyhave composedstrictrules(“bestpractices”)prescribingtheformprogramsshould haveandcarefullystaywithintheirsafelittlezone.
Thisisnotonlyboring,itisineffective.Newproblemsoftenrequirenew solutions.Thefieldofprogrammingisyoungandstilldevelopingrapidly,and itisvariedenoughtohaveroomforwildlydifferentapproaches.Thereare manyterriblemistakestomakeinprogramdesign,andyoushouldgoahead andmakethematleastoncesothatyouunderstandthem.Asenseofwhata goodprogramlookslikeisdevelopedwithpractice,notlearnedfromalistof rules.
Whylanguagematters
Inthebeginning,atthebirthofcomputing,therewerenoprogramminglanguages.Programslookedsomethinglikethis:
Thisisaprogramtoaddthenumbersfrom1to10togetherandprintthe result: 1+2+...+10=55.Itcouldrunonasimplehypotheticalmachine. Toprogramearlycomputers,itwasnecessarytosetlargearraysofswitches intherightpositionorpunchholesinstripsofcardboardandfeedthemto thecomputer.Youcanimaginehowtediousanderror-pronethisprocedure was.Evenwritingsimpleprogramsrequiredmuchclevernessanddiscipline. Complexoneswerenearlyinconceivable.
Ofcourse,manuallyenteringthesearcanepatternsofbits(theonesand zeros)didgivetheprogrammeraprofoundsenseofbeingamightywizard. Andthathastobeworthsomethingintermsofjobsatisfaction.
Eachlineofthepreviousprogramcontainsasingleinstruction.Itcouldbe writteninEnglishlikethis:
1. Storethenumber0inmemorylocation0. 3
2. Storethenumber1inmemorylocation1.
3. Storethevalueofmemorylocation1inmemorylocation2.
4. Subtractthenumber11fromthevalueinmemorylocation2.
5. Ifthevalueinmemorylocation2isthenumber0,continuewithinstruction9.
6. Addthevalueofmemorylocation1tomemorylocation0.
7. Addthenumber1tothevalueofmemorylocation1.
8. Continuewithinstruction3.
9. Outputthevalueofmemorylocation0.
Althoughthatisalreadymorereadablethanthesoupofbits,itisstillrather obscure.Usingnamesinsteadofnumbersfortheinstructionsandmemory locationshelps:
Set“total”to0. Set“count”to1. [loop]
Set“compare”to“count”. Subtract11from“compare”. If“compare”iszero,continueat[end].
Add“count”to“total”. Add1to“count”. Continueat[loop]. [end]
Output“total”.
Canyouseehowtheprogramworksatthispoint?Thefirsttwolinesgive twomemorylocationstheirstartingvalues: total willbeusedtobuildupthe resultofthecomputation,and count willkeeptrackofthenumberthatweare currentlylookingat.Thelinesusing compare areprobablythemostconfusing ones.Theprogramwantstoseewhether count isequalto11todecidewhether itcanstoprunning.Becauseourhypotheticalmachineisratherprimitive,it canonlytestwhetheranumberiszeroandmakeadecisionbasedonthat. Itthereforeusesthememorylocationlabeled compare tocomputethevalue of count-11 andmakesadecisionbasedonthatvalue.Thenexttwolines addthevalueof count totheresultandincrement count by1everytimethe programdecidesthat count isnot11yet. HereisthesameprograminJavaScript: 4
lettotal=0,count=1; while(count<=10){ total+=count; count+=1; }
console.log(total); //→55
Thisversiongivesusafewmoreimprovements.Mostimportantly,thereis noneedtospecifythewaywewanttheprogramtojumpbackandforth anymore—the while constructtakescareofthat.Itcontinuesexecutingthe block(wrappedinbraces)belowitaslongastheconditionitwasgivenholds. Thatconditionis count<=10,whichmeans“thecountislessthanorequal to10”.Wenolongerhavetocreateatemporaryvalueandcomparethatto zero,whichwasjustanuninterestingdetail.Partofthepowerofprogramming languagesisthattheycantakecareofuninterestingdetailsforus.
Attheendoftheprogram,afterthe while constructhasfinished,the console .log operationisusedtowriteouttheresult.
Finally,hereiswhattheprogramcouldlooklikeifwehappenedtohave theconvenientoperations range and sum available,whichrespectivelycreatea collectionofnumberswithinarangeandcomputethesumofacollectionof numbers:
console.log(sum(range(1,10))); //→55
Themoralofthisstoryisthatthesameprogramcanbeexpressedinbothlong andshort,unreadableandreadableways.Thefirstversionoftheprogramwas extremelyobscure,whereasthislastoneisalmostEnglish: log the sum ofthe range ofnumbersfrom1to10.(Wewillseein laterchapters howtodefine operationslike sum and range.)
Agoodprogramminglanguagehelpstheprogrammerbyallowingthemto talkabouttheactionsthatthecomputerhastoperformonahigherlevel. Ithelpsomitdetails,providesconvenientbuildingblocks(suchas while and console.log),allowsyoutodefineyourownbuildingblocks(suchas sum and range),andmakesthoseblockseasytocompose.
WhatisJavaScript?
JavaScriptwasintroducedin1995asawaytoaddprogramstowebpagesinthe NetscapeNavigatorbrowser.Thelanguagehassincebeenadoptedbyallother majorgraphicalwebbrowsers.Ithasmademodernwebapplicationspossible—
thatis,applicationswithwhichyoucaninteractdirectlywithoutdoingapage reloadforeveryaction.JavaScriptisalsousedinmoretraditionalwebsitesto providevariousformsofinteractivityandcleverness.
ItisimportanttonotethatJavaScripthasalmostnothingtodowiththe programminglanguagenamedJava.Thesimilarnamewasinspiredbymarketingconsiderationsratherthangoodjudgment.WhenJavaScriptwasbeing introduced,theJavalanguagewasbeingheavilymarketedandwasgaining popularity.Someonethoughtitwasagoodideatotrytoridealongonthis success.Nowwearestuckwiththename.
AfteritsadoptionoutsideofNetscape,astandarddocumentwaswrittento describethewaytheJavaScriptlanguageshouldworksothatthevariouspieces ofsoftwarethatclaimedtosupportJavaScriptcouldmakesuretheyactually providedthesamelanguage.ThisiscalledtheECMAScriptstandard,after theEcmaInternationalorganizationthatconductedthestandardization.In practice,thetermsECMAScriptandJavaScriptcanbeusedinterchangeably— theyaretwonamesforthesamelanguage.
Therearethosewhowillsay terrible thingsaboutJavaScript.Manyofthese thingsaretrue.WhenIwasrequiredtowritesomethinginJavaScriptforthe firsttime,Iquicklycametodespiseit.ItwouldacceptalmostanythingItyped butinterpretitinawaythatwascompletelydifferentfromwhatImeant.This hadalottodowiththefactthatIdidnothaveacluewhatIwasdoing,of course,butthereisarealissuehere:JavaScriptisridiculouslyliberalinwhat itallows.Theideabehindthisdesignwasthatitwouldmakeprogrammingin JavaScripteasierforbeginners.Inactuality,itmostlymakesfindingproblems inyourprogramsharderbecausethesystemwillnotpointthemouttoyou.
Thisflexibilityalsohasitsadvantages,though.Itleavesroomfortechniques thatareimpossibleinmorerigidlanguagesandmakesforapleasant,informal styleofprogramming.Afterlearningthelanguageproperlyandworkingwith itforawhile,Ihavecometoactually like JavaScript.
TherehavebeenseveralversionsofJavaScript.ECMAScriptversion3was thewidelysupportedversionduringJavaScript’sascenttodominance,roughly between2000and2010.Duringthistime,workwasunderwayonanambitious version4,whichplannedanumberofradicalimprovementsandextensionsto thelanguage.Changingaliving,widelyusedlanguageinsucharadicalway turnedouttobepoliticallydifficult,andworkontheversion4wasabandoned in2008.Amuchlessambitiousversion5,whichmadeonlysomeuncontroversialimprovements,cameoutin2009.In2015,version6cameout,amajor updatethatincludedsomeoftheideasplannedforversion4.Sincethenwe’ve hadnew,smallupdateseveryyear.
ThefactthatJavaScriptisevolvingmeansthatbrowsershavetoconstantly
keepup.Ifyou’reusinganolderbrowser,itmaynotsupporteveryfeature. Thelanguagedesignersarecarefultonotmakeanychangesthatcouldbreak existingprograms,sonewbrowserscanstillrunoldprograms.Inthisbook, I’musingthe2023versionofJavaScript.
WebbrowsersarenottheonlyplatformsonwhichJavaScriptisused.Some databases,suchasMongoDBandCouchDB,useJavaScriptastheirscripting andquerylanguage.Severalplatformsfordesktopandserverprogramming, mostnotablytheNode.jsproject(thesubjectof Chapter20),provideanenvironmentforprogrammingJavaScriptoutsideofthebrowser.
Code,andwhattodowithit
Code isthetextthatmakesupprograms.Mostchaptersinthisbookcontain quitealotofcode.Ibelievereadingcodeandwritingcodeareindispensable partsoflearningtoprogram.Trytonotjustglanceovertheexamples—read themattentivelyandunderstandthem.Thismaybeslowandconfusingat first,butIpromisethatyou’llquicklygetthehangofit.Thesamegoesfor theexercises.Don’tassumeyouunderstandthemuntilyou’veactuallywritten aworkingsolution.
IrecommendyoutryyoursolutionstoexercisesinanactualJavaScript interpreter.Thatway,you’llgetimmediatefeedbackonwhetherwhatyouare doingisworking,and,Ihope,you’llbetemptedtoexperimentandgobeyond theexercises.
Theeasiestwaytoruntheexamplecodeinthebook—andtoexperiment withit—istolookitupintheonlineversionofthebookat https://eloquentjavascript.net There,youcanclickanycodeexampletoeditandrunitandtoseetheoutput itproduces.Toworkontheexercises,goto https://eloquentjavascript.net/ code,whichprovidesstartingcodeforeachcodingexerciseandallowsyouto lookatthesolutions.
Runningtheprogramsdefinedinthisbookoutsideofthebook’swebsite requiressomecare.Manyexamplesstandontheirownandshouldworkin anyJavaScriptenvironment.Butcodeinlaterchaptersisoftenwrittenfor aspecificenvironment(thebrowserorNode.js)andcanrunonlythere.In addition,manychaptersdefinebiggerprograms,andthepiecesofcodethat appearinthemdependoneachotheroronexternalfiles.The sandbox on thewebsiteprovideslinkstoZIPfilescontainingallthescriptsanddatafiles necessarytorunthecodeforagivenchapter.
Overviewofthisbook
Thisbookcontainsroughlythreeparts.Thefirst12chaptersdiscussthe JavaScriptlanguage.Thenextsevenchaptersareaboutwebbrowsersandthe wayJavaScriptisusedtoprogramthem.Finally,twochaptersaredevotedto Node.js,anotherenvironmenttoprogramJavaScriptin.Therearefive project chapters inthebookthatdescribelargerexampleprogramstogiveyouataste ofactualprogramming.
Thelanguagepartofthebookstartswithfourchaptersthatintroducethe basicstructureoftheJavaScriptlanguage.Theydiscuss controlstructures (suchasthe while wordyousawinthisintroduction), functions (writingyour ownbuildingblocks),and datastructures.Afterthese,youwillbeabletowrite basicprograms.Next,Chapters 5 and 6 introducetechniquestousefunctions andobjectstowritemore abstract codeandkeepcomplexityundercontrol.
Aftera firstprojectchapter thatbuildsacrudedeliveryrobot,thelanguage partofthebookcontinueswithchapterson errorhandlingandbugfixing, regularexpressions (animportanttoolforworkingwithtext), modularity (anotherdefenseagainstcomplexity),and asynchronousprogramming (dealing witheventsthattaketime).The secondprojectchapter,whereweimplement aprogramminglanguage,concludesthefirstpartofthebook.
Thesecondpartofthebook,Chapters 13 to 19,describesthetoolsthat browserJavaScripthasaccessto.You’lllearntodisplaythingsonthescreen (Chapters 14 and 17),respondtouserinput(Chapter15),andcommunicate overthenetwork(Chapter18).Thereareagaintwoprojectchaptersinthis part,buildinga platformgame anda pixelpaintprogram.
Chapter20 describesNode.js,and Chapter21 buildsasmallwebsiteusing thattool.
Typographicconventions
Inthisbook,textwrittenina monospaced fontwillrepresentelementsofprograms.Sometimestheseareself-sufficientfragments,andsometimestheyjust refertopartofanearbyprogram.Programs(ofwhichyouhavealreadyseen afew)arewrittenasfollows:
functionfactorial(n){ if(n==0){ return1; }else{ returnfactorial(n-1)*n; } 8
Sometimes,toshowtheoutputthataprogramproduces,theexpectedoutput iswrittenafterit,withtwoslashesandanarrowinfront.
console.log(factorial(8)); //→40320
Goodluck!
“Belowthesurfaceofthemachine,theprogrammoves.Without effort,itexpandsandcontracts.Ingreatharmony,electronsscatter andregroup.Theformsonthemonitorarebutripplesonthewater. Theessencestaysinvisiblybelow.”
—MasterYuan-Ma,TheBookofProgramming
Chapter1
Values,Types,andOperators
Inthecomputer’sworld,thereisonlydata.Youcanreaddata,modifydata, createnewdata—butthatwhichisn’tdatacannotbementioned.Allthisdata isstoredaslongsequencesofbitsandisthusfundamentallyalike.
Bits areanykindoftwo-valuedthings,usuallydescribedaszerosandones. Insidethecomputer,theytakeformssuchasahighorlowelectricalcharge, astrongorweaksignal,orashinyordullspotonthesurfaceofaCD.Any pieceofdiscreteinformationcanbereducedtoasequenceofzerosandones andthusrepresentedinbits.
Forexample,wecanexpressthenumber13inbits.Thisworksthesame wayasadecimalnumber,butinsteadof10differentdigits,wehaveonly2, andtheweightofeachincreasesbyafactorof2fromrighttoleft.Herearethe bitsthatmakeupthenumber13,withtheweightsofthedigitsshownbelow them:
That’sthebinarynumber00001101.Itsnon-zerodigitsstandfor8,4,and1, andaddupto13.
Values
Imagineaseaofbits—anoceanofthem.Atypicalmoderncomputerhasmore than100billionbitsinitsvolatiledatastorage(workingmemory).Nonvolatile storage(theharddiskorequivalent)tendstohaveyetafewordersofmagnitude more.
Tobeabletoworkwithsuchquantitiesofbitswithoutgettinglost,we separatethemintochunksthatrepresentpiecesofinformation.InaJavaScript environment,thosechunksarecalled values.Thoughallvaluesaremadeofbits, theyplaydifferentroles.Everyvaluehasatypethatdeterminesitsrole.Some valuesarenumbers,somevaluesarepiecesoftext,somevaluesarefunctions,
andsoon.
Tocreateavalue,youmustmerelyinvokeitsname.Thisisconvenient.You don’thavetogatherbuildingmaterialforyourvaluesorpayforthem.You justcallforone,and whoosh,youhaveit.Ofcourse,valuesarenotreally createdfromthinair.Eachonehastobestoredsomewhere,andifyouwant touseagiganticnumberofthematthesametime,youmightrunoutof computermemory.Fortunately,thisisaproblemonlyifyouneedthemall simultaneously.Assoonasyounolongeruseavalue,itwilldissipate,leaving behinditsbitstoberecycledasbuildingmaterialforthenextgenerationof values.
TheremainderofthischapterintroducestheatomicelementsofJavaScript programs,thatis,thesimplevaluetypesandtheoperatorsthatcanacton suchvalues.
Numbers
Valuesofthe number typeare,unsurprisingly,numericvalues.InaJavaScript program,theyarewrittenasfollows:
13
Usingthatinaprogramwillcausethebitpatternforthenumber13tocome intoexistenceinsidethecomputer’smemory.
JavaScriptusesafixednumberofbits,64ofthem,tostoreasinglenumber value.Thereareonlysomanypatternsyoucanmakewith64bits,whichlimits thenumberofdifferentnumbersthatcanberepresented.With N decimal digits,youcanrepresent10N numbers.Similarly,given64binarydigits,you canrepresent264 differentnumbers,whichisabout18quintillion(an18with 18zerosafterit).That’salot.
Computermemoryusedtobemuchsmaller,andpeopletendedtousegroups of8or16bitstorepresenttheirnumbers.Itwaseasytoaccidentally overflow suchsmallnumbers—toendupwithanumberthatdidnotfitintothegiven numberofbits.Today,evencomputersthatfitinyourpockethaveplentyof memory,soyouarefreetouse64-bitchunks,andyouneedtoworryabout overflowonlywhendealingwithtrulyastronomicalnumbers.
Notallwholenumberslessthan18quintillionfitinaJavaScriptnumber, though.Thosebitsalsostorenegativenumbers,soonebitindicatesthesign ofthenumber.Abiggerissueisrepresentingnonwholenumbers.Todothis, someofthebitsareusedtostorethepositionofthedecimalpoint.Theactual maximumwholenumberthatcanbestoredismoreintherangeof9quadrillion
(15zeros)—whichisstillpleasantlyhuge.
Fractionalnumbersarewrittenusingadot: 9.81
Forverybigorverysmallnumbers,youmayalsousescientificnotationby addingan e (for exponent),followedbytheexponentofthenumber: 2.998e8
That’s2.998×108 =299,800,000.
Calculationswithwholenumbers(alsocalled integers)thataresmallerthan theaforementioned9quadrillionareguaranteedtoalwaysbeprecise.Unfortunately,calculationswithfractionalnumbersaregenerallynot.Justas π (pi) cannotbepreciselyexpressedbyafinitenumberofdecimaldigits,manynumberslosesomeprecisionwhenonly64bitsareavailabletostorethem.This isashame,butitcausespracticalproblemsonlyinspecificsituations.The importantthingistobeawareofitandtreatfractionaldigitalnumbersas approximations,notasprecisevalues.
Arithmetic
Themainthingtodowithnumbersisarithmetic.Arithmeticoperationssuch asadditionormultiplicationtaketwonumbervaluesandproduceanewnumber fromthem.HereiswhattheylooklikeinJavaScript:
100+4*11
The + and * symbolsarecalled operators.Thefirststandsforadditionandthe secondstandsformultiplication.Puttinganoperatorbetweentwovalueswill applyittothosevaluesandproduceanewvalue.
Doesthisexamplemean“Add4and100,andmultiplytheresultby11”, oristhemultiplicationdonebeforetheadding?Asyoumighthaveguessed, themultiplicationhappensfirst.Asinmathematics,youcanchangethisby wrappingtheadditioninparentheses:
(100+4)*11
Forsubtraction,thereisthe - operator.Divisioncanbedonewiththe / operator.
Whenoperatorsappeartogetherwithoutparentheses,theorderinwhich theyareappliedisdeterminedbythe precedence oftheoperators.Theexample showsthatmultiplicationcomesbeforeaddition.The / operatorhasthesame precedenceas *.Likewise, + and - havethesameprecedence.Whenmultiple
operatorswiththesameprecedenceappearnexttoeachother,asin 1-2+1, theyareappliedlefttoright: (1-2)+1
Don’tworrytoomuchabouttheseprecedencerules.Whenindoubt,just addparentheses.
Thereisonemorearithmeticoperator,whichyoumightnotimmediately recognize.The % symbolisusedtorepresentthe remainder operation. X%Y istheremainderofdividing X by Y.Forexample, 314%100 produces 14,and 144%12 gives 0.Theremainderoperator’sprecedenceisthesameasthatof multiplicationanddivision.You’llalsooftenseethisoperatorreferredtoas modulo.
Specialnumbers
TherearethreespecialvaluesinJavaScriptthatareconsiderednumbersbut don’tbehavelikenormalnumbers.Thefirsttwoare Infinity and -Infinity ,whichrepresentthepositiveandnegativeinfinities. Infinity-1 isstill Infinity,andsoon.Don’tputtoomuchtrustininfinity-basedcomputation, though.Itisn’tmathematicallysound,anditwillquicklyleadtothenext specialnumber: NaN.
NaN standsfor“notanumber”,eventhoughit is avalueofthenumbertype. You’llgetthisresultwhenyou,forexample,trytocalculate 0/0 (zerodivided byzero), Infinity-Infinity,oranynumberofothernumericoperationsthat don’tyieldameaningfulresult.
Strings
Thenextbasicdatatypeisthe string.Stringsareusedtorepresenttext.They arewrittenbyenclosingtheircontentinquotes.
`Downonthesea` "Lieontheocean" 'Floatontheocean'
Youcanusesinglequotes,doublequotes,orbacktickstomarkstrings,aslong asthequotesatthestartandtheendofthestringmatch.
YoucanputalmostanythingbetweenquotestohaveJavaScriptmakea stringvalueoutofit.Butafewcharactersaremoredifficult.Youcanimagine howputtingquotesbetweenquotesmightbehard,sincetheywilllooklikethe endofthestring. Newlines (thecharactersyougetwhenyoupress enter) canbeincludedonlywhenthestringisquotedwithbackticks(\‘).
Tomakeitpossibletoincludesuchcharactersinastring,thefollowing notationisused:abackslash(\)insidequotedtextindicatesthatthecharacter afterithasaspecialmeaning.Thisiscalled escaping thecharacter.Aquote thatisprecededbyabackslashwillnotendthestringbutbepartofit.When an n characteroccursafterabackslash,itisinterpretedasanewline.Similarly, a t afterabackslashmeansatabcharacter.Takethefollowingstring:
"Thisisthefirstline\nAndthisisthesecond"
Thisistheactualtextisthatstring:
Thisisthefirstline
Andthisisthesecond
Thereare,ofcourse,situationswhereyouwantabackslashinastringtobejust abackslash,notaspecialcode.Iftwobackslashesfolloweachother,theywill collapsetogether,andonlyonewillbeleftintheresultingstringvalue.This ishowthestring“Anewlinecharacteriswrittenlike "\n" ”canbeexpressed:
"Anewlinecharacteriswrittenlike\"\\n\"."
Strings,too,havetobemodeledasaseriesofbitstobeabletoexistinside thecomputer.ThewayJavaScriptdoesthisisbasedonthe Unicode standard. Thisstandardassignsanumbertovirtuallyeverycharacteryouwouldever need,includingcharactersfromGreek,Arabic,Japanese,Armenian,andso on.Ifwehaveanumberforeverycharacter,astringcanbedescribedbya sequenceofnumbers.Andthat’swhatJavaScriptdoes.
There’sacomplicationthough:JavaScript’srepresentationuses16bitsper stringelement,whichcandescribeupto216 differentcharacters.However, Unicodedefinesmorecharactersthanthat—abouttwiceasmany,atthispoint. Sosomecharacters,suchasmanyemoji,takeuptwo“characterpositions”in JavaScriptstrings.We’llcomebacktothisin Chapter5.
Stringscannotbedivided,multiplied,orsubtracted.The + operator can be usedonthem,nottoadd,butto concatenate—togluetwostringstogether. Thefollowinglinewillproducethestring "concatenate": "con"+"cat"+"e"+"nate"
Stringvalueshaveanumberofassociatedfunctions(methods)thatcanbeused toperformotheroperationsonthem.I’llsaymoreaboutthesein Chapter4.
Stringswrittenwithsingleordoublequotesbehaveverymuchthesame— theonlydifferenceliesinwhichtypeofquoteyouneedtoescapeinsideof them.Backtick-quotedstrings,usuallycalled templateliterals,candoafew
moretricks.Apartfrombeingabletospanlines,theycanalsoembedother values.
`halfof100is${100/2}`
Whenyouwritesomethinginside ${} inatemplateliteral,itsresultwillbe computed,convertedtoastring,andincludedatthatposition.Thisexample produces“halfof100is50”.
Unaryoperators
Notalloperatorsaresymbols.Somearewrittenaswords.Oneexampleisthe typeof operator,whichproducesastringvaluenamingthetypeofthevalue yougiveit.
console.log(typeof4.5) //→number
console.log(typeof"x") //→string
Wewilluse console.log inexamplecodetoindicatethatwewanttoseethe resultofevaluatingsomething.Moreaboutthatinthe nextchapter Theotheroperatorsshownsofarinthischapteralloperatedontwovalues, but typeof takesonlyone.Operatorsthatusetwovaluesarecalled binary operators,whilethosethattakeonearecalled unary operators.Theminus operatorcanbeusedbothasabinaryoperatorandasaunaryoperator.
console.log(-(10-2)) //→-8
Booleanvalues
Itisoftenusefultohaveavaluethatdistinguishesbetweenonlytwopossibilities,like“yes”and“no”or“on”and“off”.Forthispurpose,JavaScripthasa Boolean type,whichhasjusttwovalues,trueandfalse,writtenasthosewords.
Comparison
HereisonewaytoproduceBooleanvalues:
console.log(3>2) //→true
console.log(3<2) //→false
The > and < signsarethetraditionalsymbolsfor“isgreaterthan”and“isless than”,respectively.Theyarebinaryoperators.Applyingthemresultsina Booleanvaluethatindicateswhethertheyholdtrueinthiscase.
Stringscanbecomparedinthesameway:
console.log("Aardvark"<"Zoroaster") //→true
Thewaystringsareorderedisroughlyalphabeticbutnotreallywhatyou’d expecttoseeinadictionary:uppercaselettersarealways“less”thanlowercase ones,so "Z"<"a",andnonalphabeticcharacters(!,-,andsoon)arealso includedintheordering.Whencomparingstrings,JavaScriptgoesoverthe charactersfromlefttoright,comparingtheUnicodecodesonebyone.
Othersimilaroperatorsare >= (greaterthanorequalto), <= (lessthanor equalto), == (equalto),and != (notequalto).
console.log("Garnet"!="Ruby") //→true
console.log("Pearl"=="Amethyst") //→false
ThereisonlyonevalueinJavaScriptthatisnotequaltoitself,andthatis NaN (“notanumber”).
console.log(NaN==NaN) //→false
NaN issupposedtodenotetheresultofanonsensicalcomputation,andassuch, itisn’tequaltotheresultofany other nonsensicalcomputations.
Logicaloperators
TherearealsosomeoperationsthatcanbeappliedtoBooleanvaluesthemselves.JavaScriptsupportsthreelogicaloperators: and, or,and not.These canbeusedto“reason”aboutBooleans.
The && operatorrepresentslogical and.Itisabinaryoperator,anditsresult istrueonlyifboththevaluesgiventoitaretrue.
console.log(true&&false) //→false
console.log(true&&true) //→true
The || operatordenoteslogical or.Itproducestrueifeitherofthevaluesgiven toitistrue.
console.log(false||true) //→true
console.log(false||false) //→false
Not iswrittenasanexclamationmark(!).Itisaunaryoperatorthatflipsthe valuegiventoit—!true produces false and !false gives true
WhenmixingtheseBooleanoperatorswitharithmeticandotheroperators, itisnotalwaysobviouswhenparenthesesareneeded.Inpractice,youcan usuallygetbywithknowingthatoftheoperatorswehaveseensofar, || has thelowestprecedence,thencomes &&,thenthecomparisonoperators(>, == , andsoon),andthentherest.Thisorderhasbeenchosensuchthat,intypical expressionslikethefollowingone,asfewparenthesesaspossiblearenecessary: 1+1==2&&10*10>50
Thelastlogicaloperatorwewilllookatisnotunary,notbinary,but ternary, operatingonthreevalues.Itiswrittenwithaquestionmarkandacolon,like this:
console.log(true?1:2); //→1 console.log(false?1:2); //→2
Thisoneiscalledthe conditional operator(orsometimesjust theternaryoperator sinceitistheonlysuchoperatorinthelanguage).Theoperatorusesthe valuetotheleftofthequestionmarktodecidewhichofthetwoothervalues to“pick”.Ifyouwrite a?b:c,theresultwillbe b when a istrueand c otherwise.
Emptyvalues
Therearetwospecialvalues,written null and undefined,thatareusedto denotetheabsenceofa meaningful value.Theyarethemselvesvalues,but theycarrynoinformation.
Manyoperationsinthelanguagethatdon’tproduceameaningfulvalueyield undefined simplybecausetheyhavetoyield some value.
Thedifferenceinmeaningbetween undefined and null isanaccidentof JavaScript’sdesign,anditdoesn’tmattermostofthetime.Incaseswhere
youactuallyhavetoconcernyourselfwiththesevalues,Irecommendtreating themasmostlyinterchangeable.
Automatictypeconversion
IntheIntroduction,ImentionedthatJavaScriptgoesoutofitswaytoaccept almostanyprogramyougiveit,evenprogramsthatdooddthings.Thisis nicelydemonstratedbythefollowingexpressions:
console.log(8*null) //→0
console.log("5"-1) //→4
console.log("5"+1) //→51
console.log("five"*2) //→NaN console.log(false==0) //→true
Whenanoperatorisappliedtothe“wrong”typeofvalue,JavaScriptwill quietlyconvertthatvaluetothetypeitneeds,usingasetofrulesthatoften aren’twhatyouwantorexpect.Thisiscalled typecoercion.The null inthe firstexpressionbecomes 0 andthe "5" inthesecondexpressionbecomes 5 (from stringtonumber).Yetinthethirdexpression, + triesstringconcatenation beforenumericaddition,sothe 1 isconvertedto "1" (fromnumbertostring).
Whensomethingthatdoesn’tmaptoanumberinanobviousway(suchas "five" or undefined)isconvertedtoanumber,yougetthevalue NaN.Further arithmeticoperationson NaN keepproducing NaN,soifyoufindyourselfgetting oneofthoseinanunexpectedplace,lookforaccidentaltypeconversions.
Whencomparingvaluesofthesametypeusingthe == operator,theoutcome iseasytopredict:youshouldgettruewhenbothvaluesarethesame,except inthecaseof NaN.Butwhenthetypesdiffer,JavaScriptusesacomplicated andconfusingsetofrulestodeterminewhattodo.Inmostcases,itjusttries toconvertoneofthevaluestotheothervalue’stype.However,when null or undefined occursoneithersideoftheoperator,itproducestrueonlyifboth sidesareoneof null or undefined
console.log(null==undefined); //→true
console.log(null==0); //→false