Eloquent javascript 4th edition marijn haverbeke download pdf

Page 1


Eloquent JavaScript 4th Edition Marijn Haverbeke

Visit to download the full and correct content document: https://ebookmass.com/product/eloquent-javascript-4th-edition-marijn-haverbeke/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

JavaScript T. J. Crowder

https://ebookmass.com/product/javascript-t-j-crowder/

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-thecomplete-beginners-guide-to-learning-javascript-programming-inno-time-angularjs-jquery-javascript-visually-nathaniel-hill/

JavaScript: A Beginner's Guide, Fifth Edition Pollock

https://ebookmass.com/product/javascript-a-beginners-guide-fifthedition-pollock/

How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development 1st Edition Jonathon Simpson

https://ebookmass.com/product/how-javascript-works-master-thebasics-of-javascript-and-modern-web-app-development-1st-editionjonathon-simpson-2/

How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development 1st Edition Jonathon Simpson

https://ebookmass.com/product/how-javascript-works-master-thebasics-of-javascript-and-modern-web-app-development-1st-editionjonathon-simpson/

JavaScript A Beginner's Guide Fifth Edition John Pollock

https://ebookmass.com/product/javascript-a-beginners-guide-fifthedition-john-pollock/

JavaScript Design Patterns Hugo Di Francesco

https://ebookmass.com/product/javascript-design-patterns-hugo-difrancesco/

JavaScript: The New Toys T. J. Crowder

https://ebookmass.com/product/javascript-the-new-toys-t-jcrowder/

JavaScript All-in-One For Dummies 1st Edition Chris Minnick

https://ebookmass.com/product/javascript-all-in-one-fordummies-1st-edition-chris-minnick/

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

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.

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

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.