https://ebookmass.com/product/eloquent-javascript-4th-
Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...
JavaScript T. J. Crowder
https://ebookmass.com/product/javascript-t-j-crowder/
ebookmass.com
Javascript: Crash Course - The Complete Beginners Guide To Learning JavaScript Programming In No Time! (Angularjs, jQuery, JavaScript Visually) Nathaniel Hill
https://ebookmass.com/product/javascript-crash-course-the-completebeginners-guide-to-learning-javascript-programming-in-no-timeangularjs-jquery-javascript-visually-nathaniel-hill/ ebookmass.com
JavaScript: A Beginner's Guide, Fifth Edition Pollock
https://ebookmass.com/product/javascript-a-beginners-guide-fifthedition-pollock/
ebookmass.com
Shigley's mechanical engineering design (11th Ed.) 11th Edition Richard G. Budynas
https://ebookmass.com/product/shigleys-mechanical-engineeringdesign-11th-ed-11th-edition-richard-g-budynas/
ebookmass.com
1st Edition TorresSkoumal
https://ebookmass.com/product/myp-mathematics-2-ib-myp-series-1stedition-torres-skoumal/
ebookmass.com
The Environmental Impact of COVID-19 Deepak Rawtani
https://ebookmass.com/product/the-environmental-impact-ofcovid-19-deepak-rawtani/
ebookmass.com
Exploring Ibero-American Youth Cultures in the 21st Century: Creativity, Resistance and Transgression in the City 1st Edition Ricardo Campos
https://ebookmass.com/product/exploring-ibero-american-youth-culturesin-the-21st-century-creativity-resistance-and-transgression-in-thecity-1st-edition-ricardo-campos/ ebookmass.com
Fitzgerald's Clinical Neuroanatomy and neuroscience 8th Edition Estomih Mtui
https://ebookmass.com/product/fitzgeralds-clinical-neuroanatomy-andneuroscience-8th-edition-estomih-mtui/
ebookmass.com
Shi'ism Revisited: Ijtihad and Reformation in Contemporary Times Liyakat Takim
https://ebookmass.com/product/shiism-revisited-ijtihad-andreformation-in-contemporary-times-liyakat-takim/
ebookmass.com
https://ebookmass.com/product/electronic-materials-principles-andapplied-science-poplavko/
ebookmass.com
EloquentJavaScript 4thedition MarijnHaverbeke Copyright©2024byMarijnHaverbeke
ThisworkislicensedunderaCreativeCommonsattribution-noncommercial license(http://creativecommons.org/licenses/by-nc/3.0/).Allcodeinthe bookmayalsobeconsideredlicensedunderanMITlicense(https://eloquentjavascript. net/code/LICENSE).
Theillustrationsarecontributedbyvariousartists:CoverbyPéchaneSumie.ChapterillustrationsbyMadalinaTantareanu.PixelartinChapters7and 16byAntonioPerdomoPastor.RegularexpressiondiagramsinChapter9 generatedwith regexper.com byJeffAvallone.VillagephotographinChapter 11byFabriceCreuzot.GameconceptforChapter16by ThomasPalef
Youcanbuyaprintversionofthisbook,withanextrabonuschapterincluded, printedbyNoStarchPressat http://a-fwd.com/com=marijhaver-20&asincom=1593279507
“Wethinkwearecreatingthesystemforourownpurposes.We believewearemakingitinourownimage...Butthecomputeris notreallylikeus.Itisaprojectionofaveryslimpartofourselves: thatportiondevotedtologic,order,rule,andclarity.”
—EllenUllman,ClosetotheMachine:Technophiliaandits Discontents
Introduction Thisisabookaboutinstructingcomputers.Computersareaboutascommon asscrewdriverstoday,buttheyarequiteabitmorecomplex,andmakingthem dowhatyouwantthemtodoisn’talwayseasy.
Ifthetaskyouhaveforyourcomputerisacommon,well-understoodone, suchasshowingyouyouremailoractinglikeacalculator,youcanopenthe appropriateapplicationandgettowork.Butforuniqueoropen-endedtasks, thereoftenisnoappropriateapplication.
Thatiswhereprogrammingmaycomein. Programming istheactofconstructinga program—asetofpreciseinstructionstellingacomputerwhattodo. Becausecomputersaredumb,pedanticbeasts,programmingisfundamentally tediousandfrustrating.
Fortunately,ifyoucangetoverthatfact—andmaybeevenenjoytherigor ofthinkingintermsthatdumbmachinescandealwith—programmingcanbe rewarding.Itallowsyoutodothingsinsecondsthatwouldtake forever by hand.Itisawaytomakeyourcomputertooldothingsthatitcouldn’tdo before.Ontopofthat,itmakesforawonderfulgameofpuzzlesolvingand abstractthinking.
Mostprogrammingisdonewithprogramminglanguages.A programming language isanartificiallyconstructedlanguageusedtoinstructcomputers.It isinterestingthatthemosteffectivewaywe’vefoundtocommunicatewitha computerborrowssoheavilyfromthewaywecommunicatewitheachother. Likehumanlanguages,computerlanguagesallowwordsandphrasestobe combinedinnewways,makingitpossibletoexpressevernewconcepts.
Atonepoint,language-basedinterfaces,suchastheBASICandDOSprompts ofthe1980sand1990s,werethemainmethodofinteractingwithcomputers. Forroutinecomputeruse,thesehavelargelybeenreplacedwithvisualinterfaces,whichareeasiertolearnbutofferlessfreedom.Butifyouknowwhere tolook,thelanguagesarestillthere.Oneofthem, JavaScript,isbuiltinto everymodernwebbrowser—andisthusavailableonalmosteverydevice.
Thisbookwilltrytomakeyoufamiliarenoughwiththislanguagetodo usefulandamusingthingswithit.
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