Tải bản đầy đủ (.pdf) (377 trang)

Practical modern javascript dive into ES6 and the future of javascript

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.15 MB, 377 trang )


PraiseforPracticalModernJavaScript
PracticalModernJavaScriptbringsawholetonofnewsyntaxandsemanticsthatmakesyourcode
moreexpressiveanddeclarative.Nicolásdoesanamazingjobofdistillingthiswithsimpleexamples
soyoucangetuptospeedquickly.
KentC.Dodds(PayPal,TC39)
NicolásdemystifiesthemassiveES6specificationwithapragmaticandpracticaldiveintothefeatures
thatareredefiningmodernJavaScriptdevelopment.
RodVagg(NodeSource,Node.jsTSC)
Nicoláshasanamazingabilitytobreakdownhighlycomplextechnicaltopicsintoeasy-to-understand
proseandsamplecode.
MathiasBynens(Google,TC39)
JavaScriptisatoughlanguagetomaster,andthe2015editionaddsalotofnewfeatures.Practical
ModernJavaScripthelpsbreakthemdownandexplainsusecases,conceptualmodels,andbest
practices,withsimpleexamples—makingthesenewpatternsmucheasiertograsp.
JordanHarband(Airbnb,TC39)
ES6broughtsignificantchangestothelanguage—changesthattaketimetograspevenforadvanced
JavaScriptdevelopers.You’llneedaguideonthisjourney,andNicolás’bookisoneofthebestyou
canget.
IngvarStepanyan(CloudFlare)
WhenIcreatedJavaScriptin1995,Ihadnodefiniteideathatitwouldbecomethemostwidelyused
programminglanguageontheInternet.ThisModularJavaScriptbookseriesfulfillsmyhopeforan
incrementalandstraightforwardpedagogyaboutJavaScript.Iencourageyoutodivein,todiscoverand
embraceJavaScript,andtocontributetodevelopingabetterwebforeveryone.
BrendanEich(creatorofJavaScript)



PracticalModernJavaScript
NicolásBevacqua



PracticalModernJavaScript
byNicolásBevacquaCopyright©2017NicolásBevacqua.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO’ReillyMedia,Inc.,1005GravensteinHighwayNorth,Sebastopol,CA95472.
O’Reillybooksmaybepurchasedforeducational,business,orsalespromotionaluse.Onlineeditionsare
alsoavailableformosttitles(Formoreinformation,contactour
corporate/institutionalsalesdepartment:800-998-9938or
Editor:AllysonMacDonald
ProductionEditor:MelanieYarbrough
Copyeditor:KimCofer
Proofreader:MollyIvesBrower
Indexer:WendyCatalano
InteriorDesigner:DavidFutato
CoverDesigner:KarenMontgomery
Illustrator:RebeccaDemarest
June2017:FirstEdition


RevisionHistoryfortheFirstEdition
2017-06-26:FirstRelease
Seeforreleasedetails.
TheO’ReillylogoisaregisteredtrademarkofO’ReillyMedia,Inc.PracticalModernJavaScript,the
coverimage,andrelatedtradedressaretrademarksofO’ReillyMedia,Inc.
Whilethepublisherandtheauthorhaveusedgoodfaitheffortstoensurethattheinformationand
instructionscontainedinthisworkareaccurate,thepublisherandtheauthordisclaimallresponsibility
forerrorsoromissions,includingwithoutlimitationresponsibilityfordamagesresultingfromtheuseof
orrelianceonthiswork.Useoftheinformationandinstructionscontainedinthisworkisatyourown
risk.Ifanycodesamplesorothertechnologythisworkcontainsordescribesissubjecttoopensource
licensesortheintellectualpropertyrightsofothers,itisyourresponsibilitytoensurethatyourusethereof

complieswithsuchlicensesand/orrights.
978-1-491-94353-3
[LSI]


Foreword
WhenIcreatedJavaScriptin1995atNetscape,Ihadnodefiniteideathatitwouldbecomethemost
widelyusedprogramminglanguageontheInternet.IdidknowthatIhadverylittletimetogetitinto
“minimumviableshipping”state,andsoImadeitextensibleandmutablefromglobalobjectondown,
eventobase-levelmeta-objectprotocolhooks(e.g.,toStringandvalueOf,styledafterJava’smethods
ofthesamenames).
Yetinspiteofitsongoingevolutionandstill-risingpopularity,JavaScriptalwaysbenefitsfroman
incrementalandcarefulteachingapproachthatputsfirstthingsfirst.Ithinkthisfollowsinevitablyfrom
thehurrieddesignandintentionalextensibility.Ioverloadedtwokernelelements,functionsandobjects,
sothatprogrammerscouldusetheminvariouswaysasgeneralworkalikesforindividualtoolsinalarger
Swissarmyknife.Thismeantthatstudentswouldneedtolearnwhichtoolwasbesttouseforaspecific
task,andhowpreciselytowieldthatparticularblade.
Netscapewasawhirlwindforme,andIthinkforanyonetherefromearly1995on.Itwasrushingtoward
aninitialpublicofferingpredicatedoncompetingwithMicrosoftviatheinfamous“Netscape+Javakills
Windows”formularepeatedbyMarcAndreessenontheIPOroadshowthatyear.Javawasthebigbrotheror“Batman”programminglanguagetolittle-brother,“Robintheboyhostage”sidekick“scripting
language,”JavaScript.
ButIknewwhileIwaswritingthefirstversion(code-named“Mocha”)thatJavaScriptandnotJava
wouldbeintegrateddeeplywiththeNetscapebrowserandtheDocumentObjectModelIcreatedatthe
sametime.TherewasnowayacrosstheNetscape/Sunorganizationalboundary,orthebrowser/JVM
codebases,toembedJavaotherthanasaplugin.
SoIdidhaveavaguesensethatJavaScriptwouldeithersucceedovertimeanddowell,orelsefade
quicklyintheshadowofsomethingelse.Iremembertellingmyfriendandcubicle-mateJeffWeinstein,
whenheaskedmewhatI’dbedoingin20years,thatitwouldbe“JavaScriptorbust.”EventhenIfelta
senseofdeepobligationtoJavaScript’susersthatwasinherentinthe“two-bladeSwissarmyknife”
designIhadchosenunderthedualconstraintsofextremelyshortscheduleand“makeitlooklikeJava”

managementedict.
TheModularJavaScriptbookseriesfulfillsmyhopeforanincrementalandstraightforwardpedagogy,
startingwitheasilyapplicablecodeexamplesandscalingthroughdesignpatternstoentiremodule-based
applications.Thisseriesnicelycoversbesttestingpracticesandwinningtechniquesfordeploying
JavaScriptapplications.ItisanotherjewelinO’Reilly’scrownofbooksonJavaScript.
IamdelightedtosupportNicolás’endeavorbecausehisbooklooksexactlylikewhatpeoplewhoare
comingtoJavaScriptwithfresheyesneed.IfirstmetNicolásatadinnerinParisandgottoknowhima
bitthere,andovertimeonline.Hispragmatismcombinedwithempathyfornewcomerstothelanguage
andagreatsenseofhumorconvincedmetoreviewthisbookindraftform.Thefinishedworkiseasyto
digestandfun.Iencourageyoutodivein,todiscoverandembraceJavaScript,andtocontributeto
developingabetterwebforeveryone.
BrendanEich,InventorofJavaScript,CEOandcofounderofBraveSoftware


Preface
Backin1998,whenIwasusingFrontPageforallmywebdevelopmentneedsatschool,ifsomeonehad
toldmethatI’dendupworkingonthewebforaliving,Iwould’veprobablychuckled.JavaScripthas
grownalongwithusinalltheyearssince,andit’shardtoimaginehowthewebcould’vethrivedwithout
it.Bitbybit,thisbookwillgiveyouacomprehensivepictureofthemodernJavaScriptlandscape.


WhoShouldReadThisBook
Thisbookismeantforwebdevelopers,enthusiasts,andprofessionalswithaworkingknowledgeofplain
JavaScript.ThesedevelopersandanyonelookingtofurthertheirunderstandingoftheJavaScriptlanguage
shallbenefitfromreadingPracticalModernJavaScript.


WhyModernJavaScript?
Thegoalofthisbookistoprovideanapproachablewayoflearningthelatestdevelopmentsin
JavaScript:ES6andlater.ES6wasahugeupdatetothelanguage,anditcameoutaroundthesametime

asastreamlinedspecificationdevelopmentprocess.AroundthistimeIwrotequiteafewblogposts
aboutthedifferentfeaturesinES6,whichbecameabitpopular.TherearequiteafewotherbooksonES6
outthere,butthey’realittledifferentfromwhatIhadinmindforabookonES6andbeyond.Thisbook
triestoexplainfeaturesindetailwithoutgettingcaughtupinthespecification,itsimplementationdetails,
orunlikelycornercasesthatwouldalmostcertainlyneedtoberesearchedonlineifhappenedupon.
Insteadofextremethoroughness,thebookplacesitsutmostfocusinthelearningprocess,havingsortedits
materialinsuchanincrementalwaythatyoudon’thavetoscanaheadinthebookforthedefinitionof
somethingelse.Armedwithpracticalexamples,PracticalModernJavaScriptgoesbeyondES6to
capturethechangestothelanguagesinceJune2015—whentheES6specificationwasfinalized—
includingasyncfunctions,objectdestructuring,dynamicimports,Promise#finally,andasync
generators.
Lastly,thisbookhasthegoalofestablishingabaselinewecantakeforgrantedintherestoftheModular
JavaScriptseries.Afterhavinglearnedthelatestlanguagefeaturesinthisfirstbook,we’llbeallsetto
discussmodulardesign,testing,anddeployment,withouthavingtodivergeintolanguagefeatures
wheneverthey’reusedinacodeexample.Thisincrementalandmodularapproachismeanttobe
pervasiveacrosstheseries,eachbook,eachchapter,andeachsection.


HowIsThisBookOrganized?
InChapter1,weopenwithanintroductiontoJavaScriptanditsstandardsdevelopmentprocess,howit
hasevolvedovertheyears,whereitisnow,andwhereit’sgoing.You’llalsogetashortintroductionto
BabelandESLint,moderntoolsthatcanaidusintheprocessofdiscoveringmodernJavaScript.
Chapter2coversalloftheabsolutelyessentialchangesinES6,includingarrowfunctions,destructuring,
letandconst,templateliterals,andafewothersyntaxembellishments.
InChapter3,we’lldiscussthenewclasssyntaxfordeclaringobjectprototypes,anewprimitivetype
knownasSymbol,andafewnewObjectmethods.
Chapter4goesoverallofthenewwayswecandealwithflowcontrolstartinginES6.Wediscuss
Promises,iterators,generators,andasyncfunctionsingreatdetailandwithheapsofaccompanying
examples,uncoveringthesynergisticpropertiesbetweenallthedifferenttechniques.Youwon’tonlylearn
howtousetheseflowcontroltechniquesbuthowtobestreasonaboutthemsothattheytrulysimplify

yourcode.
Chapter5describesthenewcollectionbuilt-insfoundinES6,whichwecanusetocreateobjectmaps
anduniquesets.You’llfindusageexamplesforeachofthesecollectiontypes.
Chapter6coversthenewProxyandReflectbuilt-ins.We’lllearnallabouthowwecanuseproxiesand
thereasonswhyweneedtobecarefulwhenchoosingtodoso.
Chapter7isdedicatedtotherestofbuilt-inimprovementsthatcanbefoundinES6.Particularlyaround
Array,Math,numbers,strings,Unicode,andregularexpressions.
Chapter8isdevotedtonativeJavaScriptModulesand,briefly,thehistorythatledtotheirinception.
We’llthendiscusstheirsyntaximplicationsatlength.
Chapter9,thelastchapter—dubbed“PracticalConsiderations”—issomewhatunconventionalfor
booksaboutprogramminglanguages.Ratherthanspreadingmypersonalviewsthroughoutthebook,I
condensedthemintothelastchapter.Hereyou’llfindreasoningbehindhowtodecidewhentousewhich
kindofvariabledeclarationorstringliteralquotationmark,adviceonhandlingasynchronouscodeflows
andwhetherusingclassesorproxiesisagoodidea,andafewmorenuggetsofinsight.
ForthoseofyouwhoarealreadysomewhatfamiliarwithES6andcomfortablejumpingaroundthepages
inabook,IrecommendreadingChapter4indetail,asyoushouldfindtheinsightintoflowcontrolmost
valuable.Chapters7and8arealsoamust,sincetheyprovidedetailsaroundtheareasofES6thatare
lessoftendiscussedintheopen.Thelastchapterwillindubitably—regardlessofwhetheryouagree
withtheviewsexpressedtherein—challengeyoutothinkdeeplyaboutwhatworksandwhatdoesn’tin
thecontextofJavaScriptapplicationswrittenunderthewildnewworldorderthatismodernJavaScript.


ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,andfileextensions.
Constantwidth

Usedforprogramlistings,aswellaswithinparagraphstorefertoprogramelementssuchas
variableorfunctionnames,databases,datatypes,environmentvariables,statements,andkeywords.


TIP
Thisiconsignifiesatip,suggestion,orgeneralnote.

WARNING
Thisiconindicatesawarningorcaution.


O’ReillySafari
NOTE
Safari(formerlySafariBooksOnline)isamembership-basedtrainingandreferenceplatformfor
enterprise,government,educators,andindividuals.
Membershaveaccesstothousandsofbooks,trainingvideos,LearningPaths,interactivetutorials,and
curatedplaylistsfromover250publishers,includingO’ReillyMedia,HarvardBusinessReview,
PrenticeHallProfessional,Addison-WesleyProfessional,MicrosoftPress,Sams,Que,PeachpitPress,
Adobe,FocalPress,CiscoPress,JohnWiley&Sons,Syngress,MorganKaufmann,IBMRedbooks,
Packt,AdobePress,FTPress,Apress,Manning,NewRiders,McGraw-Hill,Jones&Bartlett,and
CourseTechnology,amongothers.
Formoreinformation,pleasevisit />

HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
O’ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,examples,andanyadditionalinformation.You
canaccessthispageat />Tocommentorasktechnicalquestionsaboutthisbook,sendemailto

Formoreinformationaboutourbooks,courses,conferences,andnews,seeourwebsiteat
.
FindusonFacebook: />FollowusonTwitter: />WatchusonYouTube: />

Acknowledgments
Likevirtuallyeveryhumantaskevercarriedout,PracticalModernJavaScriptwasmadepossibleonly
bybuildingupontheworkofothers.IwanttothankNanBarber,myeditoratO’Reilly,forherfantastic
supportalongtherideofwritingthisbook.AllyMacDonald,anothereditoratO’Reilly,helpedmeoutin
theearlydaysoftheprojectandistheforemostreasonwhyModularJavaScriptbecameabookseries,as
shehelpedmeconjureupamodularapproachtoteachingJavaScript.
Thisbookhadaphenomenalensembleoftechnicalreviewers.ManyofthesefolksareonTC39,the
technicalcommitteedevotedtopushingJavaScriptforward,andit’sdeeplyhumblingthattheygaveup
someoftheirtimetohelpfuture-proofthisbook.Asalways,MathiasBynens(ex-Opera)proved
instrumentaltoproofingeverythinginthebookwithregardstoUnicodestandardsandheldmyworktoa
highdegreeofconsistencyintermsofcodesnippets.KentC.Dodds(TC39,PayPal)ingeniouslyoffered
videoreviewswhereheidentifiedweakspotsandhelpedimprovethebook.JordanHarband(TC39,
Airbnb)camethroughwithdeeptechnicalcommentaryaboutmanyoftheJavaScriptfeaturesdiscussedin
thebook,andalongwithAlexRussell(TC39,Google)helpedmeironoutthehistoryofJavaScriptand
itsstandardsbodyforthefirstchapter.IngvarStepanyan(Cloudflare)wasalsoasharpeyeinidentifying
codeissuesandpinpointedmistakesaroundlow-levelaspectsofthespecification.BrianTerlson(TC39
editor,Microsoft)alsohelpedoutwithtimelinesanddetailsaroundTC39.RodVagg(Node.js)provided
insightthatleadtobettercodeexamplesandmoreconsistentcodestylethroughoutthebook.
BrendanEich(TC39,BraveCEO)providedatroveofinsightintotheearlydaysofJavaScriptandTC39,
whichprovedessentialtothedevelopmentofthefirstchapter.Andnaturally,ifnotforhim,youwouldn’t
beholdingthisbookinyourhands.
Lastly,I’dliketothankmywife,Marianela,forhersacrificesandputtingupwithmethroughthe
developmentofthefirstbookinalongseries.Marian,Icouldn’tdothiswithoutyou!


Chapter1.ECMAScriptandtheFutureof

JavaScript
JavaScripthasgonefrombeinga1995marketingploytogainatacticaladvantagetobecomingthecore
programmingexperienceintheworld’smostwidelyusedapplicationruntimeplatformin2017.The
languagedoesn’tmerelyruninbrowsersanymore,butisalsousedtocreatedesktopandmobile
applications,inhardwaredevices,andeveninspacesuitdesignatNASA.
HowdidJavaScriptgethere,andwhereisitgoingnext?


1.1ABriefHistoryofJavaScriptStandards
Backin1995,NetscapeenvisionedadynamicwebbeyondwhatHTMLcouldoffer.BrendanEichwas
initiallybroughtintoNetscapetodevelopalanguagethatwasfunctionallyakintoScheme,butforthe
browser.Oncehejoined,helearnedthatuppermanagementwantedittolooklikeJava,andadealtothat
effectwasalreadyunderway.
BrendancreatedthefirstJavaScriptprototypein10days,takingScheme’sfirst-classfunctionsandSelf’s
prototypesasitsmainingredients.TheinitialversionofJavaScriptwascode-namedMocha.Itdidn’t
havearrayorobjectliterals,andeveryerrorresultedinanalert.Thelackofexceptionhandlingiswhy,
tothisday,manyoperationsresultinNaNorundefined.Brendan’sworkonDOMlevel0andthefirst
editionofJavaScriptsetthestageforstandardswork.
ThisrevisionofJavaScriptwasmarketedasLiveScriptwhenitstartedshippingwithabetareleaseof
NetscapeNavigator2.0,inSeptember1995.ItwasrebrandedasJavaScript(trademarkedbySun,now
ownedbyOracle)whenNavigator2.0beta3wasreleasedinDecember1995.Soonafterthisrelease,
Netscapeintroducedaserver-sideJavaScriptimplementationforscriptinginNetscapeEnterpriseServer,
andnameditLiveWire.1JScript,Microsoft’sreverse-engineeredimplementationofJavaScript,was
bundledwithIE3in1996.JScriptwasavailableforInternetInformationServer(IIS)intheserverside.
ThelanguagestartedbeingstandardizedundertheECMAScriptname(ES)intotheECMA-262
specificationin1996,underatechnicalcommitteeatECMAknownasTC39.Sunwouldn’ttransfer
ownershipoftheJavaScripttrademarktoECMA,andwhileMicrosoftofferedJScript,othermember
companiesdidn’twanttousethatname,soECMAScriptstuck.
Disputesbycompetingimplementations,JavaScriptbyNetscapeandJScriptbyMicrosoft,dominated
mostoftheTC39standardscommitteemeetingsatthetime.Evenso,thecommitteewasalreadybearing

fruit:backwardcompatibilitywasestablishedasagoldenrule,bringingaboutstrictequalityoperators
(===and!==)insteadofbreakingexistingprogramsthatreliedonthelooseEqualityComparison
Algorithm.
ThefirsteditionofECMA-262wasreleasedJune1997.Ayearlater,inJune1998,thespecificationwas
refinedundertheISO/IEC16262internationalstandard,aftermuchscrutinyfromnationalISObodies,
andformalizedasthesecondedition.
ByDecember1999thethirdeditionwaspublished,standardizingregularexpressions,theswitch
statement,do/while,try/catch,andObject#hasOwnProperty,amongafewotherchanges.Mostof
thesefeatureswerealreadyavailableinthewildthroughNetscape’sJavaScriptruntime,SpiderMonkey.
DraftsforanES4specificationweresoonafterwardspublishedbyTC39.ThisearlyworkonES4ledto
JScript​.NETinmid-20002and,eventually,toActionScript3forFlashin2006.3
ConflictingopinionsonhowJavaScriptwastomoveforwardbroughtworkonthespecificationtoa
standstill.Thiswasadelicatetimeforwebstandards:Microsofthadallbutmonopolizedtheweband
theyhadlittleinterestinstandardsdevelopment.
AsAOLlaidoff50Netscapeemployeesin2003,4theMozillaFoundationwasformed.Withover95%of
web-browsingmarketsharenowinthehandsofMicrosoft,TC39wasdisbanded.
IttooktwoyearsuntilBrendan,nowatMozilla,hadECMAresurrectworkonTC39byusingFirefox’s


growingmarketshareasleveragetogetMicrosoftbackinthefold.Bymid-2005,TC39startedmeeting
regularlyonceagain.AsforES4,therewereplansforintroducingamodulesystem,classes,iterators,
generators,destructuring,typeannotations,propertailcalls,algebraictyping,andanassortmentofother
features.Duetohowambitioustheprojectwas,workonES4wasrepeatedlydelayed.
By2007thecommitteewassplitintwo:ES3.1,whichhailedamoreincrementalapproachtoES3;and
ES4,whichwasoverdesignedandunderspecified.Itwouldn’tbeuntilAugust20085whenES3.1was
agreeduponasthewayforward,butlaterrebrandedasES5.AlthoughES4wouldbeabandoned,manyof
itsfeatureseventuallymadeitswayintoES6(whichwasdubbedHarmonyatthetimeofthisresolution),
whilesomeofthemstillremainunderconsiderationandafewothershavebeenabandoned,rejected,or
withdrawn.TheES3.1updateservedasthefoundationontopofwhichtheES4specificationcouldbe
laidinbitsandpieces.

InDecember2009,onthe10-yearanniversarysincethepublicationofES3,thefiftheditionof
ECMAScriptwaspublished.Thiseditioncodifieddefactoextensionstothelanguagespecificationthat
hadbecomecommonamongbrowserimplementations,addinggetandsetaccessors,functional
improvementstotheArrayprototype,reflectionandintrospection,aswellasnativesupportforJSON
parsingandstrictmode.
Acoupleofyearslater,inJune2011,thespecificationwasonceagainreviewedandeditedtobecomethe
thirdeditionoftheinternationalstandardISO/IEC16262:2011,andformalizedunderECMAScript5.1.
IttookTC39anotherfouryearstoformalizeECMAScript6,inJune2015.Thesixtheditionisthelargest
updatetothelanguagethatmadeitswayintopublication,implementingmanyoftheES4proposalsthat
weredeferredaspartoftheHarmonyresolution.Throughoutthisbook,we’llbeexploringES6indepth.
InparallelwiththeES6effort,in2012theWHATWG(astandardsbodyinterestedinpushingtheweb
forward)setouttodocumentthedifferencesbetweenES5.1andbrowserimplementations,intermsof
compatibilityandinteroperabilityrequirements.ThetaskforcestandardizedString#substr,whichwas
previouslyunspecified;unifiedseveralmethodsforwrappingstringsinHTMLtags,whichwere
inconsistentacrossbrowsers;anddocumentedObject.prototypepropertieslike__proto__and
__defineGetter__,amongotherimprovements.6ThiseffortwascondensedintoaseparateWeb
ECMAScriptspecification,whicheventuallymadeitswayintoAnnexBin2015.AnnexBwasan
informativesectionofthecoreECMAScriptspecification,meaningimplementationsweren’trequiredto
followitssuggestions.Jointlywiththisupdate,AnnexBwasalsomadenormativeandrequiredforweb
browsers.
ThesixtheditionisasignificantmilestoneinthehistoryofJavaScript.Besidesthedozensofnew
features,ES6marksakeyinflectionpointwhereECMAScriptwouldbecomearollingstandard.


1.2ECMAScriptasaRollingStandard
Havingspent10yearswithoutobservingsignificantchangetothelanguagespecificationafterES3,and4
yearsforES6tomaterialize,itwascleartheTC39processneededtoimprove.Therevisionprocess
usedtobedeadline-driven.Anydelayinarrivingatconsensuswouldcauselongwaitperiodsbetween
revisions,whichledtofeaturecreep,causingmoredelays.Minorrevisionsweredelayedbylarge
additionstothespecification,andlargeadditionsfacedpressuretofinalizesothattherevisionwouldbe

pushedthrough,avoidingfurtherdelays.
SinceES6cameout,TC39hasstreamlined7itsproposalrevisioningprocessandadjustedittomeet
modernexpectations:theneedtoiteratemoreoftenandconsistently,andtodemocratizespecification
development.Atthispoint,TC39movedfromanancientWord-basedflowtousingEcmarkup(anHTML
supersetusedtoformatECMAScriptspecifications)andGitHubpullrequests,greatlyincreasingthe
numberofproposals8beingcreatedaswellasexternalparticipationbynonmembers.Thenewflowis
continuousandthus,moretransparent:whilepreviouslyyou’dhavetodownloadaWorddocoritsPDF
versionfromawebpage,thelatestdraftofthespecificationisnowalwaysavailable.
Firefox,Chrome,Edge,Safari,andNode.jsallofferover95%complianceoftheES6specification,9but
we’vebeenabletousethefeaturesastheycameoutineachofthesebrowsersratherthanhavingtowait
untiltheflipofaswitchwhentheirimplementationofES6was100%finalized.
Thenewprocessinvolvesfourdifferentmaturitystages.10Themorematureaproposalis,themorelikely
itistoeventuallymakeitintothespecification.
Anydiscussion,idea,orproposalforachangeoradditionthathasnotyetbeensubmittedasaformal
proposalisconsideredtobeanaspirational“strawman”proposal(stage0),butonlyTC39memberscan
createstrawmanproposals.Atthetimeofthiswriting,thereareoveradozenactivestrawman
proposals.11
Atstage1aproposalisformalizedandexpectedtoaddresscross-cuttingconcerns,interactionswith
otherproposals,andimplementationconcerns.Proposalsatthisstageshouldidentifyadiscreteproblem
andofferaconcretesolutiontotheproblem.Astage1proposaloftenincludesahigh-levelAPI
description,illustrativeusageexamples,andadiscussionofinternalsemanticsandalgorithms.Stage1
proposalsarelikelytochangesignificantlyastheymaketheirwaythroughtheprocess.
Proposalsinstage2offeraninitialdraftofthespecification.Atthispoint,it’sreasonabletobegin
experimentingwithactualimplementationsinruntimes.Theimplementationcouldcomeintheformofa
polyfill,usercodethatmanglestheruntimeintoadheringtotheproposal;anengineimplementation,
nativelyprovidingsupportfortheproposal;orcompiledintosomethingexistingenginescanexecute,
usingbuild-timetoolstotransformsourcecode.
Proposalsinstage3arecandidaterecommendations.Inorderforaproposaltoadvancetothisstage,the
specificationeditoranddesignatedreviewersmusthavesignedoffonthefinalspecification.
Implementorsshould’veexpressedinterestintheproposalaswell.Inpractice,proposalsmovetothis

levelwithatleastonebrowserimplementation,ahigh-fidelitypolyfill,orwhensupportedbyabuildtimecompilerlikeBabel.Astage3proposalisunlikelytochangebeyondfixestoissuesidentifiedinthe
wild.
Inorderforaproposaltoattainstage4status,twoindependentimplementationsneedtopassacceptance


tests.Proposalsthatmaketheirwaythroughtostage4willbeincludedinthenextrevisionof
ECMAScript.
Newreleasesofthespecificationareexpectedtobepublishedeveryyearfromnowon.Toaccommodate
theyearlyreleaseschedule,versionswillnowbereferredtobytheirpublicationyear.ThusES6
becomesES2015,thenwehaveES2016insteadofES7,ES2017,andsoon.Colloquially,ES2015hasn’t
takenandisstilllargelyregardedasES6.ES2016hadbeenannouncedbeforethenamingconvention
changed,thusitissometimesstillreferredtoasES7.WhenweleaveoutES6duetoitspervasivenessin
thecommunity,weendupwith:ES6,ES2016,ES2017,ES2018,andsoon.
Thestreamlinedproposalprocesscombinedwiththeyearlycutintostandardizationtranslatesintoamore
consistentpublicationprocess,anditalsomeansspecificationrevisionnumbersarebecomingless
important.Thefocusisnowonproposalstages,andwecanexpectreferencestospecificrevisionsofthe
ECMAScriptstandardtobecomemoreuncommon.


1.3BrowserSupportandComplementaryTooling
Astage3candidaterecommendationproposalismostlikelytomakeitintothespecificationinthenext
cut,providedtwoindependentimplementationslandinJavaScriptengines.Effectively,stage3proposals
areconsideredsafetouseinreal-worldapplications,beitthroughanexperimentalengine
implementation,apolyfill,orusingacompiler.Stage2andearlierproposalsarealsousedinthewildby
JavaScriptdevelopers,tighteningthefeedbackloopbetweenimplementorsandconsumers.
Babelandsimilarcompilersthattakecodeasinputandproduceoutputnativetothewebplatform
(HTML,CSS,orJavaScript)areoftenreferredtoastranspilers,whichareconsideredtobeasubsetof
compilers.Whenwewanttoleverageaproposalthat’snotwidelyimplementedinJavaScriptenginesin
ourcode,compilerslikeBabelcantransformtheportionsofcodeusingthatnewproposalintosomething
that’smorewidelysupportedbyexistingJavaScriptimplementations.

Thistransformationcanbedoneatbuildtime,sothatconsumersreceivecodethat’swellsupportedby
theirJavaScriptruntimeofchoice.Thismechanismimprovestheruntimesupportbaseline,giving
JavaScriptdeveloperstheabilitytotakeadvantageofnewlanguagefeaturesandsyntaxsooner.Itisalso
significantlybeneficialtospecificationwritersandimplementors,asitallowsthemtocollectfeedback
regardingviability,desirability,andpossiblebugsorcornercases.
AtranspilercantaketheES6sourcecodewewriteandproduceES5codethatbrowserscaninterpret
moreconsistently.ThisisthemostreliablewayofrunningES6codeinproductiontoday:usingabuild
steptoproduceES5codethatmostoldbrowsers,aswellasmodernbrowsers,canexecute.
ThesameappliestoES7andbeyond.Asnewversionsofthelanguagespecificationarereleasedevery
year,wecanexpectcompilerstosupportES2017input,ES2018input,andsoon.Similarly,asbrowser
supportbecomesbetter,wecanalsoexpectcompilerstoreducecomplexityinfavorofES6output,then
ES7output,andsoon.Inthissense,wecanthinkofJavaScript-to-JavaScripttranspilersasamoving
windowthattakescodewrittenusingthelatestavailablelanguagesemanticsandproducesthemost
moderncodetheycanoutputwithoutcompromisingbrowsersupport.
Let’stalkabouthowyoucanuseBabelaspartofyourworkflow.


1.3.1IntroductiontotheBabelTranspiler
BabelcancompilemodernJavaScriptcodethatreliesonES6featuresintoES5.Itproduceshumanreadablecode,makingitmorewelcomingwhenwedon’thaveafirmgrasponallofthenewfeatures
we’reusing.
TheonlineBabelREPL(Read-Evaluate-PrintLoop)isanexcellentwayofjumpingrightintolearning
ES6,withoutanyofthehassleofinstallingNode.jsandthebabelCLI,andmanuallycompilingsource
code.
TheREPLprovidesuswithasourcecodeinputareathatgetsautomaticallycompiledinrealtime.Wecan
seethecompiledcodetotherightofoursourcecode.
Let’swritesomecodeintotheREPL.Youcanusethefollowingcodesnippettogetstarted:
vardouble=value=>value*2
console.log(double(3))
//<-6


Totherightofthesourcecodewe’veentered,you’llseethetranspiledES5equivalent,asshownin
Figure1-1.Asyouupdateyoursourcecode,thetranspiledresultisalsoupdatedinrealtime.

Figure1-1.TheonlineBabelREPLinaction—agreatwaytodiverightintoaninteractiveES6session

TheBabelREPLisaneffectivecompanionasawayoftryingoutsomeofthefeaturesintroducedinthis
book.However,notethatBabeldoesn’ttranspilenewbuilt-ins,suchasSymbol,Proxy,andWeakMap.
Thosereferencesareinsteadleftuntouched,andit’suptotheruntimeexecutingtheBabeloutputto
providethosebuilt-ins.Ifwewanttosupportruntimesthathaven’tyetimplementedthesebuilt-ins,we
couldimportthebabel-polyfillpackageinourcode.
InolderversionsofJavaScript,semanticallycorrectimplementationsofthesefeaturesarehardto
accomplishordownrightimpossible.Polyfillsmaymitigatetheproblem,buttheyoftencan’tcoverall
usecasesandthussomecompromisesneedtobemade.Weneedtobecarefulandtestourassumptions
beforewereleasetranspiledcodethatreliesonbuilt-insorpolyfillsintothewild.


Giventhesituation,itmightbebesttowaituntilbrowserssupportnewbuilt-insholisticallybeforewe
startusingthem.Itissuggestedthatyouconsideralternativesolutionsthatdon’trelyonbuilt-ins.Atthe
sametime,it’simportanttolearnaboutthesefeatures,astonotfallbehindinourunderstandingofthe
JavaScriptlanguage.
ModernbrowserslikeChrome,Firefox,andEdgenowsupportalargeportionofES2015andbeyond,
makingtheirdevelopertoolsusefulwhenwewanttotakethesemanticsofaparticularfeatureforaspin,
providedit’ssupportedbythebrowser.Whenitcomestoproduction-gradeapplicationsthatrelyon
modernJavaScriptfeatures,atranspilationbuild-stepisadvisablesothatyourapplicationsupportsa
widerarrayofJavaScriptruntimes.
BesidestheREPL,Babeloffersacommand-linetoolwrittenasaNode.jspackage.Youcaninstallit
throughnpm,thepackagemanagerforNode.

NOTE
DownloadNode.js.Afterinstallingnode,you’llalsobeabletousethenpmcommand-linetoolinyourterminal.


Beforegettingstartedwe’llmakeaprojectdirectoryandapackage.jsonfile,whichisamanifestusedto
describeNode.jsapplications.Wecancreatethepackage.jsonfilethroughthenpmCLI:
mkdirbabel-setup
cdbabel-setup
npminit--yes

NOTE
Passingthe--yesflagtotheinitcommandconfigurespackage.jsonusingthedefaultvaluesprovidedbynpm,insteadof
askingusanyquestions.

Let’salsocreateafilenamedexample.js,containingthefollowingbitsofES6code.Saveittothebabelsetupdirectoryyou’vejustcreated,underasrcsubdirectory:
vardouble=value=>value*2
console.log(double(3))
//<-6

ToinstallBabel,enterthefollowingcoupleofcommandsintoyourfavoriteterminal:
npminstallbabel-cli​@6--save-dev
npminstallbabel-preset-env@6--save-dev


NOTE
Packagesinstalledbynpmwillbeplacedinanode_modulesdirectoryattheprojectroot.Wecanthenaccessthesepackagesby
creatingnpmscriptsorbyusingrequirestatementsinourapplication.
Usingthe--save-devflagwilladdthesepackagestoourpackage.jsonmanifestasdevelopmentdependencies,sothatwhen
copyingourprojecttonewenvironmentswecanreinstalleverydependencyjustbyrunningnpminstall.
The@notationindicateswewanttoinstallaspecificversionofapackage.Using@6we’retellingnpmtoinstallthelatestversion
ofbabel-cliinthe6.xrange.Thispreferenceishandytofuture-proofourapplications,asitwouldneverinstall7.0.0orlater
versions,whichmightcontainbreakingchangesthatcouldnothavebeenforeseenatthetimeofthiswriting.


Forthenextstep,we’llreplacethevalueofthescriptspropertyinpackage.jsonwiththefollowing.
Thebabelcommand-lineutilityprovidedbybabel-clicantaketheentirecontentsofoursrcdirectory,
compilethemintothedesiredoutputformat,andsavetheresultstoadistdirectory,whilepreservingthe
originaldirectorystructureunderadifferentroot:
{
"scripts":{
"build":"babelsrc--out-dirdist"
}
}

Togetherwiththepackageswe’veinstalledinthepreviousstep,aminimalpackage.jsonfilecouldlook
likethecodeinthefollowingsnippet:
{
"scripts":{
"build":"babelsrc--out-dirdist"
},
"devDependencies":{
"babel-cli":"^6.24.0",
"babel-preset-env":"^1.2.1"
}
}

NOTE
Anycommandsenumeratedinthescriptsobjectcanbeexecutedthroughnpmrun<name>,whichtemporarilymodifiesthe
$PATHenvironmentvariablesothatwecanrunthecommand-lineexecutablesfoundinbabel-cliwithoutinstallingbabel-cli
globallyonoursystem.

Ifyouexecutenpmrunbuildinyourterminalnow,you’llnotethatadist/example.jsfileiscreated.The
outputfilewillbeidenticaltoouroriginalfile,becauseBabeldoesn’tmakeassumptions,andwehaveto
configureitfirst.Createa.babelrcfilenexttopackage.json,andwritethefollowingJSONinit:

{
"presets":["env"]
}

Theenvpreset,whichweinstalledearliervianpm,addsaseriesofpluginstoBabelthattransform
differentbitsofES6codeintoES5.Amongotherthings,thispresettransformsarrowfunctionslikethe


oneinourexample.jsfileintoES5code.TheenvBabelpresetworksbyconvention,enablingBabel
transformationpluginsaccordingtofeaturesupportinthelatestbrowsers.Thispresetisconfigurable,
meaningwecandecidehowfarbackwewanttocoverbrowsersupport.Themorebrowserswesupport,
thelargerourtranspiledbundle.Thefewerbrowserswesupport,thefewercustomerswecansatisfy.As
always,researchisoftheessencetoidentifywhatthecorrectconfigurationfortheBabelenvpresetis.
Bydefault,everytransformisenabled,providingbroadruntimesupport.
Oncewerunourbuildscriptagain,we’llobservethattheoutputisnowvalidES5code:
»npmrunbuild
»catdist/example.js
"usestrict"
vardouble=functiondouble(value){
returnvalue*2
}
console.log(double(3))
//<-6

Let’sjumpintoadifferentkindoftool,theeslintcodelinter,whichcanhelpusestablishacodequality
baselineforourapplications.


×