you don t know js up going

background image
background image

1.

Introduction

2.

Foreword

3.

Preface

4.

Chapter1:IntoProgramming

i. Code

ii. TryItYourself

iii. Operators

iv. Values&Types

v. CodeComments

vi. Variables

vii. Blocks

viii. Conditionals

ix. Loops

x. Functions

xi. Practice

5.

Chapter2:IntoJavaScript

i. Values&Types

ii. Variables

iii. Conditionals

iv. StrictMode

v. FunctionsAsValues

vi. `this`Keyword

vii. Prototypes

viii. Old&New

ix. Non-JavaScript

6.

Chapter3:IntoYDKJS

i. Scope&Closures

ii. this&ObjectPrototypes

iii. Types&Grammar

iv. Async&Performance

v. ES6&Beyond

7.

AppendixA:ThankYou's!

TableofContents

YouDon'tKnowJS:Up&Going

2

background image

ThisisaseriesofbooksdivingdeepintothecoremechanismsoftheJavaScriptlanguage.

PleasefeelfreetocontributetothequalityofthiscontentbysubmittingPR'sforimprovementstocodesnippets,

explanations,etc.Whiletypofixesarewelcomed,theywilllikelybecaughtthroughnormaleditingprocesses,andarethus

notnecessarilyasimportantforthisrepository.

Toreadmoreaboutthemotivationsandperspectivebehindthisbookseries,checkoutthe

Preface

.

Readonline(free!):

"Up&Going"

,Published:

BuyNow

,ebookformatisfree!

Readonline(free!):

"Scope&Closures"

,Published:

BuyNow

Readonline(free!):

"this&ObjectPrototypes"

,Published:

BuyNow

Readonline(free!):

"Types&Grammar"

,Published:

BuyNow

Readonline(free!):

"Async&Performance"

,Published:

BuyNow

Readonline(free!):

"ES6&Beyond"

(inproduction)

Thesebooksarebeingreleasedhereasdrafts,freetoread,butarealsobeingedited,produced,andpublishedthrough

O'Reilly.

Ifyoulikethecontentyoufindhere,andwanttosupportmorecontentlikeit,pleasepurchasethebooksoncetheyare

availableforsale,throughyournormalbooksources.:)

Ifyou'dliketocontributefinanciallytowardstheeffort(oranyofmyotherOSSwork)asidefrompurchasingthebooks,Ido

havea

patreon

thatIwouldalwaysappreciateyourgenerositytowards.

ThecontentforthesebooksderivesheavilyfromaseriesoftrainingmaterialsIteachprofessionally(inbothpublicand

private-corporateworkshopformat),called"AdvancedJS:The'WhatYouNeedToKnow'Parts".

Ifyoulikethiscontentandwouldliketocontactmeregardingconductingtrainingonthese,orothervarious

JS/HTML5/node.jstopics,pleasereachouttomethroughanyofthesechannelslistedhere:

http://getify.me

IalsohavesomeJStrainingmaterialavailableinon-demandvideoformat.Iteachcoursesthrough

FrontendMasters

,like

YouDon'tKnowJS(bookseries)

Titles

Publishing

In-personTraining

OnlineVideoTraining

YouDon'tKnowJS:Up&Going

3

Introduction

background image

my

AdvancedJS

workshop(morecoursescomingsoon!).

Thatsamecourseisalso

availablethroughPluralsight

.

Anycontributionsyoumaketothiseffortareofcoursegreatlyappreciated.

However,ifyouchoosetocontributecontent(notjusttypocorrections)tothisrepo,youagreethatyou'regivingmeanon-

exclusivelicensetousethatcontentforthebookseries,asI(andO'Reilly)deemappropriate.Youprobablyguessedthat

already,butwejusthavetomakethelawyershappybyexplicitlystatingit.

So:blah,blah,blah...:)

Thematerialshereinareall(c)2013-2015KyleSimpson.

Thisworkislicensedundera

CreativeCommonsAttribution-NonCommercial-NoDerivs3.0UnportedLicense

.

ContentContributions

License&Copyright

YouDon'tKnowJS:Up&Going

4

Introduction

background image

Whatwasthelastnewthingyoulearned?

Perhapsitwasaforeignlanguage,likeItalianorGerman.Ormaybeitwasagraphicseditor,likePhotoshop.Oracooking

techniqueorwoodworkingoranexerciseroutine.Iwantyoutorememberthatfeelingwhenyoufinallygotit:thelightbulb

moment.Whenthingswentfromblurrytocrystalclear,asyoumasteredthetablesaworunderstoodthedifference

betweenmasculineandfemininenounsinFrench.Howdiditfeel?Prettyamazing,right?

NowIwantyoutotravelbackalittlebitfurtherinyourmemorytorightbeforeyoulearnedyournewskill.Howdidthatfeel?

Probablyslightlyintimidatingandmaybealittlebitfrustrating,right?Atonepoint,wealldidnotknowthethingsthatwe

knownowandthat’stotallyOK;weallstartsomewhere.Learningnewmaterialisanexcitingadventure,especiallyifyou

arelookingtolearnthesubjectefficiently.

Iteachalotofbeginnercodingclasses.Thestudentswhotakemyclasseshaveoftentriedteachingthemselvessubjects

likeHTMLorJavaScriptbyreadingblogpostsorcopyingandpastingcode,buttheyhaven’tbeenabletotrulymasterthe

materialthatwillallowthemtocodetheirdesiredoutcome.Andbecausetheydon’ttrulygrasptheinsandoutsofcertain

codingtopics,theycan’twritepowerfulcodeordebugtheirownwork,astheydon’treallyunderstandwhatishappening.

Ialwaysbelieveinteachingmyclassestheproperway,meaningIteachwebstandards,semanticmarkup,well-

commentedcode,andotherbestpractices.Icoverthesubjectinathoroughmannertoexplainthehowsandwhys,without

justtossingoutcodetocopyandpaste.Whenyoustrivetocomprehendyourcode,youcreatebetterworkandbecome

betteratwhatyoudo.Thecodeisn’tjustyourjobanymore,it’syourcraft.ThisiswhyIloveUp&Going.Kyletakesusona

deepdivethroughsyntaxandterminologytogiveagreatintroductiontoJavaScriptwithoutcuttingcorners.Thisbook

doesn’tskimoverthesurface,butreallyallowsustogenuinelyunderstandtheconceptswewillbewriting.

Becauseit’snotenoughtobeabletoduplicatejQuerysnippetsintoyourwebsite,thesamewayit’snotenoughtolearn

howtoopen,close,andsaveadocumentinPhotoshop.Sure,onceIlearnafewbasicsabouttheprogramIcouldcreate

andshareadesignImade.Butwithoutlegitimatelyknowingthetoolsandwhatisbehindthem,howcanIdefineagrid,or

craftalegibletypesystem,oroptimizegraphicsforwebuse.ThesamegoesforJavaScript.Withoutknowinghowloops

work,orhowtodefinevariables,orwhatscopeis,wewon’tbewritingthebestcodewecan.Wedon’twanttosettlefor

anythingless--thisis,afterall,ourcraft.

ThemoreyouareexposedtoJavaScript,thecleareritbecomes.Wordslikeclosures,objects,andmethodsmightseem

outofreachtoyounow,butthisbookwillhelpthosetermscomeintoclarity.Iwantyoutokeepthosetwofeelingsofbefore

andafteryoulearnsomethinginmindasyoubeginthisbook.Itmightseemdaunting,butyou’vepickedupthisbook

becauseyouarestartinganawesomejourneytohoneyourknowledge.Up&Goingisthestartofourpathto

understandingprogramming.Enjoythelightbulbmoments!

JennLukas

jennlukas.com

,

@jennlukas

Front-endconsultant

Foreword

YouDon'tKnowJS:Up&Going

5

Foreword

background image

I'msureyounoticed,but"JS"inthebookseriestitleisnotanabbreviationforwordsusedtocurseaboutJavaScript,

thoughcursingatthelanguage'squirksissomethingwecanprobablyallidentifywith!

Fromtheearliestdaysoftheweb,JavaScripthasbeenafoundationaltechnologythatdrivesinteractiveexperiencearound

thecontentweconsume.Whileflickeringmousetrailsandannoyingpop-uppromptsmaybewhereJavaScriptstarted,

nearly2decadeslater,thetechnologyandcapabilityofJavaScripthasgrownmanyordersofmagnitude,andfewdoubtits

importanceattheheartoftheworld'smostwidelyavailablesoftwareplatform:theweb.

Butasalanguage,ithasperpetuallybeenatargetforagreatdealofcriticism,owingpartlytoitsheritagebutevenmoreto

itsdesignphilosophy.Eventhenameevokes,asBrendanEichonceputit,"dumbkidbrother"statusnexttoitsmore

matureolderbrother"Java".Butthenameismerelyanaccidentofpoliticsandmarketing.Thetwolanguagesarevastly

differentinmanyimportantways."JavaScript"isasrelatedto"Java"as"Carnival"isto"Car".

BecauseJavaScriptborrowsconceptsandsyntaxidiomsfromseverallanguages,includingproudC-styleproceduralroots

aswellassubtle,lessobviousScheme/Lisp-stylefunctionalroots,itisexceedinglyapproachabletoabroadaudienceof

developers,eventhosewithjustlittletonoprogrammingexperience.The"HelloWorld"ofJavaScriptissosimplethatthe

languageisinvitingandeasytogetcomfortablewithinearlyexposure.

WhileJavaScriptisperhapsoneoftheeasiestlanguagestogetupandrunningwith,itseccentricitiesmakesolidmastery

ofthelanguageavastlylesscommonoccurrencethaninmanyotherlanguages.Whereittakesaprettyin-depth

knowledgeofalanguagelikeCorC++towriteafull-scaleprogram,full-scaleproductionJavaScriptcan,andoftendoes,

barelyscratchthesurfaceofwhatthelanguagecando.

Sophisticatedconceptswhicharedeeplyrootedintothelanguagetendinsteadtosurfacethemselvesinseemingly

simplisticways,suchaspassingaroundfunctionsascallbacks,whichencouragestheJavaScriptdevelopertojustusethe

languageas-isandnotworrytoomuchaboutwhat'sgoingonunderthehood.

Itissimultaneouslyasimple,easy-to-uselanguagethathasbroadappeal,andacomplexandnuancedcollectionof

languagemechanicswhichwithoutcarefulstudywilleludetrueunderstandingevenforthemostseasonedofJavaScript

developers.

ThereinliestheparadoxofJavaScript,theAchilles'Heelofthelanguage,thechallengewearepresentlyaddressing.

BecauseJavaScriptcanbeusedwithoutunderstanding,theunderstandingofthelanguageisoftenneverattained.

IfateverypointthatyouencounterasurpriseorfrustrationinJavaScript,yourresponseistoaddittotheblacklist,as

someareaccustomedtodoing,yousoonwillberelegatedtoahollowshelloftherichnessofJavaScript.

Whilethissubsethasbeenfamouslydubbed"TheGoodParts",Iwouldimploreyou,dearreader,toinsteadconsideritthe

"TheEasyParts","TheSafeParts",oreven"TheIncompleteParts".

ThisYouDon'tKnowJavaScriptbookseriesoffersacontrarychallenge:learnanddeeplyunderstandallofJavaScript,

evenandespecially"TheToughParts".

Here,weaddressheadonthetendencyofJSdeveloperstolearn"justenough"togetby,withouteverforcingthemselves

tolearnexactlyhowandwhythelanguagebehavesthewayitdoes.Furthermore,weeschewthecommonadviceto

retreatwhentheroadgetsrough.

Iamnotcontent,norshouldyoube,atstoppingoncesomethingjustworks,andnotreallyknowingwhy.Igentlychallenge

Preface

Mission

YouDon'tKnowJS:Up&Going

6

Preface

background image

youtojourneydownthatbumpy"roadlesstraveled"andembraceallthatJavaScriptisandcando.Withthatknowledge,

notechnique,noframework,nopopularbuzzwordacronymoftheweek,willbebeyondyourunderstanding.

Thesebookseachtakeonspecificcorepartsofthelanguagewhicharemostcommonlymisunderstoodorunder-

understood,anddiveverydeepandexhaustivelyintothem.Youshouldcomeawayfromreadingwithafirmconfidencein

yourunderstanding,notjustofthetheoretical,butthepractical"whatyouneedtoknow"bits.

TheJavaScriptyouknowrightnowisprobablypartshandeddowntoyoubyotherswho'vebeenburnedbyincomplete

understanding.ThatJavaScriptisbutashadowofthetruelanguage.Youdon'treallyknowJavaScript,yet,butifyoudig

intothisseries,youwill.Readon,myfriends.JavaScriptawaitsyou.

JavaScriptisawesome.It'seasytolearnpartially,andmuchhardertolearncompletely(orevensufficiently).When

developersencounterconfusion,theyusuallyblamethelanguageinsteadoftheirlackofunderstanding.Thesebooksaim

tofixthat,inspiringastrongappreciationforthelanguageyoucannow,andshould,deeplyknow.

Note:Manyoftheexamplesinthisbookassumemodern(andfuture-reaching)JavaScriptengineenvironments,suchas

ES6.Somecodemaynotworkasdescribedifruninolder(pre-ES6)engines.

Summary

YouDon'tKnowJS:Up&Going

7

Preface

background image

WelcometotheYouDon'tKnowJS(YDKJS)series.

Up&Goingisanintroductiontoseveralbasicconceptsofprogramming--ofcourseweleantowardJavaScript(often

abbreviatedJS)specifically--andhowtoapproachandunderstandtherestofthetitlesinthisseries.Especiallyifyou're

justgettingintoprogrammingand/orJavaScript,thisbookwillbrieflyexplorewhatyouneedtogetupandgoing.

Thisbookstartsoffexplainingthebasicprinciplesofprogrammingataveryhighlevel.It'smostlyintendedifyouare

startingYDKJSwithlittletonopriorprogrammingexperience,andarelookingtothesebookstohelpgetyoustartedalong

apathtounderstandingprogrammingthroughthelensofJavaScript.

Chapter1shouldbeapproachedasaquickoverviewofthethingsyou'llwanttolearnmoreaboutandpracticetogetinto

programming.Therearealsomanyotherfantasticprogrammingintroductionresourcesthatcanhelpyoudigintothese

topicsfurther,andIencourageyoutolearnfromtheminadditiontothischapter.

Onceyoufeelcomfortablewithgeneralprogrammingbasics,Chapter2willhelpguideyoutoafamiliaritywithJavaScript's

flavorofprogramming.Chapter2introduceswhatJavaScriptisabout,butagain,it'snotacomprehensiveguide--that's

whattherestoftheYDKJSbooksarefor!

Ifyou'realreadyfairlycomfortablewithJavaScript,firstcheckoutChapter3asabriefglimpseofwhattoexpectfrom

YDKJS,thenjumprightin!

Let'sstartfromthebeginning.

Aprogram,oftenreferredtoassourcecodeorjustcode,isasetofspecialinstructionstotellthecomputerwhattasksto

perform.Usuallycodeissavedinatextfile,althoughwithJavaScriptyoucanalsotypecodedirectlyintoadeveloper

consoleinabrowser,whichwe'llcovershortly.

Therulesforvalidformatandcombinationsofinstructionsiscalledacomputerlanguage,sometimesreferredtoasits

syntax,muchthesameasEnglishtellsyouhowtospellwordsandhowtocreatevalidsentencesusingwordsand

punctuation.

Inacomputerlanguage,agroupofwords,numbers,andoperatorsthatperformsaspecifictaskisastatement.In

JavaScript,astatementmightlookasfollows:

a=b*

2

;

Thecharacters

a

and

b

arecalledvariables(see"Variables"),whicharelikesimpleboxesyoucanstoreanyofyourstuff

in.Inprograms,variablesholdvalues(likethenumber

42

)tobeusedbytheprogram.Thinkofthemassymbolic

placeholdersforthevaluesthemselves.

Bycontrast,the

2

isjustavalueitself,calledaliteralvalue,becauseitstandsalonewithoutbeingstoredinavariable.

The

=

and

*

charactersareoperators(see"Operators")--theyperformactionswiththevaluesandvariablessuchas

assignmentandmathematicmultiplication.

Chapter1:IntoProgramming

Code

Statements

YouDon'tKnowJS:Up&Going

8

Chapter1:IntoProgramming

background image

MoststatementsinJavaScriptconcludewithasemicolon(

;

)attheend.

Thestatement

a=b*2;

tellsthecomputer,roughly,togetthecurrentvaluestoredinthevariable

b

,multiplythatvalue

by

2

,thenstoretheresultbackintoanothervariablewecall

a

.

Programsarejustcollectionsofmanysuchstatements,whichtogetherdescribeallthestepsthatittakestoperformyour

program'spurpose.

Statementsaremadeupofoneormoreexpressions.Anexpressionisanyreferencetoavariableorvalue,orasetof

variable(s)andvalue(s)combinedwithoperators.

Forexample:

a=b*

2

;

Thisstatementhasfourexpressionsinit:

2

isaliteralvalueexpression

b

isavariableexpression,whichmeanstoretrieveitscurrentvalue

b*2

isanarithmeticexpression,whichmeanstodothemultiplication

a=b*2

isanassignmentexpression,whichmeanstoassigntheresultofthe

b*2

expressiontothevariable

a

(moreonassignmentslater)

Ageneralexpressionthatstandsaloneisalsocalledanexpressionstatement,suchasthefollowing:

b*

2

;

Thisflavorofexpressionstatementisnotverycommonoruseful,asgenerallyitwouldn'thaveanyeffectontherunningof

theprogram--itwouldretrievethevalueof

b

andmultiplyitby

2

,butthenwouldn'tdoanythingwiththatresult.

Amorecommonexpressionstatementisacallexpressionstatement(see"Functions"),astheentirestatementisthe

functioncallexpressionitself:

alert(a);

Howdothosecollectionsofprogrammingstatementstellthecomputerwhattodo?Theprogramneedstobeexecuted,

alsoreferredtoasrunningtheprogram.

Statementslike

a=b*2

arehelpfulfordeveloperswhenreadingandwriting,butarenotactuallyinaformthecomputer

candirectlyunderstand.Soaspecialutilityonthecomputer(eitheraninterpreteroracompiler)isusedtotranslatethe

codeyouwriteintocommandsacomputercanunderstand.

Forsomecomputerlanguages,thistranslationofcommandsistypicallydonefromtoptobottom,linebyline,everytime

theprogramisrun,whichisusuallycalledinterpretingthecode.

Forotherlanguages,thetranslationisdoneaheadoftime,calledcompilingthecode,sowhentheprogramrunslater,

what'srunningisactuallythealreadycompiledcomputerinstructionsreadytogo.

Expressions

ExecutingaProgram

YouDon'tKnowJS:Up&Going

9

Chapter1:IntoProgramming

background image

It'stypicallyassertedthatJavaScriptisinterpreted,becauseyourJavaScriptsourcecodeisprocessedeachtimeit'srun.

Butthat'snotentirelyaccurate.TheJavaScriptengineactuallycompilestheprogramontheflyandthenimmediatelyruns

thecompiledcode.

Note:FormoreinformationonJavaScriptcompiling,seethefirsttwochaptersoftheScope&Closurestitleofthisseries.

Thischapterisgoingtointroduceeachprogrammingconceptwithsimplesnippetsofcode,allwritteninJavaScript

(obviously!).

Itcannotbeemphasizedenough:whileyougothroughthischapter--andyoumayneedtospendthetimetogooverit

severaltimes--youshouldpracticeeachoftheseconceptsbytypingthecodeyourself.Theeasiestwaytodothatisto

openupthedevelopertoolsconsoleinyournearestbrowser(Firefox,Chrome,IE,etc.).

Tip:Typically,youcanlaunchthedeveloperconsolewithakeyboardshortcutorfromamenuitem.Formoredetailed

informationaboutlaunchingandusingtheconsoleinyourfavoritebrowser,see"MasteringTheDeveloperToolsConsole"

(

http://blog.teamtreehouse.com/mastering-developer-tools-console

).Totypemultiplelinesintotheconsoleatonce,use

<shift>+<enter>

tomovetothenextnewline.Onceyouhit

<enter>

byitself,theconsolewillruneverythingyou'vejust

typed.

Let'sgetfamiliarwiththeprocessofrunningcodeintheconsole.First,Isuggestopeningupanemptytabinyourbrowser.

Iprefertodothisbytyping

about:blank

intotheaddressbar.Then,makesureyourdeveloperconsoleisopen,aswejust

mentioned.

Now,typethiscodeandseehowitruns:

a=

21

;

b=a*

2

;

console

.log(b);

TypingtheprecedingcodeintotheconsoleinChromeshouldproducesomethinglikethefollowing:

Goon,tryit.Thebestwaytolearnprogrammingistostartcoding!

Inthepreviouscodesnippet,weused

console.log(..)

.Briefly,let'slookatwhatthatlineofcodeisallabout.

TryItYourself

Output

YouDon'tKnowJS:Up&Going

10

Chapter1:IntoProgramming

background image

Youmayhaveguessed,butthat'sexactlyhowweprinttext(akaoutputtotheuser)inthedeveloperconsole.Therearetwo

characteristicsofthatstatementthatweshouldexplain.

First,the

log(b)

partisreferredtoasafunctioncall(see"Functions").What'shappeningiswe'rehandingthe

b

variabletothatfunction,whichasksittotakethevalueof

b

andprintittotheconsole.

Second,the

console.

partisanobjectreferencewherethe

log(..)

functionislocated.Wecoverobjectsandtheir

propertiesinmoredetailinChapter2.

Anotherwayofcreatingoutputthatyoucanseeistorunan

alert(..)

statement.Forexample:

alert(b);

Ifyourunthat,you'llnoticethatinsteadofprintingtheoutputtotheconsole,itshowsapopup"OK"boxwiththecontentsof

the

b

variable.However,using

console.log(..)

isgenerallygoingtomakelearningaboutcodingandrunningyour

programsintheconsoleeasierthanusing

alert(..)

,becauseyoucanoutputmanyvaluesatoncewithoutinterruptingthe

browserinterface.

Forthisbook,we'lluse

console.log(..)

foroutput.

Whilewe'rediscussingoutput,youmayalsowonderaboutinput(i.e.,receivinginformationfromtheuser).

ThemostcommonwaythathappensisfortheHTMLpagetoshowformelements(liketextboxes)toauserthattheycan

typeinto,andthenusingJStoreadthosevaluesintoyourprogram'svariables.

Butthere'saneasierwaytogetinputforsimplelearninganddemonstrationpurposessuchaswhatyou'llbedoing

throughoutthisbook.Usethe

prompt(..)

function:

age=prompt(

"Pleasetellmeyourage:"

);

console

.log(age);

Asyoumayhaveguessed,themessageyoupassto

prompt(..)

--inthiscase,

"Pleasetellmeyourage:"

--isprinted

intothepopup.

Thisshouldlooksimilartothefollowing:

Input

YouDon'tKnowJS:Up&Going

11

Chapter1:IntoProgramming

background image

Onceyousubmittheinputtextbyclicking"OK,"you'llobservethatthevalueyoutypedisstoredinthe

age

variable,which

wethenoutputwith

console.log(..)

:

Tokeepthingssimplewhilewe'relearningbasicprogrammingconcepts,theexamplesinthisbookwillnotrequireinput.

Butnowthatyou'veseenhowtouse

prompt(..)

,ifyouwanttochallengeyourselfyoucantrytouseinputinyour

explorationsoftheexamples.

Operatorsarehowweperformactionsonvariablesandvalues.We'vealreadyseentwoJavaScriptoperators,the

=

and

the

*

.

The

*

operatorperformsmathematicmultiplication.Simpleenough,right?

The

=

equalsoperatorisusedforassignment--wefirstcalculatethevalueontheright-handside(sourcevalue)ofthe

=

andthenputitintothevariablethatwespecifyontheleft-handside(targetvariable).

Warning:Thismayseemlikeastrangereverseordertospecifyassignment.Insteadof

a=42

,somemightprefertoflip

theordersothesourcevalueisontheleftandthetargetvariableisontheright,like

42->a

(thisisnotvalidJavaScript!).

Unfortunately,the

a=42

orderedform,andsimilarvariations,isquiteprevalentinmodernprogramminglanguages.Ifit

feelsunnatural,justspendsometimerehearsingthatorderinginyourmindtogetaccustomedtoit.

Consider:

a=

2

;

b=a+

1

;

Operators

YouDon'tKnowJS:Up&Going

12

Chapter1:IntoProgramming

background image

Here,weassignthe

2

valuetothe

a

variable.Then,wegetthevalueofthe

a

variable(still

2

),add

1

toitresultingin

thevalue

3

,thenstorethatvalueinthe

b

variable.

Whilenottechnicallyanoperator,you'llneedthekeyword

var

ineveryprogram,asit'stheprimarywayyoudeclare(aka

create)variables(see"Variables").

Youshouldalwaysdeclarethevariablebynamebeforeyouuseit.Butyouonlyneedtodeclareavariableonceforeach

scope(see"Scope");itcanbeusedasmanytimesafterthatasneeded.Forexample:

var

a=

20

;

a=a+

1

;

a=a*

2

;

console

.log(a);

//42

HerearesomeofthemostcommonoperatorsinJavaScript:

Assignment:

=

asin

a=2

.

Math:

+

(addition),

-

(subtraction),

*

(multiplication),and

/

(division),asin

a*3

.

CompoundAssignment:

+=

,

-=

,

*=

,and

/=

arecompoundoperatorsthatcombineamathoperationwith

assignment,asin

a+=2

(sameas

a=a+2

).

Increment/Decrement:

++

(increment),

--

(decrement),asin

a++

(similarto

a=a+1

).

ObjectPropertyAccess:

.

asin

console.log()

.

Objectsarevaluesthatholdothervaluesatspecificnamedlocationscalledproperties.

obj.a

meansanobjectvalue

called

obj

withapropertyofthename

a

.Propertiescanalternativelybeaccessedas

obj["a"]

.SeeChapter2.

Equality:

==

(loose-equals),

===

(strict-equals),

!=

(loosenot-equals),

!==

(strictnot-equals),asin

a==b

.

See"Values&Types"andChapter2.

Comparison:

<

(lessthan),

>

(greaterthan),

<=

(lessthanorloose-equals),

>=

(greaterthanorloose-equals),asin

a<=b

.

See"Values&Types"andChapter2.

Logical:

&&

(and),

||

(or),asin

a||b

thatselectseither

a

or

b

.

Theseoperatorsareusedtoexpresscompoundconditionals(see"Conditionals"),likeifeither

a

or

b

istrue.

Note:Formuchmoredetail,andcoverageofoperatorsnotmentionedhere,seetheMozillaDeveloperNetwork(MDN)'s

"ExpressionsandOperators"(

https://developer.mozilla.org/en-

US/docs/Web/JavaScript/Guide/Expressions_and_Operators

).

Ifyouaskanemployeeataphonestorehowmuchacertainphonecosts,andtheysay"ninety-nine,ninety-nine"(i.e.,

$99.99),they'regivingyouanactualnumericdollarfigurethatrepresentswhatyou'llneedtopay(plustaxes)tobuyit.If

youwanttobuytwoofthosephones,youcaneasilydothementalmathtodoublethatvaluetoget$199.98foryourbase

cost.

Ifthatsameemployeepicksupanothersimilarphonebutsaysit's"free"(perhapswithairquotes),they'renotgivingyoua

number,butinsteadanotherkindofrepresentationofyourexpectedcost($0.00)--theword"free."

Values&Types

YouDon'tKnowJS:Up&Going

13

Chapter1:IntoProgramming

background image

Whenyoulateraskifthephoneincludesacharger,thatanswercouldonlyhavebeeneither"yes"or"no."

Inverysimilarways,whenyouexpressvaluesinaprogram,youchoosedifferentrepresentationsforthosevaluesbased

onwhatyouplantodowiththem.

Thesedifferentrepresentationsforvaluesarecalledtypesinprogrammingterminology.JavaScripthasbuilt-intypesfor

eachofthesesocalledprimitivevalues:

Whenyouneedtodomath,youwanta

number

.

Whenyouneedtoprintavalueonthescreen,youneeda

string

(oneormorecharacters,words,sentences).

Whenyouneedtomakeadecisioninyourprogram,youneeda

boolean

(

true

or

false

).

Valuesthatareincludeddirectlyinthesourcecodearecalledliterals.

string

literalsaresurroundedbydoublequotes

"..."

orsinglequotes(

'...'

)--theonlydifferenceisstylisticpreference.

number

and

boolean

literalsarejustpresented

asis(i.e.,

42

,

true

,etc.).

Consider:

"Iamastring"

;

'Iamalsoastring'

;

42

;

true

;

false

;

Beyond

string

/

number

/

boolean

valuetypes,it'scommonforprogramminglanguagestoprovidearrays,objects,functions,

andmore.We'llcovermuchmoreaboutvaluesandtypesthroughoutthischapterandthenext.

Ifyouhavea

number

butneedtoprintitonthescreen,youneedtoconvertthevaluetoa

string

,andinJavaScriptthis

conversioniscalled"coercion."Similarly,ifsomeoneentersaseriesofnumericcharactersintoaformonanecommerce

page,that'sa

string

,butifyouneedtothenusethatvaluetodomathoperations,youneedtocoerceittoa

number

.

JavaScriptprovidesseveraldifferentfacilitiesforforciblycoercingbetweentypes.Forexample:

var

a=

"42"

;

var

b=

Number

(a);

console

.log(a);

//"42"

console

.log(b);

//42

Using

Number(..)

(abuilt-infunction)asshownisanexplicitcoercionfromanyothertypetothe

number

type.Thatshould

beprettystraightforward.

Butacontroversialtopiciswhathappenswhenyoutrytocomparetwovaluesthatarenotalreadyofthesametype,which

wouldrequireimplicitcoercion.

Whencomparingthestring

"99.99"

tothenumber

99.99

,mostpeoplewouldagreetheyareequivalent.Butthey'renot

exactlythesame,arethey?It'sthesamevalueintwodifferentrepresentations,twodifferenttypes.Youcouldsaythey're

"looselyequal,"couldn'tyou?

Tohelpyououtinthesecommonsituations,JavaScriptwillsometimeskickinandimplicitlycoercevaluestothematching

types.

ConvertingBetweenTypes

YouDon'tKnowJS:Up&Going

14

Chapter1:IntoProgramming

background image

Soifyouusethe

==

looseequalsoperatortomakethecomparison

"99.99"==99.99

,JavaScriptwillconverttheleft-hand

side

"99.99"

toits

number

equivalent

99.99

.Thecomparisonthenbecomes

99.99==99.99

,whichisofcourse

true

.

Whiledesignedtohelpyou,implicitcoercioncancreateconfusionifyouhaven'ttakenthetimetolearntherulesthat

governitsbehavior.MostJSdevelopersneverhave,sothecommonfeelingisthatimplicitcoercionisconfusingandharms

programswithunexpectedbugs,andshouldthusbeavoided.It'sevensometimescalledaflawinthedesignofthe

language.

However,implicitcoercionisamechanismthatcanbelearned,andmoreovershouldbelearnedbyanyonewishingtotake

JavaScriptprogrammingseriously.Notonlyisitnotconfusingonceyoulearntherules,itcanactuallymakeyourprograms

better!Theeffortiswellworthit.

Note:Formoreinformationoncoercion,seeChapter2ofthistitleandChapter4oftheTypes&Grammartitleofthis

series.

Thephonestoreemployeemightjotdownsomenotesonthefeaturesofanewlyreleasedphoneoronthenewplansher

companyoffers.Thesenotesareonlyfortheemployee--they'renotforcustomerstoread.Nevertheless,thesenoteshelp

theemployeedoherjobbetterbydocumentingthehowsandwhysofwhatsheshouldtellcustomers.

Oneofthemostimportantlessonsyoucanlearnaboutwritingcodeisthatit'snotjustforthecomputer.Codeiseverybit

asmuch,ifnotmore,forthedeveloperasitisforthecompiler.

Yourcomputeronlycaresaboutmachinecode,aseriesofbinary0sand1s,thatcomesfromcompilation.There'sanearly

infinitenumberofprogramsyoucouldwritethatyieldthesameseriesof0sand1s.Thechoicesyoumakeabouthowto

writeyourprogrammatter--notonlytoyou,buttoyourotherteammembersandeventoyourfutureself.

Youshouldstrivenotjusttowriteprogramsthatworkcorrectly,butprogramsthatmakesensewhenexamined.Youcango

alongwayinthateffortbychoosinggoodnamesforyourvariables(see"Variables")andfunctions(see"Functions").

Butanotherimportantpartiscodecomments.Thesearebitsoftextinyourprogramthatareinsertedpurelytoexplain

thingstoahuman.Theinterpreter/compilerwillalwaysignorethesecomments.

Therearelotsofopinionsonwhatmakeswell-commentedcode;wecan'treallydefineabsoluteuniversalrules.Butsome

observationsandguidelinesarequiteuseful:

Codewithoutcommentsissuboptimal.

Toomanycomments(oneperline,forexample)isprobablyasignofpoorlywrittencode.

Commentsshouldexplainwhy,notwhat.Theycanoptionallyexplainhowifthat'sparticularlyconfusing.

InJavaScript,therearetwotypesofcommentspossible:asingle-linecommentandamultilinecomment.

Consider:

//Thisisasingle-linecomment

/*Butthisis

amultiline

comment.

*/

The

//

single-linecommentisappropriateifyou'regoingtoputacommentrightaboveasinglestatement,orevenatthe

endofaline.Everythingonthelineafterthe

//

istreatedasthecomment(andthusignoredbythecompiler),alltheway

CodeComments

YouDon'tKnowJS:Up&Going

15

Chapter1:IntoProgramming

background image

totheendoftheline.There'snorestrictiontowhatcanappearinsideasingle-linecomment.

Consider:

var

a=

42

;

//42isthemeaningoflife

The

/*..*/

multilinecommentisappropriateifyouhaveseverallinesworthofexplanationtomakeinyourcomment.

Here'sacommonusageofmultilinecomments:

/*Thefollowingvalueisusedbecause

ithasbeenshownthatitanswers

everyquestionintheuniverse.*/

var

a=

42

;

Itcanalsoappearanywhereonaline,eveninthemiddleofaline,becausethe

*/

endsit.Forexample:

var

a=

/*arbitraryvalue*/

42

;

console

.log(a);

//42

Theonlythingthatcannotappearinsideamultilinecommentisa

*/

,becausethatwouldbeinterpretedtoendthe

comment.

Youwilldefinitelywanttobeginyourlearningofprogrammingbystartingoffwiththehabitofcommentingcode.Throughout

therestofthischapter,you'llseeIusecommentstoexplainthings,sodothesameinyourownpractice.Trustme,

everyonewhoreadsyourcodewillthankyou!

Mostusefulprogramsneedtotrackavalueasitchangesoverthecourseoftheprogram,undergoingdifferentoperations

ascalledforbyyourprogram'sintendedtasks.

Theeasiestwaytogoaboutthatinyourprogramistoassignavaluetoasymboliccontainer,calledavariable--socalled

becausethevalueinthiscontainercanvaryovertimeasneeded.

Insomeprogramminglanguages,youdeclareavariable(container)toholdaspecifictypeofvalue,suchas

number

or

string

.Statictyping,otherwiseknownastypeenforcement,istypicallycitedasabenefitforprogramcorrectnessby

preventingunintendedvalueconversions.

Otherlanguagesemphasizetypesforvaluesinsteadofvariables.Weaktyping,otherwiseknownasdynamictyping,allows

avariabletoholdanytypeofvalueatanytime.It'stypicallycitedasabenefitforprogramflexibilitybyallowingasingle

variabletorepresentavaluenomatterwhattypeformthatvaluemaytakeatanygivenmomentintheprogram'slogicflow.

JavaScriptusesthelatterapproach,dynamictyping,meaningvariablescanholdvaluesofanytypewithoutanytype

enforcement.

Asmentionedearlier,wedeclareavariableusingthe

var

statement--noticethere'snoothertypeinformationinthe

declaration.Considerthissimpleprogram:

var

amount=

99.99

;

Variables

YouDon'tKnowJS:Up&Going

16

Chapter1:IntoProgramming

background image

amount=amount*

2

;

console

.log(amount);

//199.98

//convert`amount`toastring,and

//add"$"onthebeginning

amount=

"$"

+

String

(amount);

console

.log(amount);

//"$199.98"

The

amount

variablestartsoutholdingthenumber

99.99

,andthenholdsthe

number

resultof

amount*2

,whichis

199.98

.

Thefirst

console.log(..)

commandhastoimplicitlycoercethat

number

valuetoa

string

toprintitout.

Thenthestatement

amount="$"+String(amount)

explicitlycoercesthe

199.98

valuetoa

string

andaddsa

"$"

charactertothebeginning.Atthispoint,

amount

nowholdsthe

string

value

"$199.98"

,sothesecond

console.log(..)

statementdoesn'tneedtodoanycoerciontoprintitout.

JavaScriptdeveloperswillnotetheflexibilityofusingthe

amount

variableforeachofthe

99.99

,

199.98

,andthe

"$199.98"

values.Static-typingenthusiastswouldpreferaseparatevariablelike

amountStr

toholdthefinal

"$199.98"

representationofthevalue,becauseit'sadifferenttype.

Eitherway,you'llnotethat

amount

holdsarunningvaluethatchangesoverthecourseoftheprogram,illustratingthe

primarypurposeofvariables:managingprogramstate.

Inotherwords,stateistrackingthechangestovaluesasyourprogramruns.

Anothercommonusageofvariablesisforcentralizingvaluesetting.Thisismoretypicallycalledconstants,whenyou

declareavariablewithavalueandintendforthatvaluetonotchangethroughouttheprogram.

Youdeclaretheseconstants,oftenatthetopofaprogram,sothatit'sconvenientforyoutohaveoneplacetogotoaltera

valueifyouneedto.Byconvention,JavaScriptvariablesasconstantsareusuallycapitalized,withunderscores

_

between

multiplewords.

Here'sasillyexample:

var

TAX_RATE=

0.08

;

//8%salestax

var

amount=

99.99

;

amount=amount*

2

;

amount=amount+(amount*TAX_RATE);

console

.log(amount);

//215.9784

console

.log(amount.toFixed(

2

));

//"215.98"

Note:Similartohow

console.log(..)

isafunction

log(..)

accessedasanobjectpropertyonthe

console

value,

toFixed(..)

hereisafunctionthatcanbeaccessedon

number

values.JavaScript

number

saren'tautomaticallyformatted

fordollars--theenginedoesn'tknowwhatyourintentisandthere'snotypeforcurrency.

toFixed(..)

letsusspecifyhow

manydecimalplaceswe'dlikethe

number

roundedto,anditproducesthe

string

asnecessary.

The

TAX_RATE

variableisonlyconstantbyconvention--there'snothingspecialinthisprogramthatpreventsitfrombeing

changed.Butifthecityraisesthesalestaxrateto9%,wecanstilleasilyupdateourprogrambysettingthe

TAX_RATE

assignedvalueto

0.09

inoneplace,insteadoffindingmanyoccurrencesofthevalue

0.08

strewnthroughoutthe

programandupdatingallofthem.

YouDon'tKnowJS:Up&Going

17

Chapter1:IntoProgramming

background image

ThenewestversionofJavaScriptatthetimeofthiswriting(commonlycalled"ES6")includesanewwaytodeclare

constants,byusing

const

insteadof

var

:

//asofES6:

const

TAX_RATE=

0.08

;

var

amount=

99.99

;

//..

Constantsareusefuljustlikevariableswithunchangedvalues,exceptthatconstantsalsopreventaccidentallychanging

valuesomewhereelseaftertheinitialsetting.Ifyoutriedtoassignanydifferentvalueto

TAX_RATE

afterthatfirst

declaration,yourprogramwouldrejectthechange(andinstrictmode,failwithanerror--see"StrictMode"inChapter2).

Bytheway,thatkindof"protection"againstmistakesissimilartothestatic-typingtypeenforcement,soyoucanseewhy

statictypesinotherlanguagescanbeattractive!

Note:Formoreinformationabouthowdifferentvaluesinvariablescanbeusedinyourprograms,seetheTypes&

Grammartitleofthisseries.

Thephonestoreemployeemustgothroughaseriesofstepstocompletethecheckoutasyoubuyyournewphone.

Similarly,incodeweoftenneedtogroupaseriesofstatementstogether,whichweoftencallablock.InJavaScript,ablock

isdefinedbywrappingoneormorestatementsinsideacurly-bracepair

{..}

.Consider:

var

amount=

99.99

;

//ageneralblock

{

amount=amount*

2

;

console

.log(amount);

//199.98

}

Thiskindofstandalone

{..}

generalblockisvalid,butisn'tascommonlyseeninJSprograms.Typically,blocksare

attachedtosomeothercontrolstatement,suchasan

if

statement(see"Conditionals")oraloop(see"Loops").For

example:

var

amount=

99.99

;

//isamountbigenough?

if

(amount>

10

){

//<--blockattachedto`if`

amount=amount*

2

;

console

.log(amount);

//199.98

}

We'llexplain

if

statementsinthenextsection,butasyoucansee,the

{..}

blockwithitstwostatementsisattachedto

if(amount>10)

;thestatementsinsidetheblockwillonlybeprocessediftheconditionalpasses.

Note:Unlikemostotherstatementslike

console.log(amount);

,ablockstatementdoesnotneedasemicolon(

;

)to

concludeit.

Blocks

Conditionals

YouDon'tKnowJS:Up&Going

18

Chapter1:IntoProgramming

background image

"Doyouwanttoaddontheextrascreenprotectorstoyourpurchase,for$9.99?"Thehelpfulphonestoreemployeehas

askedyoutomakeadecision.Andyoumayneedtofirstconsultthecurrentstateofyourwalletorbankaccounttoanswer

thatquestion.Butobviously,thisisjustasimple"yesorno"question.

Therearequiteafewwayswecanexpressconditionals(akadecisions)inourprograms.

Themostcommononeisthe

if

statement.Essentially,you'resaying,"Ifthisconditionistrue,dothefollowing...".For

example:

var

bank_balance=

302.13

;

var

amount=

99.99

;

if

(amount<bank_balance){

console

.log(

"Iwanttobuythisphone!"

);

}

The

if

statementrequiresanexpressioninbetweentheparentheses

()

thatcanbetreatedaseither

true

or

false

.In

thisprogram,weprovidedtheexpression

amount<bank_balance

,whichindeedwilleitherevaluateto

true

or

false

dependingontheamountinthe

bank_balance

variable.

Youcanevenprovideanalternativeiftheconditionisn'ttrue,calledan

else

clause.Consider:

const

ACCESSORY_PRICE=

9.99

;

var

bank_balance=

302.13

;

var

amount=

99.99

;

amount=amount*

2

;

//canweaffordtheextrapurchase?

if

(amount<bank_balance){

console

.log(

"I'lltaketheaccessory!"

);

amount=amount+ACCESSORY_PRICE;

}

//otherwise:

else

{

console

.log(

"No,thanks."

);

}

Here,if

amount<bank_balance

is

true

,we'llprintout

"I'lltaketheaccessory!"

andaddthe

9.99

toour

amount

variable.Otherwise,the

else

clausesayswe'lljustpolitelyrespondwith

"No,thanks."

andleave

amount

unchanged.

Aswediscussedin"Values&Types"earlier,valuesthataren'talreadyofanexpectedtypeareoftencoercedtothattype.

The

if

statementexpectsa

boolean

,butifyoupassitsomethingthat'snotalready

boolean

,coercionwilloccur.

JavaScriptdefinesalistofspecificvaluesthatareconsidered"falsy"becausewhencoercedtoa

boolean

,theybecome

false

--theseincludevalueslike

0

and

""

.Anyothervaluenotonthe"falsy"listisautomatically"truthy"--when

coercedtoa

boolean

theybecome

true

.Truthyvaluesincludethingslike

99.99

and

"free"

.See"Truthy&Falsy"in

Chapter2formoreinformation.

Conditionalsexistinotherformsbesidesthe

if

.Forexample,the

switch

statementcanbeusedasashorthandfora

seriesof

if..else

statements(seeChapter2).Loops(see"Loops")useaconditionaltodetermineiftheloopshouldkeep

goingorstop.

Note:Fordeeperinformationaboutthecoercionsthatcanoccurimplicitlyinthetestexpressionsofconditionals,see

Chapter4oftheTypes&Grammartitleofthisseries.

Loops

YouDon'tKnowJS:Up&Going

19

Chapter1:IntoProgramming

background image

Duringbusytimes,there'sawaitinglistforcustomerswhoneedtospeaktothephonestoreemployee.Whilethere'sstill

peopleonthatlist,shejustneedstokeepservingthenextcustomer.

Repeatingasetofactionsuntilacertainconditionfails--inotherwords,repeatingonlywhiletheconditionholds--isthe

jobofprogrammingloops;loopscantakedifferentforms,buttheyallsatisfythisbasicbehavior.

Aloopincludesthetestconditionaswellasablock(typicallyas

{..}

).Eachtimetheloopblockexecutes,that'scalled

aniteration.

Forexample,the

while

loopandthe

do..while

loopformsillustratetheconceptofrepeatingablockofstatementsuntila

conditionnolongerevaluatesto

true

:

while

(numOfCustomers>

0

){

console

.log(

"HowmayIhelpyou?"

);

//helpthecustomer...

numOfCustomers=numOfCustomers-

1

;

}

//versus:

do

{

console

.log(

"HowmayIhelpyou?"

);

//helpthecustomer...

numOfCustomers=numOfCustomers-

1

;

}

while

(numOfCustomers>

0

);

Theonlypracticaldifferencebetweentheseloopsiswhethertheconditionalistestedbeforethefirstiteration(

while

)or

afterthefirstiteration(

do..while

).

Ineitherform,iftheconditionaltestsas

false

,thenextiterationwillnotrun.Thatmeansiftheconditionisinitially

false

,a

while

loopwillneverrun,buta

do..while

loopwillrunjustthefirsttime.

Sometimesyouareloopingfortheintendedpurposeofcountingacertainsetofnumbers,likefrom

0

to

9

(tennumbers).

Youcandothatbysettingaloopiterationvariablelike

i

atvalue

0

andincrementingitby

1

eachiteration.

Warning:Foravarietyofhistoricalreasons,programminglanguagesalmostalwayscountthingsinazero-basedfashion,

meaningstartingwith

0

insteadof

1

.Ifyou'renotfamiliarwiththatmodeofthinking,itcanbequiteconfusingatfirst.Take

sometimetopracticecountingstartingwith

0

tobecomemorecomfortablewithit!

Theconditionalistestedoneachiteration,muchasifthereisanimplied

if

statementinsidetheloop.

WecanuseJavaScript's

break

statementtostopaloop.Also,wecanobservethatit'sawfullyeasytocreatealoopthat

wouldotherwiserunforeverwithouta

break

ingmechanism.

Let'sillustrate:

var

i=

0

;

//a`while..true`loopwouldrunforever,right?

while

(

true

){

//stoptheloop?

if

((i<=

9

)===

false

){

break

;

}

console

.log(i);

YouDon'tKnowJS:Up&Going

20

Chapter1:IntoProgramming

background image

i=i+

1

;

}

//0123456789

Warning:Thisisnotnecessarilyapracticalformyou'dwanttouseforyourloops.It'spresentedhereforillustration

purposesonly.

Whilea

while

(or

do..while

)canaccomplishthetaskmanually,there'sanothersyntacticformcalleda

for

loopforjust

thatpurpose:

for

(

var

i=

0

;i<=

9

;i=i+

1

){

console

.log(i);

}

//0123456789

Asyoucansee,inbothcasestheconditional

i<=9

is

true

forthefirst10iterations(

i

ofvalues

0

through

9

)ofeither

loopform,butbecomes

false

once

i

isvalue

10

.

The

for

loophasthreeclauses:theinitializationclause(

vari=0

),theconditionaltestclause(

i<=9

),andtheupdate

clause(

i=i+1

).Soifyou'regoingtodocountingwithyourloopiterations,

for

isamorecompactandofteneasier

formtounderstandandwrite.

Thereareotherspecializedloopformsthatareintendedtoiterateoverspecificvalues,suchasthepropertiesofanobject

(seeChapter2)wheretheimpliedconditionaltestisjustwhetherallthepropertieshavebeenprocessed.The"loopuntila

conditionfails"conceptholdsnomatterwhattheformoftheloop.

Thephonestoreemployeeprobablydoesn'tcarryaroundacalculatortofigureoutthetaxesandfinalpurchaseamount.

That'satasksheneedstodefineonceandreuseoverandoveragain.Oddsare,thecompanyhasacheckoutregister

(computer,tablet,etc.)withthose"functions"builtin.

Similarly,yourprogramwillalmostcertainlywanttobreakupthecode'stasksintoreusablepieces,insteadofrepeatedly

repeatingyourselfrepetitiously(punintended!).Thewaytodothisistodefinea

function

.

Afunctionisgenerallyanamedsectionofcodethatcanbe"called"byname,andthecodeinsideitwillberuneachtime.

Consider:

function

printAmount

()

{

console

.log(amount.toFixed(

2

));

}

var

amount=

99.99

;

printAmount();

//"99.99"

amount=amount*

2

;

printAmount();

//"199.98"

Functionscanoptionallytakearguments(akaparameters)--valuesyoupassin.Andtheycanalsooptionallyreturna

valueback.

function

printAmount

(

amt

)

{

console

.log(amt.toFixed(

2

));

Functions

YouDon'tKnowJS:Up&Going

21

Chapter1:IntoProgramming

background image

}

function

formatAmount

()

{

return

"$"

+amount.toFixed(

2

);

}

var

amount=

99.99

;

printAmount(amount*

2

);

//"199.98"

amount=formatAmount();

console

.log(amount);

//"$99.99"

Thefunction

printAmount(..)

takesaparameterthatwecall

amt

.Thefunction

formatAmount()

returnsavalue.Ofcourse,

youcanalsocombinethosetwotechniquesinthesamefunction.

Functionsareoftenusedforcodethatyouplantocallmultipletimes,buttheycanalsobeusefuljusttoorganizerelated

bitsofcodeintonamedcollections,evenifyouonlyplantocallthemonce.

Consider:

const

TAX_RATE=

0.08

;

function

calculateFinalPurchaseAmount

(

amt

)

{

//calculatethenewamountwiththetax

amt=amt+(amt*TAX_RATE);

//returnthenewamount

return

amt;

}

var

amount=

99.99

;

amount=calculateFinalPurchaseAmount(amount);

console

.log(amount.toFixed(

2

));

//"107.99"

Although

calculateFinalPurchaseAmount(..)

isonlycalledonce,organizingitsbehaviorintoaseparatenamedfunction

makesthecodethatusesitslogic(the

amount=calculateFinal...

statement)cleaner.Ifthefunctionhadmorestatements

init,thebenefitswouldbeevenmorepronounced.

Ifyouaskthephonestoreemployeeforaphonemodelthatherstoredoesn'tcarry,shewillnotbeabletosellyouthe

phoneyouwant.Sheonlyhasaccesstothephonesinherstore'sinventory.You'llhavetotryanotherstoretoseeifyou

canfindthephoneyou'relookingfor.

Programminghasatermforthisconcept:scope(technicallycalledlexicalscope).InJavaScript,eachfunctiongetsitsown

scope.Scopeisbasicallyacollectionofvariablesaswellastherulesforhowthosevariablesareaccessedbyname.Only

codeinsidethatfunctioncanaccessthatfunction'sscopedvariables.

Avariablenamehastobeuniquewithinthesamescope--therecan'tbetwodifferent

a

variablessittingrightnexttoeach

other.Butthesamevariablename

a

couldappearindifferentscopes.

function

one

()

{

//this`a`onlybelongstothe`one()`function

var

a=

1

;

console

.log(a);

}

function

two

()

{

//this`a`onlybelongstothe`two()`function

Scope

YouDon'tKnowJS:Up&Going

22

Chapter1:IntoProgramming

background image

var

a=

2

;

console

.log(a);

}

one();

//1

two();

//2

Also,ascopecanbenestedinsideanotherscope,justlikeifaclownatabirthdaypartyblowsuponeballooninside

anotherballoon.Ifonescopeisnestedinsideanother,codeinsidetheinnermostscopecanaccessvariablesfromeither

scope.

Consider:

function

outer

()

{

var

a=

1

;

function

inner

()

{

var

b=

2

;

//wecanaccessboth`a`and`b`here

console

.log(a+b);

//3

}

inner();

//wecanonlyaccess`a`here

console

.log(a);

//1

}

outer();

Lexicalscoperulessaythatcodeinonescopecanaccessvariablesofeitherthatscopeoranyscopeoutsideofit.

So,codeinsidethe

inner()

functionhasaccesstobothvariables

a

and

b

,butcodeonlyin

outer()

hasaccessonlyto

a

--itcannotaccess

b

becausethatvariableisonlyinside

inner()

.

Recallthiscodesnippetfromearlier:

const

TAX_RATE=

0.08

;

function

calculateFinalPurchaseAmount

(

amt

)

{

//calculatethenewamountwiththetax

amt=amt+(amt*TAX_RATE);

//returnthenewamount

return

amt;

}

The

TAX_RATE

constant(variable)isaccessiblefrominsidethe

calculateFinalPurchaseAmount(..)

function,eventhoughwe

didn'tpassitin,becauseoflexicalscope.

Note:Formoreinformationaboutlexicalscope,seethefirstthreechaptersoftheScope&Closurestitleofthisseries.

Thereisabsolutelynosubstituteforpracticeinlearningprogramming.Noamountofarticulatewritingonmypartisalone

goingtomakeyouaprogrammer.

Withthatinmind,let'strypracticingsomeoftheconceptswelearnedhereinthischapter.I'llgivethe"requirements,"and

youtryitfirst.ThenconsultthecodelistingbelowtoseehowIapproachedit.

Practice

YouDon'tKnowJS:Up&Going

23

Chapter1:IntoProgramming

background image

Writeaprogramtocalculatethetotalpriceofyourphonepurchase.Youwillkeeppurchasingphones(hint:loop!)until

yourunoutofmoneyinyourbankaccount.You'llalsobuyaccessoriesforeachphoneaslongasyourpurchase

amountisbelowyourmentalspendingthreshold.

Afteryou'vecalculatedyourpurchaseamount,addinthetax,thenprintoutthecalculatedpurchaseamount,properly

formatted.

Finally,checktheamountagainstyourbankaccountbalancetoseeifyoucanafforditornot.

Youshouldsetupsomeconstantsforthe"taxrate,""phoneprice,""accessoryprice,"and"spendingthreshold,"aswell

asavariableforyour"bankaccountbalance.""

Youshoulddefinefunctionsforcalculatingthetaxandforformattingthepricewitha"$"androundingtotwodecimal

places.

BonusChallenge:Trytoincorporateinputintothisprogram,perhapswiththe

prompt(..)

coveredin"Input"earlier.

Youmayprompttheuserfortheirbankaccountbalance,forexample.Havefunandbecreative!

OK,goahead.Tryit.Don'tpeekatmycodelistinguntilyou'vegivenitashotyourself!

Note:BecausethisisaJavaScriptbook,I'mobviouslygoingtosolvethepracticeexerciseinJavaScript.Butyoucandoit

inanotherlanguagefornowifyoufeelmorecomfortable.

Here'smyJavaScriptsolutionforthisexercise:

const

SPENDING_THRESHOLD=

200

;

const

TAX_RATE=

0.08

;

const

PHONE_PRICE=

99.99

;

const

ACCESSORY_PRICE=

9.99

;

var

bank_balance=

303.91

;

var

amount=

0

;

function

calculateTax

(

amount

)

{

return

amount*TAX_RATE;

}

function

formatAmount

(

amount

)

{

return

"$"

+amount.toFixed(

2

);

}

//keepbuyingphoneswhileyoustillhavemoney

while

(amount<bank_balance){

//buyanewphone!

amount=amount+PHONE_PRICE;

//canweaffordtheaccessory?

if

(amount<SPENDING_THRESHOLD){

amount=amount+ACCESSORY_PRICE;

}

}

//don'tforgettopaythegovernment,too

amount=amount+calculateTax(amount);

console

.log(

"Yourpurchase:"

+formatAmount(amount)

);

//Yourpurchase:$334.76

//canyouactuallyaffordthispurchase?

if

(amount>bank_balance){

console

.log(

"Youcan'taffordthispurchase.:("

);

}

//Youcan'taffordthispurchase.:(

Note:ThesimplestwaytorunthisJavaScriptprogramistotypeitintothedeveloperconsoleofyournearestbrowser.

YouDon'tKnowJS:Up&Going

24

Chapter1:IntoProgramming

background image

Howdidyoudo?Itwouldn'thurttotryitagainnowthatyou'veseenmycode.Andplayaroundwithchangingsomeofthe

constantstoseehowtheprogramrunswithdifferentvalues.

Learningprogrammingdoesn'thavetobeacomplexandoverwhelmingprocess.Therearejustafewbasicconceptsyou

needtowrapyourheadaround.

Theseactlikebuildingblocks.Tobuildatalltower,youstartfirstbyputtingblockontopofblockontopofblock.Thesame

goeswithprogramming.Herearesomeoftheessentialprogrammingbuildingblocks:

Youneedoperatorstoperformactionson

Youneedvaluesandtypestoperformdifferentkindsofactionslikemathon

number

soroutputwith

string

s.

Youneedvariablestostoredata(akastate)duringyourprogram'sexecution.

Youneedconditionalslike

if

statementstomakedecisions.

Youneedloopstorepeattasksuntilaconditionstopsbeingtrue.

Youneedfunctionstoorganizeyourcodeintologicalandreusablechunks.

Codecommentsareoneeffectivewaytowritemorereadablecode,whichmakesyourprogrameasiertounderstand,

maintain,andfixlaterifthereareproblems.

Finally,don'tneglectthepowerofpractice.Thebestwaytolearnhowtowritecodeistowritecode.

I'mexcitedyou'rewellonyourwaytolearninghowtocode,now!Keepitup.Don'tforgettocheckoutotherbeginner

programmingresources(books,blogs,onlinetraining,etc.).Thischapterandthisbookareagreatstart,butthey'rejusta

briefintroduction.

Thenextchapterwillreviewmanyoftheconceptsfromthischapter,butfromamoreJavaScript-specificperspective,which

willhighlightmostofthemajortopicsthatareaddressedindeeperdetailthroughouttherestoftheseries.

Review

YouDon'tKnowJS:Up&Going

25

Chapter1:IntoProgramming

background image

Inthepreviouschapter,Iintroducedthebasicbuildingblocksofprogramming,suchasvariables,loops,conditionals,and

functions.Ofcourse,allthecodeshownhasbeeninJavaScript.Butinthischapter,wewanttofocusspecificallyonthings

youneedtoknowaboutJavaScripttogetupandgoingasaJSdeveloper.

WewillintroducequiteafewconceptsinthischapterthatwillnotbefullyexploreduntilsubsequentYDKJSbooks.Youcan

thinkofthischapterasanoverviewofthetopicscoveredindetailthroughouttherestofthisseries.

Especiallyifyou'renewtoJavaScript,youshouldexpecttospendquiteabitoftimereviewingtheconceptsandcode

examplesheremultipletimes.Anygoodfoundationislaidbrickbybrick,sodon'texpectthatyou'llimmediatelyunderstand

itallthefirstpassthrough.

YourjourneytodeeplylearnJavaScriptstartshere.

Note:AsIsaidinChapter1,youshoulddefinitelytryallthiscodeyourselfasyoureadandworkthroughthischapter.Be

awarethatsomeofthecodehereassumescapabilitiesintroducedinthenewestversionofJavaScriptatthetimeofthis

writing(commonlyreferredtoas"ES6"forthe6theditionofECMAScript--theofficialnameoftheJSspecification).Ifyou

happentobeusinganolder,pre-ES6browser,thecodemaynotwork.Arecentupdateofamodernbrowser(likeChrome,

Firefox,orIE)shouldbeused.

AsweassertedinChapter1,JavaScripthastypedvalues,nottypedvariables.Thefollowingbuilt-intypesareavailable:

string

number

boolean

null

and

undefined

object

symbol

(newtoES6)

JavaScriptprovidesa

typeof

operatorthatcanexamineavalueandtellyouwhattypeitis:

var

a;

typeof

a;

//"undefined"

a=

"helloworld"

;

typeof

a;

//"string"

a=

42

;

typeof

a;

//"number"

a=

true

;

typeof

a;

//"boolean"

a=

null

;

typeof

a;

//"object"--weird,bug

a=

undefined

;

typeof

a;

//"undefined"

a={b:

"c"

};

typeof

a;

//"object"

Thereturnvaluefromthe

typeof

operatorisalwaysoneofsix(sevenasofES6!)stringvalues.Thatis,

typeof"abc"

Chapter2:IntoJavaScript

Values&Types

YouDon'tKnowJS:Up&Going

26

Chapter2:IntoJavaScript

background image

returns

"string"

,not

string

.

Noticehowinthissnippetthe

a

variableholdseverydifferenttypeofvalue,andthatdespiteappearances,

typeofa

isnot

askingforthe"typeof

a

",butratherforthe"typeofthevaluecurrentlyin

a

."OnlyvalueshavetypesinJavaScript;

variablesarejustsimplecontainersforthosevalues.

typeofnull

isaninterestingcase,becauseiterrantlyreturns

"object"

,whenyou'dexpectittoreturn

"null"

.

Warning:Thisisalong-standingbuginJS,butonethatislikelynevergoingtobefixed.ToomuchcodeontheWebrelies

onthebugandthusfixingitwouldcausealotmorebugs!

Also,note

a=undefined

.We'reexplicitlysetting

a

tothe

undefined

value,butthatisbehaviorallynodifferentfroma

variablethathasnovaluesetyet,likewiththe

vara;

lineatthetopofthesnippet.Avariablecangettothis"undefined"

valuestateinseveraldifferentways,includingfunctionsthatreturnnovaluesandusageofthe

void

operator.

The

object

typereferstoacompoundvaluewhereyoucansetproperties(namedlocations)thateachholdtheirown

valuesofanytype.ThisisperhapsoneofthemostusefulvaluetypesinallofJavaScript.

var

obj={

a:

"helloworld"

,

b:

42

,

c:

true

};

obj.a;

//"helloworld"

obj.b;

//42

obj.c;

//true

obj[

"a"

];

//"helloworld"

obj[

"b"

];

//42

obj[

"c"

];

//true

Itmaybehelpfultothinkofthis

obj

valuevisually:

Propertiescaneitherbeaccessedwithdotnotation(i.e.,

obj.a

)orbracketnotation(i.e.,

obj["a"]

).Dotnotationisshorter

andgenerallyeasiertoread,andisthuspreferredwhenpossible.

Bracketnotationisusefulifyouhaveapropertynamethathasspecialcharactersinit,like

obj["helloworld!"]

--such

propertiesareoftenreferredtoaskeyswhenaccessedviabracketnotation.The

[]

notationrequireseitheravariable

(explainednext)ora

string

literal(whichneedstobewrappedin

".."

or

'..'

).

Ofcourse,bracketnotationisalsousefulifyouwanttoaccessaproperty/keybutthenameisstoredinanothervariable,

suchas:

var

obj={

a:

"helloworld"

,

b:

42

};

var

b=

"a"

;

Objects

YouDon'tKnowJS:Up&Going

27

Chapter2:IntoJavaScript

background image

obj[b];

//"helloworld"

obj[

"b"

];

//42

Note:FormoreinformationonJavaScript

object

s,seethethis&ObjectPrototypestitleofthisseries,specificallyChapter

3.

ThereareacoupleofothervaluetypesthatyouwillcommonlyinteractwithinJavaScriptprograms:arrayandfunction.But

ratherthanbeingproperbuilt-intypes,theseshouldbethoughtofmorelikesubtypes--specializedversionsofthe

object

type.

Anarrayisan

object

thatholdsvalues(ofanytype)notparticularlyinnamedproperties/keys,butratherinnumerically

indexedpositions.Forexample:

var

arr=[

"helloworld"

,

42

,

true

];

arr[

0

];

//"helloworld"

arr[

1

];

//42

arr[

2

];

//true

arr.length;

//3

typeof

arr;

//"object"

Note:Languagesthatstartcountingatzero,likeJSdoes,use

0

astheindexofthefirstelementinthearray.

Itmaybehelpfultothinkof

arr

visually:

Becausearraysarespecialobjects(as

typeof

implies),theycanalsohaveproperties,includingtheautomaticallyupdated

length

property.

Youtheoreticallycoulduseanarrayasanormalobjectwithyourownnamedproperties,oryoucouldusean

object

but

onlygiveitnumericproperties(

0

,

1

,etc.)similartoanarray.However,thiswouldgenerallybeconsideredimproper

usageoftherespectivetypes.

Thebestandmostnaturalapproachistousearraysfornumericallypositionedvaluesanduse

object

sfornamed

properties.

Theother

object

subtypeyou'llusealloveryourJSprogramsisafunction:

function

foo

()

{

return

42

;

}

foo.bar=

"helloworld"

;

Arrays

Functions

YouDon'tKnowJS:Up&Going

28

Chapter2:IntoJavaScript

background image

typeof

foo;

//"function"

typeof

foo();

//"number"

typeof

foo.bar;

//"string"

Again,functionsareasubtypeof

objects

--

typeof

returns

"function"

,whichimpliesthata

function

isamaintype--

andcanthushaveproperties,butyoutypicallywillonlyusefunctionobjectproperties(like

foo.bar

)inlimitedcases.

Note:FormoreinformationonJSvaluesandtheirtypes,seethefirsttwochaptersoftheTypes&Grammartitleofthis

series.

Thebuilt-intypesandsubtypeswe'vejustdiscussedhavebehaviorsexposedaspropertiesandmethodsthatarequite

powerfulanduseful.

Forexample:

var

a=

"helloworld"

;

var

b=

3.14159

;

a.length;

//11

a.toUpperCase();

//"HELLOWORLD"

b.toFixed(

4

);

//"3.1416"

The"how"behindbeingabletocall

a.toUpperCase()

ismorecomplicatedthanjustthatmethodexistingonthevalue.

Briefly,thereisa

String

(capital

S

)objectwrapperform,typicallycalleda"native,"thatpairswiththeprimitive

string

type;it'sthisobjectwrapperthatdefinesthe

toUpperCase()

methodonitsprototype.

Whenyouuseaprimitivevaluelike

"helloworld"

asan

object

byreferencingapropertyormethod(e.g.,

a.toUpperCase()

intheprevioussnippet),JSautomatically"boxes"thevaluetoitsobjectwrappercounterpart(hidden

underthecovers).

A

string

valuecanbewrappedbya

String

object,a

number

canbewrappedbya

Number

object,anda

boolean

canbe

wrappedbya

Boolean

object.Forthemostpart,youdon'tneedtoworryaboutordirectlyusetheseobjectwrapperforms

ofthevalues--prefertheprimitivevalueformsinpracticallyallcasesandJavaScriptwilltakecareoftherestforyou.

Note:FormoreinformationonJSnativesand"boxing,"seeChapter3oftheTypes&Grammartitleofthisseries.Tobetter

understandtheprototypeofanobject,seeChapter5ofthethis&ObjectPrototypestitleofthisseries.

TherearetwomaintypesofvaluecomparisonthatyouwillneedtomakeinyourJSprograms:equalityandinequality.The

resultofanycomparisonisastrictly

boolean

value(

true

or

false

),regardlessofwhatvaluetypesarecompared.

WetalkedbrieflyaboutcoercioninChapter1,butlet'srevisitithere.

CoercioncomesintwoformsinJavaScript:explicitandimplicit.Explicitcoercionissimplythatyoucanseeobviouslyfrom

thecodethataconversionfromonetypetoanotherwilloccur,whereasimplicitcoercioniswhenthetypeconversioncan

happenasmoreofanon-obvioussideeffectofsomeotheroperation.

You'veprobablyheardsentimentslike"coercionisevil"drawnfromthefactthatthereareclearlyplaceswherecoercion

canproducesomesurprisingresults.Perhapsnothingevokesfrustrationfromdevelopersmorethanwhenthelanguage

Built-InTypeMethods

ComparingValues

Coercion

YouDon'tKnowJS:Up&Going

29

Chapter2:IntoJavaScript

background image

surprisesthem.

Coercionisnotevil,nordoesithavetobesurprising.Infact,themajorityofcasesyoucanconstructwithtypecoercionare

quitesensibleandunderstandable,andcanevenbeusedtoimprovethereadabilityofyourcode.Butwewon'tgomuch

furtherintothatdebate--Chapter4oftheTypes&Grammartitleofthisseriescoversallsides.

Here'sanexampleofexplicitcoercion:

var

a=

"42"

;

var

b=

Number

(a);

a;

//"42"

b;

//42--thenumber!

Andhere'sanexampleofimplicitcoercion:

var

a=

"42"

;

var

b=a*

1

;

//"42"implicitlycoercedto42here

a;

//"42"

b;

//42--thenumber!

InChapter1,webrieflymentionedthe"truthy"and"falsy"natureofvalues:whenanon-

boolean

valueiscoercedtoa

boolean

,doesitbecome

true

or

false

,respectively?

Thespecificlistof"falsy"valuesinJavaScriptisasfollows:

""

(emptystring)

0

,

-0

,

NaN

(invalid

number

)

null

,

undefined

false

Anyvaluethat'snotonthis"falsy"listis"truthy."Herearesomeexamplesofthose:

"hello"

42

true

[]

,

[1,"2",3]

(arrays)

{}

,

{a:42}

(objects)

functionfoo(){..}

(functions)

It'simportanttorememberthatanon-

boolean

valueonlyfollowsthis"truthy"/"falsy"coercionifit'sactuallycoercedtoa

boolean

.It'snotallthatdifficulttoconfuseyourselfwithasituationthatseemslikeit'scoercingavaluetoa

boolean

when

it'snot.

Therearefourequalityoperators:

==

,

===

,

!=

,and

!==

.The

!

formsareofcoursethesymmetric"notequal"versions

oftheircounterparts;non-equalityshouldnotbeconfusedwithinequality.

Thedifferencebetween

==

and

===

isusuallycharacterizedthat

==

checksforvalueequalityand

===

checksforboth

Truthy&Falsy

Equality

YouDon'tKnowJS:Up&Going

30

Chapter2:IntoJavaScript

background image

valueandtypeequality.However,thisisinaccurate.Theproperwaytocharacterizethemisthat

==

checksforvalue

equalitywithcoercionallowed,and

===

checksforvalueequalitywithoutallowingcoercion;

===

isoftencalled"strict

equality"forthisreason.

Considertheimplicitcoercionthat'sallowedbythe

==

loose-equalitycomparisonandnotallowedwiththe

===

strict-

equality:

var

a=

"42"

;

var

b=

42

;

a==b;

//true

a===b;

//false

Inthe

a==b

comparison,JSnoticesthatthetypesdonotmatch,soitgoesthroughanorderedseriesofstepstocoerce

oneorbothvaluestoadifferenttypeuntilthetypesmatch,wherethenasimplevalueequalitycanbechecked.

Ifyouthinkaboutit,there'stwopossibleways

a==b

couldgive

true

viacoercion.Eitherthecomparisoncouldendupas

42==42

oritcouldbe

"42"=="42"

.Sowhichisit?

Theanswer:

"42"

becomes

42

,tomakethecomparison

42==42

.Insuchasimpleexample,itdoesn'treallyseemto

matterwhichwaythatprocessgoes,astheendresultisthesame.Therearemorecomplexcaseswhereitmattersnotjust

whattheendresultofthecomparisonis,buthowyougetthere.

The

a===b

produces

false

,becausethecoercionisnotallowed,sothesimplevaluecomparisonobviouslyfails.Many

developersfeelthat

===

ismorepredictable,sotheyadvocatealwaysusingthatformandstayingawayfrom

==

.Ithink

thisviewisveryshortsighted.Ibelieve

==

isapowerfultoolthathelpsyourprogram,ifyoutakethetimetolearnhowit

works.

We'renotgoingtocoverallthenitty-grittydetailsofhowthecoercionin

==

comparisonsworkshere.Muchofitispretty

sensible,buttherearesomeimportantcornercasestobecarefulof.Youcanreadsection11.9.3oftheES5specification

(

http://www.ecma-international.org/ecma-262/5.1/

)toseetheexactrules,andyou'llbesurprisedatjusthowstraightforward

thismechanismis,comparedtoallthenegativehypesurroundingit.

Toboildownawholelotofdetailstoafewsimpletakeaways,andhelpyouknowwhethertouse

==

or

===

invarious

situations,herearemysimplerules:

Ifeithervalue(akaside)inacomparisoncouldbethe

true

or

false

value,avoid

==

anduse

===

.

Ifeithervalueinacomparisoncouldbeofthesespecificvalues(

0

,

""

,or

[]

--emptyarray),avoid

==

anduse

===

.

Inallothercases,you'resafetouse

==

.Notonlyisitsafe,butinmanycasesitsimplifiesyourcodeinawaythat

improvesreadability.

Whattheserulesboildowntoisrequiringyoutothinkcriticallyaboutyourcodeandaboutwhatkindsofvaluescancome

throughvariablesthatgetcomparedforequality.Ifyoucanbecertainaboutthevalues,and

==

issafe,useit!Ifyoucan't

becertainaboutthevalues,use

===

.It'sthatsimple.

The

!=

non-equalityformpairswith

==

,andthe

!==

formpairswith

===

.Alltherulesandobservationswejust

discussedholdsymmetricallyforthesenon-equalitycomparisons.

Youshouldtakespecialnoteofthe

==

and

===

comparisonrulesifyou'recomparingtwonon-primitivevalues,like

object

s(including

function

and

array

).Becausethosevaluesareactuallyheldbyreference,both

==

and

===

comparisonswillsimplycheckwhetherthereferencesmatch,notanythingabouttheunderlyingvalues.

Forexample,

array

sarebydefaultcoercedto

string

sbysimplyjoiningallthevalueswithcommas(

,

)inbetween.You

mightthinkthattwo

array

swiththesamecontentswouldbe

==

equal,butthey'renot:

YouDon'tKnowJS:Up&Going

31

Chapter2:IntoJavaScript

background image

var

a=[

1

,

2

,

3

];

var

b=[

1

,

2

,

3

];

var

c=

"1,2,3"

;

a==c;

//true

b==c;

//true

a==b;

//false

Note:Formoreinformationaboutthe

==

equalitycomparisonrules,seetheES5specification(section11.9.3)andalso

consultChapter4oftheTypes&Grammartitleofthisseries;seeChapter2formoreinformationaboutvaluesversus

references.

The

<

,

>

,

<=

,and

>=

operatorsareusedforinequality,referredtointhespecificationas"relationalcomparison."

Typicallytheywillbeusedwithordinallycomparablevalueslike

number

s.It'seasytounderstandthat

3<4

.

ButJavaScript

string

valuescanalsobecomparedforinequality,usingtypicalalphabeticrules(

"bar"<"foo"

).

Whataboutcoercion?Similarrulesas

==

comparison(thoughnotexactlyidentical!)applytotheinequalityoperators.

Notably,thereareno"strictinequality"operatorsthatwoulddisallowcoercionthesameway

===

"strictequality"does.

Consider:

var

a=

41

;

var

b=

"42"

;

var

c=

"43"

;

a<b;

//true

b<c;

//true

Whathappenshere?Insection11.8.5oftheES5specification,itsaysthatifbothvaluesinthe

<

comparisonare

string

s,asitiswith

b<c

,thecomparisonismadelexicographically(akaalphabeticallylikeadictionary).Butifoneor

bothisnota

string

,asitiswith

a<b

,thenbothvaluesarecoercedtobe

number

s,andatypicalnumericcomparison

occurs.

Thebiggestgotchayoumayrunintoherewithcomparisonsbetweenpotentiallydifferentvaluetypes--remember,there

areno"strictinequality"formstouse--iswhenoneofthevaluescannotbemadeintoavalidnumber,suchas:

var

a=

42

;

var

b=

"foo"

;

a<b;

//false

a>b;

//false

a==b;

//false

Wait,howcanallthreeofthosecomparisonsbe

false

?Becausethe

b

valueisbeingcoercedtothe"invalidnumber

value"

NaN

inthe

<

and

>

comparisons,andthespecificationsaysthat

NaN

isneithergreater-thannorless-thanany

othervalue.

The

==

comparisonfailsforadifferentreason.

a==b

couldfailifit'sinterpretedeitheras

42==NaN

or

"42"=="foo"

--

asweexplainedearlier,theformeristhecase.

Note:Formoreinformationabouttheinequalitycomparisonrules,seesection11.8.5oftheES5specificationandalso

consultChapter4oftheTypes&Grammartitleofthisseries.

Inequality

YouDon'tKnowJS:Up&Going

32

Chapter2:IntoJavaScript

background image

InJavaScript,variablenames(includingfunctionnames)mustbevalididentifiers.Thestrictandcompleterulesforvalid

charactersinidentifiersarealittlecomplexwhenyouconsidernontraditionalcharacterssuchasUnicode.Ifyouonly

considertypicalASCIIalphanumericcharacters,though,therulesaresimple.

Anidentifiermuststartwith

a

-

z

,

A

-

Z

,

$

,or

_

.Itcanthencontainanyofthosecharactersplusthenumerals

0

-

9

.

Generally,thesamerulesapplytoapropertynameastoavariableidentifier.However,certainwordscannotbeusedas

variables,butareOKaspropertynames.Thesewordsarecalled"reservedwords,"andincludetheJSkeywords(

for

,

in

,

if

,etc.)aswellas

null

,

true

,and

false

.

Note:Formoreinformationaboutreservedwords,seeAppendixAoftheTypes&Grammartitleofthisseries.

Youusethe

var

keywordtodeclareavariablethatwillbelongtothecurrentfunctionscope,ortheglobalscopeifatthe

topleveloutsideofanyfunction.

Wherevera

var

appearsinsideascope,thatdeclarationistakentobelongtotheentirescopeandaccessibleeverywhere

throughout.

Metaphorically,thisbehavioriscalledhoisting,whena

var

declarationisconceptually"moved"tothetopofitsenclosing

scope.Technically,thisprocessismoreaccuratelyexplainedbyhowcodeiscompiled,butwecanskipoverthosedetails

fornow.

Consider:

var

a=

2

;

foo();

//worksbecause`foo()`

//declarationis"hoisted"

function

foo

()

{

a=

3

;

console

.log(a);

//3

var

a;

//declarationis"hoisted"

//tothetopof`foo()`

}

console

.log(a);

//2

Warning:It'snotcommonoragoodideatorelyonvariablehoistingtouseavariableearlierinitsscopethanits

var

declarationappears;itcanbequiteconfusing.It'smuchmorecommonandacceptedtousehoistedfunctiondeclarations,

aswedowiththe

foo()

callappearingbeforeitsformaldeclaration.

Whenyoudeclareavariable,itisavailableanywhereinthatscope,aswellasanylower/innerscopes.Forexample:

function

foo

()

{

var

a=

1

;

Variables

FunctionScopes

Hoisting

NestedScopes

YouDon'tKnowJS:Up&Going

33

Chapter2:IntoJavaScript

background image

function

bar

()

{

var

b=

2

;

function

baz

()

{

var

c=

3

;

console

.log(a,b,c);

//123

}

baz();

console

.log(a,b);

//12

}

bar();

console

.log(a);

//1

}

foo();

Noticethat

c

isnotavailableinsideof

bar()

,becauseit'sdeclaredonlyinsidetheinner

baz()

scope,andthat

b

isnot

availableto

foo()

forthesamereason.

Ifyoutrytoaccessavariable'svalueinascopewhereit'snotavailable,you'llgeta

ReferenceError

thrown.Ifyoutrytoset

avariablethathasn'tbeendeclared,you'lleitherendupcreatingavariableinthetop-levelglobalscope(bad!)orgettingan

error,dependingon"strictmode"(see"StrictMode").Let'stakealook:

function

foo

()

{

a=

1

;

//`a`notformallydeclared

}

foo();

a;

//1--oops,autoglobalvariable:(

Thisisaverybadpractice.Don'tdoit!Alwaysformallydeclareyourvariables.

Inadditiontocreatingdeclarationsforvariablesatthefunctionlevel,ES6letsyoudeclarevariablestobelongtoindividual

blocks(pairsof

{..}

),usingthe

let

keyword.Besidessomenuanceddetails,thescopingruleswillbehaveroughlythe

sameaswejustsawwithfunctions:

function

foo

()

{

var

a=

1

;

if

(a>=

1

){

let

b=

2

;

while

(b<

5

){

let

c=b*

2

;

b++;

console

.log(a+c);

}

}

}

foo();

//579

Becauseofusing

let

insteadof

var

,

b

willbelongonlytothe

if

statementandthusnottothewhole

foo()

function's

scope.Similarly,

c

belongsonlytothe

while

loop.Blockscopingisveryusefulformanagingyourvariablescopesina

morefine-grainedfashion,whichcanmakeyourcodemucheasiertomaintainovertime.

Note:Formoreinformationaboutscope,seetheScope&Closurestitleofthisseries.SeetheES6&Beyondtitleofthis

seriesformoreinformationabout

let

blockscoping.

YouDon'tKnowJS:Up&Going

34

Chapter2:IntoJavaScript

background image

Inadditiontothe

if

statementweintroducedbrieflyinChapter1,JavaScriptprovidesafewotherconditionals

mechanismsthatweshouldtakealookat.

Sometimesyoumayfindyourselfwritingaseriesof

if..else..if

statementslikethis:

if

(a==

2

){

//dosomething

}

else

if

(a==

10

){

//doanotherthing

}

else

if

(a==

42

){

//doyetanotherthing

}

else

{

//fallbacktohere

}

Thisstructureworks,butit'salittleverbosebecauseyouneedtospecifythe

a

testforeachcase.Here'sanotheroption,

the

switch

statement:

switch

(a){

case

2

:

//dosomething

break

;

case

10

:

//doanotherthing

break

;

case

42

:

//doyetanotherthing

break

;

default

:

//fallbacktohere

}

The

break

isimportantifyouwantonlythestatement(s)inone

case

torun.Ifyouomit

break

froma

case

,andthat

case

matchesorruns,executionwillcontinuewiththenext

case

'sstatementsregardlessofthat

case

matching.Thissocalled

"fallthrough"issometimesuseful/desired:

switch

(a){

case

2

:

case

10

:

//somecoolstuff

break

;

case

42

:

//otherstuff

break

;

default

:

//fallback

}

Here,if

a

iseither

2

or

10

,itwillexecutethe"somecoolstuff"codestatements.

AnotherformofconditionalinJavaScriptisthe"conditionaloperator,"oftencalledthe"ternaryoperator."It'slikeamore

conciseformofasingle

if..else

statement,suchas:

var

a=

42

;

Conditionals

YouDon'tKnowJS:Up&Going

35

Chapter2:IntoJavaScript

background image

var

b=(a>

41

)?

"hello"

:

"world"

;

//similarto:

//if(a>41){

//b="hello";

//}

//else{

//b="world";

//}

Ifthetestexpression(

a>41

here)evaluatesas

true

,thefirstclause(

"hello"

)results,otherwisethesecondclause

(

"world"

)results,andwhatevertheresultisthengetsassignedto

b

.

Theconditionaloperatordoesn'thavetobeusedinanassignment,butthat'sdefinitelythemostcommonusage.

Note:Formoreinformationabouttestingconditionsandotherpatternsfor

switch

and

?:

,seetheTypes&Grammartitle

ofthisseries.

ES5addeda"strictmode"tothelanguage,whichtightenstherulesforcertainbehaviors.Generally,theserestrictionsare

seenaskeepingthecodetoasaferandmoreappropriatesetofguidelines.Also,adheringtostrictmodemakesyourcode

generallymoreoptimizablebytheengine.Strictmodeisabigwinforcode,andyoushoulduseitforallyourprograms.

Youcanoptintostrictmodeforanindividualfunction,oranentirefile,dependingonwhereyouputthestrictmode

pragma:

function

foo

()

{

"usestrict";

//thiscodeisstrictmode

function

bar

()

{

//thiscodeisstrictmode

}

}

//thiscodeisnotstrictmode

Comparethatto:

"usestrict";

function

foo

()

{

//thiscodeisstrictmode

function

bar

()

{

//thiscodeisstrictmode

}

}

//thiscodeisstrictmode

Onekeydifference(improvement!)withstrictmodeisdisallowingtheimplicitauto-globalvariabledeclarationfromomitting

the

var

:

function

foo

()

{

"usestrict";

//turnonstrictmode

a=

1

;

//`var`missing,ReferenceError

StrictMode

YouDon'tKnowJS:Up&Going

36

Chapter2:IntoJavaScript

background image

}

foo();

Ifyouturnonstrictmodeinyourcode,andyougeterrors,orcodestartsbehavingbuggy,yourtemptationmightbetoavoid

strictmode.Butthatinstinctwouldbeabadideatoindulge.Ifstrictmodecausesissuesinyourprogram,almostcertainly

it'sasignthatyouhavethingsinyourprogramyoushouldfix.

Notonlywillstrictmodekeepyourcodetoasaferpath,andnotonlywillitmakeyourcodemoreoptimizable,butitalso

representsthefuturedirectionofthelanguage.It'dbeeasieronyoutogetusedtostrictmodenowthantokeepputtingit

off--it'llonlygethardertoconvertlater!

Note:Formoreinformationaboutstrictmode,seetheChapter5oftheTypes&Grammartitleofthisseries.

Sofar,we'vediscussedfunctionsastheprimarymechanismofscopeinJavaScript.Yourecalltypical

function

declaration

syntaxasfollows:

function

foo

()

{

//..

}

Thoughitmaynotseemobviousfromthatsyntax,

foo

isbasicallyjustavariableintheouterenclosingscopethat'sgiven

areferencetothe

function

beingdeclared.Thatis,the

function

itselfisavalue,justlike

42

or

[1,2,3]

wouldbe.

Thismaysoundlikeastrangeconceptatfirst,sotakeamomenttoponderit.Notonlycanyoupassavalue(argument)to

afunction,butafunctionitselfcanbeavaluethat'sassignedtovariables,orpassedtoorreturnedfromotherfunctions.

Assuch,afunctionvalueshouldbethoughtofasanexpression,muchlikeanyothervalueorexpression.

Consider:

var

foo=

function

()

{

//..

};

var

x=

function

bar

()

{

//..

};

Thefirstfunctionexpressionassignedtothe

foo

variableiscalledanonymousbecauseithasno

name

.

Thesecondfunctionexpressionisnamed(

bar

),evenasareferencetoitisalsoassignedtothe

x

variable.Named

functionexpressionsaregenerallymorepreferable,thoughanonymousfunctionexpressionsarestillextremelycommon.

Formoreinformation,seetheScope&Closurestitleofthisseries.

Intheprevioussnippet,neitherofthefunctionexpressionsareexecuted--wecouldifwehadincluded

foo()

or

x()

,for

instance.

There'sanotherwaytoexecuteafunctionexpression,whichistypicallyreferredtoasanimmediatelyinvokedfunction

FunctionsAsValues

ImmediatelyInvokedFunctionExpressions(IIFEs)

YouDon'tKnowJS:Up&Going

37

Chapter2:IntoJavaScript

background image

expression(IIFE):

(

function

IIFE

()

{

console

.log(

"Hello!"

);

})();

//"Hello!"

Theouter

(..)

thatsurroundsthe

(functionIIFE(){..})

functionexpressionisjustanuanceofJSgrammarneeded

topreventitfrombeingtreatedasanormalfunctiondeclaration.

Thefinal

()

ontheendoftheexpression--the

})();

line--iswhatactuallyexecutesthefunctionexpressionreferenced

immediatelybeforeit.

Thatmayseemstrange,butit'snotasforeignasfirstglance.Considerthesimilaritiesbetween

foo

and

IIFE

here:

function

foo

()

{..}

//`foo`functionreferenceexpression,

//then`()`executesit

foo();

//`IIFE`functionexpression,

//then`()`executesit

(

function

IIFE

()

{..})();

Asyoucansee,listingthe

(functionIIFE(){..})

beforeitsexecuting

()

isessentiallythesameasincluding

foo

beforeitsexecuting

()

;inbothcases,thefunctionreferenceisexecutedwith

()

immediatelyafterit.

BecauseanIIFEisjustafunction,andfunctionscreatevariablescope,usinganIIFEinthisfashionisoftenusedtodeclare

variablesthatwon'taffectthesurroundingcodeoutsidetheIIFE:

var

a=

42

;

(

function

IIFE

()

{

var

a=

10

;

console

.log(a);

//10

})();

console

.log(a);

//42

IIFEscanalsohavereturnvalues:

var

x=(

function

IIFE

()

{

return

42

;

})();

x;

//42

The

42

valuegets

return

edfromthe

IIFE

-namedfunctionbeingexecuted,andisthenassignedto

x

.

Closureisoneofthemostimportant,andoftenleastunderstood,conceptsinJavaScript.Iwon'tcoveritindeepdetail

here,andinsteadreferyoutotheScope&Closurestitleofthisseries.ButIwanttosayafewthingsaboutitsoyou

understandthegeneralconcept.ItwillbeoneofthemostimportanttechniquesinyourJSskillset.

Closure

YouDon'tKnowJS:Up&Going

38

Chapter2:IntoJavaScript

background image

Youcanthinkofclosureasawayto"remember"andcontinuetoaccessafunction'sscope(itsvariables)evenoncethe

functionhasfinishedrunning.

Consider:

function

makeAdder

(

x

)

{

//parameter`x`isaninnervariable

//innerfunction`add()`uses`x`,so

//ithasa"closure"overit

function

add

(

y

)

{

return

y+x;

};

return

add;

}

Thereferencetotheinner

add(..)

functionthatgetsreturnedwitheachcalltotheouter

makeAdder(..)

isableto

rememberwhatever

x

valuewaspassedinto

makeAdder(..)

.Now,let'suse

makeAdder(..)

:

//`plusOne`getsareferencetotheinner`add(..)`

//functionwithclosureoverthe`x`parameterof

//theouter`makeAdder(..)`

var

plusOne=makeAdder(

1

);

//`plusTen`getsareferencetotheinner`add(..)`

//functionwithclosureoverthe`x`parameterof

//theouter`makeAdder(..)`

var

plusTen=makeAdder(

10

);

plusOne(

3

);

//4<--1+3

plusOne(

41

);

//42<--1+41

plusTen(

13

);

//23<--10+13

Moreonhowthiscodeworks:

1. Whenwecall

makeAdder(1)

,wegetbackareferencetoitsinner

add(..)

thatremembers

x

as

1

.Wecallthis

functionreference

plusOne(..)

.

2. Whenwecall

makeAdder(10)

,wegetbackanotherreferencetoitsinner

add(..)

thatremembers

x

as

10

.Wecall

thisfunctionreference

plusTen(..)

.

3. Whenwecall

plusOne(3)

,itadds

3

(itsinner

y

)tothe

1

(rememberedby

x

),andweget

4

astheresult.

4. Whenwecall

plusTen(13)

,itadds

13

(itsinner

y

)tothe

10

(rememberedby

x

),andweget

23

astheresult.

Don'tworryifthisseemsstrangeandconfusingatfirst--itcanbe!It'lltakelotsofpracticetounderstanditfully.

Buttrustme,onceyoudo,it'soneofthemostpowerfulandusefultechniquesinallofprogramming.It'sdefinitelyworththe

efforttoletyourbrainsimmeronclosuresforabit.Inthenextsection,we'llgetalittlemorepracticewithclosure.

ThemostcommonusageofclosureinJavaScriptisthemodulepattern.Modulesletyoudefineprivateimplementation

details(variables,functions)thatarehiddenfromtheoutsideworld,aswellasapublicAPIthatisaccessiblefromthe

outside.

Consider:

function

User

()

{

var

username,password;

Modules

YouDon'tKnowJS:Up&Going

39

Chapter2:IntoJavaScript

background image

function

doLogin

(

user,pw

)

{

username=user;

password=pw;

//dotherestoftheloginwork

}

var

publicAPI={

login:doLogin

};

return

publicAPI;

}

//createa`User`moduleinstance

var

fred=User();

fred.login(

"fred"

,

"12Battery34!"

);

The

User()

functionservesasanouterscopethatholdsthevariables

username

and

password

,aswellastheinner

doLogin()

function;theseareallprivateinnerdetailsofthis

User

modulethatcannotbeaccessedfromtheoutsideworld.

Warning:Wearenotcalling

newUser()

here,onpurpose,despitethefactthatprobablyseemsmorecommontomost

readers.

User()

isjustafunction,notaclasstobeinstantiated,soit'sjustcallednormally.Using

new

wouldbe

inappropriateandactuallywasteresources.

Executing

User()

createsaninstanceofthe

User

module--awholenewscopeiscreated,andthusawholenewcopyof

eachoftheseinnervariables/functions.Weassignthisinstanceto

fred

.Ifwerun

User()

again,we'dgetanewinstance

entirelyseparatefrom

fred

.

Theinner

doLogin()

functionhasaclosureover

username

and

password

,meaningitwillretainitsaccesstothemeven

afterthe

User()

functionfinishesrunning.

publicAPI

isanobjectwithoneproperty/methodonit,

login

,whichisareferencetotheinner

doLogin()

function.When

wereturn

publicAPI

from

User()

,itbecomestheinstancewecall

fred

.

Atthispoint,theouter

User()

functionhasfinishedexecuting.Normally,you'dthinktheinnervariableslike

username

and

password

havegoneaway.Butheretheyhavenot,becausethere'saclosureinthe

login()

functionkeepingthemalive.

That'swhywecancall

fred.login(..)

--thesameascallingtheinner

doLogin(..)

--anditcanstillaccess

username

and

password

innervariables.

There'sagoodchancethatwithjustthisbriefglimpseatclosureandthemodulepattern,someofitisstillabitconfusing.

That'sOK!Ittakessomeworktowrapyourbrainaroundit.

Fromhere,goreadtheScope&Closurestitleofthisseriesforamuchmorein-depthexploration.

AnotherverycommonlymisunderstoodconceptinJavaScriptisthe

this

identifier.Again,there'sacoupleofchaptersonit

inthethis&ObjectPrototypestitleofthisseries,soherewe'lljustbrieflyintroducetheconcept.

Whileitmayoftenseemthat

this

isrelatedto"object-orientedpatterns,"inJS

this

isadifferentmechanism.

Ifafunctionhasa

this

referenceinsideit,that

this

referenceusuallypointstoan

object

.Butwhich

object

itpointsto

dependsonhowthefunctionwascalled.

It'simportanttorealizethat

this

doesnotrefertothefunctionitself,asisthemostcommonmisconception.

this

Identifier

YouDon'tKnowJS:Up&Going

40

Chapter2:IntoJavaScript

background image

Here'saquickillustration:

function

foo

()

{

console

.log(

this

.bar);

}

var

bar=

"global"

;

var

obj1={

bar:

"obj1"

,

foo:foo

};

var

obj2={

bar:

"obj2"

};

//--------

foo();

//"global"

obj1.foo();

//"obj1"

foo.call(obj2);

//"obj2"

new

foo();

//undefined

Therearefourrulesforhow

this

getsset,andthey'reshowninthoselastfourlinesofthatsnippet.

1.

foo()

endsupsetting

this

totheglobalobjectinnon-strictmode--instrictmode,

this

wouldbe

undefined

and

you'dgetanerrorinaccessingthe

bar

property--so

"global"

isthevaluefoundfor

this.bar

.

2.

obj1.foo()

sets

this

tothe

obj1

object.

3.

foo.call(obj2)

sets

this

tothe

obj2

object.

4.

newfoo()

sets

this

toabrandnewemptyobject.

Bottomline:tounderstandwhat

this

pointsto,youhavetoexaminehowthefunctioninquestionwascalled.Itwillbeone

ofthosefourwaysjustshown,andthatwillthenanswerwhat

this

is.

Note:Formoreinformationabout

this

,seeChapters1and2ofthethis&ObjectPrototypestitleofthisseries.

TheprototypemechanisminJavaScriptisquitecomplicated.Wewillonlyglanceatithere.Youwillwanttospendplentyof

timereviewingChapters4-6ofthethis&ObjectPrototypestitleofthisseriesforallthedetails.

Whenyoureferenceapropertyonanobject,ifthatpropertydoesn'texist,JavaScriptwillautomaticallyusethatobject's

internalprototypereferencetofindanotherobjecttolookforthepropertyon.Youcouldthinkofthisalmostasafallbackif

thepropertyismissing.

Theinternalprototypereferencelinkagefromoneobjecttoitsfallbackhappensatthetimetheobjectiscreated.The

simplestwaytoillustrateitiswithabuilt-inutilitycalled

Object.create(..)

.

Consider:

var

foo={

a:

42

};

//create`bar`andlinkitto`foo`

var

bar=

Object

.create(foo);

bar.b=

"helloworld"

;

bar.b;

//"helloworld"

Prototypes

YouDon'tKnowJS:Up&Going

41

Chapter2:IntoJavaScript

background image

bar.a;

//42<--delegatedto`foo`

Itmayhelptovisualizethe

foo

and

bar

objectsandtheirrelationship:

The

a

propertydoesn'tactuallyexistonthe

bar

object,butbecause

bar

isprototype-linkedto

foo

,JavaScript

automaticallyfallsbacktolookingfor

a

onthe

foo

object,whereit'sfound.

Thislinkagemayseemlikeastrangefeatureofthelanguage.Themostcommonwaythisfeatureisused--andIwould

argue,abused--istotrytoemulate/fakea"class"mechanismwith"inheritance."

Butamorenaturalwayofapplyingprototypesisapatterncalled"behaviordelegation,"whereyouintentionallydesignyour

linkedobjectstobeabletodelegatefromonetotheotherforpartsoftheneededbehavior.

Note:Formoreinformationaboutprototypesandbehaviordelegation,seeChapters4-6ofthethis&ObjectPrototypes

titleofthisseries.

SomeoftheJSfeatureswe'vealreadycovered,andcertainlymanyofthefeaturescoveredintherestofthisseries,are

neweradditionsandwillnotnecessarilybeavailableinolderbrowsers.Infact,someofthenewestfeaturesinthe

specificationaren'tevenimplementedinanystablebrowsersyet.

So,whatdoyoudowiththenewstuff?Doyoujusthavetowaitaroundforyearsordecadesforalltheoldbrowserstofade

intoobscurity?

That'showmanypeoplethinkaboutthesituation,butit'sreallynotahealthyapproachtoJS.

Therearetwomaintechniquesyoucanuseto"bring"thenewerJavaScriptstufftotheolderbrowsers:polyfillingand

transpiling.

Theword"polyfill"isaninventedterm(byRemySharp)(

https://remysharp.com/2010/10/08/what-is-a-polyfill

)usedtorefer

totakingthedefinitionofanewerfeatureandproducingapieceofcodethat'sequivalenttothebehavior,butisabletorun

inolderJSenvironments.

Forexample,ES6definesautilitycalled

Number.isNaN(..)

toprovideanaccuratenon-buggycheckfor

NaN

values,

deprecatingtheoriginal

isNaN(..)

utility.Butit'seasytopolyfillthatutilitysothatyoucanstartusingitinyourcode

regardlessofwhethertheenduserisinanES6browserornot.

Consider:

Old&New

Polyfilling

YouDon'tKnowJS:Up&Going

42

Chapter2:IntoJavaScript

background image

if

(!

Number

.isNaN){

Number

.isNaN=

function

isNaN

(

x

)

{

return

x!==x;

};

}

The

if

statementguardsagainstapplyingthepolyfilldefinitioninES6browserswhereitwillalreadyexist.Ifit'snot

alreadypresent,wedefine

Number.isNaN(..)

.

Note:Thecheckwedoheretakesadvantageofaquirkwith

NaN

values,whichisthatthey'retheonlyvalueinthewhole

languagethatisnotequaltoitself.Sothe

NaN

valueistheonlyonethatwouldmake

x!==x

be

true

.

Notallnewfeaturesarefullypolyfillable.Sometimesmostofthebehaviorcanbepolyfilled,buttherearestillsmall

deviations.Youshouldbereally,reallycarefulinimplementingapolyfillyourself,tomakesureyouareadheringtothe

specificationasstrictlyaspossible.

Orbetteryet,useanalreadyvettedsetofpolyfillsthatyoucantrust,suchasthoseprovidedbyES5-Shim

(

https://github.com/es-shims/es5-shim

)andES6-Shim(

https://github.com/es-shims/es6-shim

).

There'snowaytopolyfillnewsyntaxthathasbeenaddedtothelanguage.Thenewsyntaxwouldthrowanerrorintheold

JSengineasunrecognized/invalid.

Sothebetteroptionistouseatoolthatconvertsyournewercodeintooldercodeequivalents.Thisprocessiscommonly

called"transpiling,"atermfortransforming+compiling.

Essentially,yoursourcecodeisauthoredinthenewsyntaxform,butwhatyoudeploytothebrowseristhetranspiledcode

inoldsyntaxform.Youtypicallyinsertthetranspilerintoyourbuildprocess,similartoyourcodelinteroryourminifier.

Youmightwonderwhyyou'dgotothetroubletowritenewsyntaxonlytohaveittranspiledawaytooldercode--whynot

justwritetheoldercodedirectly?

Thereareseveralimportantreasonsyoushouldcareabouttranspiling:

Thenewsyntaxaddedtothelanguageisdesignedtomakeyourcodemorereadableandmaintainable.Theolder

equivalentsareoftenmuchmoreconvoluted.Youshouldpreferwritingnewerandcleanersyntax,notonlyforyourself

butforallothermembersofthedevelopmentteam.

Ifyoutranspileonlyforolderbrowsers,butservethenewsyntaxtothenewestbrowsers,yougettotakeadvantageof

browserperformanceoptimizationswiththenewsyntax.Thisalsoletsbrowsermakershavemorereal-worldcodeto

testtheirimplementationsandoptimizationson.

Usingthenewsyntaxearlierallowsittobetestedmorerobustlyintherealworld,whichprovidesearlierfeedbackto

theJavaScriptcommittee(TC39).Ifissuesarefoundearlyenough,theycanbechanged/fixedbeforethoselanguage

designmistakesbecomepermanent.

Here'saquickexampleoftranspiling.ES6addsafeaturecalled"defaultparametervalues."Itlookslikethis:

function

foo

(

a=2

)

{

console

.log(a);

}

foo();

//2

foo(

42

);

//42

Simple,right?Helpful,too!Butit'snewsyntaxthat'sinvalidinpre-ES6engines.Sowhatwillatranspilerdowiththatcode

Transpiling

YouDon'tKnowJS:Up&Going

43

Chapter2:IntoJavaScript

background image

tomakeitruninolderenvironments?

function

foo

()

{

var

a=

arguments

[

0

]!==(

void

0

)?

arguments

[

0

]:

2

;

console

.log(a);

}

Asyoucansee,itcheckstoseeifthe

arguments[0]

valueis

void0

(aka

undefined

),andifsoprovidesthe

2

default

value;otherwise,itassignswhateverwaspassed.

Inadditiontobeingabletonowusethenicersyntaxeveninolderbrowsers,lookingatthetranspiledcodeactuallyexplains

theintendedbehaviormoreclearly.

YoumaynothaverealizedjustfromlookingattheES6versionthat

undefined

istheonlyvaluethatcan'tgetexplicitly

passedinforadefault-valueparameter,butthetranspiledcodemakesthatmuchmoreclear.

ThelastimportantdetailtoemphasizeabouttranspilersisthattheyshouldnowbethoughtofasastandardpartoftheJS

developmentecosystemandprocess.JSisgoingtocontinuetoevolve,muchmorequicklythanbefore,soeveryfew

monthsnewsyntaxandnewfeatureswillbeadded.

Ifyouuseatranspilerbydefault,you'llalwaysbeabletomakethatswitchtonewersyntaxwheneveryoufindituseful,

ratherthanalwayswaitingforyearsfortoday'sbrowserstophaseout.

Therearequiteafewgreattranspilersforyoutochoosefrom.Herearesomegoodoptionsatthetimeofthiswriting:

Babel(

https://babeljs.io

)(formerly6to5):TranspilesES6+intoES5

Traceur(

https://github.com/google/traceur-compiler

):TranspilesES6,ES7,andbeyondintoES5

Sofar,theonlythingswe'vecoveredareintheJSlanguageitself.TherealityisthatmostJSiswrittentoruninandinteract

withenvironmentslikebrowsers.Agoodchunkofthestuffthatyouwriteinyourcodeis,strictlyspeaking,notdirectly

controlledbyJavaScript.Thatprobablysoundsalittlestrange.

Themostcommonnon-JavaScriptJavaScriptyou'llencounteristheDOMAPI.Forexample:

var

el=

document

.getElementById(

"foo"

);

The

document

variableexistsasaglobalvariablewhenyourcodeisrunninginabrowser.It'snotprovidedbytheJS

engine,norisitparticularlycontrolledbytheJavaScriptspecification.Ittakestheformofsomethingthatlooksanawfullot

likeanormalJS

object

,butit'snotreallyexactlythat.It'saspecial

object,

oftencalleda"hostobject."

Moreover,the

getElementById(..)

methodon

document

lookslikeanormalJSfunction,butit'sjustathinlyexposed

interfacetoabuilt-inmethodprovidedbytheDOMfromyourbrowser.Insome(newer-generation)browsers,thislayermay

alsobeinJS,buttraditionallytheDOManditsbehaviorisimplementedinsomethingmorelikeC/C++.

Anotherexampleiswithinput/output(I/O).

Everyone'sfavorite

alert(..)

popsupamessageboxintheuser'sbrowserwindow.

alert(..)

isprovidedtoyourJS

programbythebrowser,notbytheJSengineitself.Thecallyoumakesendsthemessagetothebrowserinternalsandit

handlesdrawinganddisplayingthemessagebox.

Thesamegoeswith

console.log(..)

;yourbrowserprovidessuchmechanismsandhooksthemuptothedevelopertools.

Non-JavaScript

YouDon'tKnowJS:Up&Going

44

Chapter2:IntoJavaScript

background image

Thisbook,andthiswholeseries,focusesonJavaScriptthelanguage.That'swhyyoudon'tseeanysubstantialcoverageof

thesenon-JavaScriptJavaScriptmechanisms.Nevertheless,youneedtobeawareofthem,asthey'llbeineveryJS

programyouwrite!

ThefirststeptolearningJavaScript'sflavorofprogrammingistogetabasicunderstandingofitscoremechanismslike

values,types,functionclosures,

this

,andprototypes.

Ofcourse,eachofthesetopicsdeservesmuchgreatercoveragethanyou'veseenhere,butthat'swhytheyhavechapters

andbooksdedicatedtothemthroughouttherestofthisseries.Afteryoufeelprettycomfortablewiththeconceptsandcode

samplesinthischapter,therestoftheseriesawaitsyoutoreallydiginandgettoknowthelanguagedeeply.

Thefinalchapterofthisbookwillbrieflysummarizeeachoftheothertitlesintheseriesandtheotherconceptstheycover

besideswhatwe'vealreadyexplored.

Review

YouDon'tKnowJS:Up&Going

45

Chapter2:IntoJavaScript

background image

Whatisthisseriesallabout?Putsimply,it'sabouttakingseriouslythetaskoflearningallpartsofJavaScript,notjustsome

subsetofthelanguagethatsomeonecalled"thegoodparts,"andnotjustwhateverminimalamountyouneedtogetyour

jobdoneatwork.

Seriousdevelopersinotherlanguagesexpecttoputintheefforttolearnmostorallofthelanguage(s)theyprimarilywrite

in,butJSdevelopersseemtostandoutfromthecrowdinthesenseoftypicallynotlearningverymuchofthelanguage.

Thisisnotagoodthing,andit'snotsomethingweshouldcontinuetoallowtobethenorm.

TheYouDon'tKnowJS(YDKJS)seriesstandsinstarkcontrasttothetypicalapproachestolearningJS,andisunlike

almostanyotherJSbooksyouwillread.Itchallengesyoutogobeyondyourcomfortzoneandtoaskthedeeper"why"

questionsforeverysinglebehavioryouencounter.Areyouupforthatchallenge?

I'mgoingtousethisfinalchaptertobrieflysummarizewhattoexpectfromtherestofthebooksintheseries,andhowto

mosteffectivelygoaboutbuildingafoundationofJSlearningontopofYDKJS.

Perhapsoneofthemostfundamentalthingsyou'llneedtoquicklycometotermswithishowscopingofvariablesreally

worksinJavaScript.It'snotenoughtohaveanecdotalfuzzybeliefsaboutscope.

TheScope&ClosurestitlestartsbydebunkingthecommonmisconceptionthatJSisan"interpretedlanguage"and

thereforenotcompiled.Nope.

TheJSenginecompilesyourcoderightbefore(andsometimesduring!)execution.Soweusesomedeeperunderstanding

ofthecompiler'sapproachtoourcodetounderstandhowitfindsanddealswithvariableandfunctiondeclarations.Along

theway,weseethetypicalmetaphorforJSvariablescopemanagement,"Hoisting."

Thiscriticalunderstandingof"lexicalscope"iswhatwethenbaseourexplorationofclosureonforthelastchapterofthe

book.ClosureisperhapsthesinglemostimportantconceptinallofJS,butifyouhaven'tfirstgraspedfirmlyhowscope

works,closurewilllikelyremainbeyondyourgrasp.

Oneimportantapplicationofclosureisthemodulepattern,aswebrieflyintroducedinthisbookinChapter2.Themodule

patternisperhapsthemostprevalentcodeorganizationpatterninallofJavaScript;deepunderstandingofitshouldbeone

ofyourhighestpriorities.

PerhapsoneofthemostwidespreadandpersistentmistruthsaboutJavaScriptisthatthe

this

keywordreferstothe

functionitappearsin.Terriblymistaken.

The

this

keywordisdynamicallyboundbasedonhowthefunctioninquestionisexecuted,anditturnsouttherearefour

simplerulestounderstandandfullydetermine

this

binding.

Closelyrelatedtothe

this

keywordistheobjectprototypemechanism,whichisalook-upchainforproperties,similarto

howlexicalscopevariablesarefound.ButwrappedupintheprototypesistheotherhugemiscueaboutJS:theideaof

emulating(fake)classesand(so-called"prototypal")inheritance.

Unfortunately,thedesiretobringclassandinheritancedesignpatternthinkingtoJavaScriptisjustabouttheworstthing

youcouldtrytodo,becausewhilethesyntaxmaytrickyouintothinkingthere'ssomethinglikeclassespresent,infactthe

Chapter3:IntoYDKJS

Scope&Closures

this&ObjectPrototypes

YouDon'tKnowJS:Up&Going

46

Chapter3:IntoYDKJS

background image

prototypemechanismisfundamentallyoppositeinitsbehavior.

What'satissueiswhetherit'sbettertoignorethemismatchandpretendthatwhatyou'reimplementingis"inheritance,"or

whetherit'smoreappropriatetolearnandembracehowtheobjectprototypesystemactuallyworks.Thelatterismore

appropriatelynamed"behaviordelegation."

Thisismorethansyntacticpreference.Delegationisanentirelydifferent,andmorepowerful,designpattern,onethat

replacestheneedtodesignwithclassesandinheritance.Buttheseassertionswillabsolutelyflyinthefaceofnearlyevery

otherblogpost,book,andconferencetalkonthesubjectfortheentiretyofJavaScript'slifetime.

TheclaimsImakeregardingdelegationversusinheritancecomenotfromadislikeofthelanguageanditssyntax,butfrom

thedesiretoseethetruecapabilityofthelanguageproperlyleveragedandtheendlessconfusionandfrustrationwiped

away.

ButthecaseImakeregardingprototypesanddelegationisamuchmoreinvolvedonethanwhatIwillindulgehere.If

you'rereadytoreconsidereverythingyouthinkyouknowaboutJavaScript"classes"and"inheritance,"Iofferyouthe

chanceto"taketheredpill"(Matrix1999)andcheckoutChapters4-6ofthethis&ObjectPrototypestitleofthisseries.

Thethirdtitleinthisseriesprimarilyfocusesontacklingyetanotherhighlycontroversialtopic:typecoercion.Perhapsno

topiccausesmorefrustrationwithJSdevelopersthanwhenyoutalkabouttheconfusionssurroundingimplicitcoercion.

Byfar,theconventionalwisdomisthatimplicitcoercionisa"badpart"ofthelanguageandshouldbeavoidedatallcosts.

Infact,somehavegonesofarastocallita"flaw"inthedesignofthelanguage.Indeed,therearetoolswhoseentirejobis

todonothingbutscanyourcodeandcomplainifyou'redoinganythingevenremotelylikecoercion.

Butiscoercionreallysoconfusing,sobad,sotreacherous,thatyourcodeisdoomedfromthestartifyouuseit?

Isayno.AfterhavingbuiltupanunderstandingofhowtypesandvaluesreallyworkinChapters1-3,Chapter4takeson

thisdebateandfullyexplainshowcoercionworks,inallitsnooksandcrevices.Weseejustwhatpartsofcoercionreally

aresurprisingandwhatpartsactuallymakecompletesenseifgiventhetimetolearn.

ButI'mnotmerelysuggestingthatcoercionissensibleandlearnable,I'massertingthatcoercionisanincrediblyusefuland

totallyunderestimatedtoolthatyoushouldbeusinginyourcode.I'msayingthatcoercion,whenusedproperly,notonly

works,butmakesyourcodebetter.Allthenaysayersanddoubterswillsurelyscoffatsuchaposition,butIbelieveit'sone

ofthemainkeystouppingyourJSgame.

Doyouwanttojustkeepfollowingwhatthecrowdsays,orareyouwillingtosetalltheassumptionsasideandlookat

coercionwithafreshperspective?TheTypes&Grammartitleofthisserieswillcoerceyourthinking.

Thefirstthreetitlesofthisseriesfocusonthecoremechanicsofthelanguage,butthefourthtitlebranchesoutslightlyto

coverpatternsontopofthelanguagemechanicsformanagingasynchronousprogramming.Asynchronyisnotonlycritical

totheperformanceofourapplications,it'sincreasinglybecomingthecriticalfactorinwritabilityandmaintainability.

Thebookstartsfirstbyclearingupalotofterminologyandconceptconfusionaroundthingslike"async,""parallel,"and

"concurrent,"andexplainsindepthhowsuchthingsdoanddonotapplytoJS.

Thenwemoveintoexaminingcallbacksastheprimarymethodofenablingasynchrony.Butit'sherethatwequicklysee

thatthecallbackaloneishopelesslyinsufficientforthemoderndemandsofasynchronousprogramming.Weidentifytwo

majordeficienciesofcallbacks-onlycoding:InversionofControl(IoC)trustlossandlackoflinearreason-ability.

Types&Grammar

Async&Performance

YouDon'tKnowJS:Up&Going

47

Chapter3:IntoYDKJS

background image

Toaddressthesetwomajordeficiencies,ES6introducestwonewmechanisms(andindeed,patterns):promisesand

generators.

Promisesareatime-independentwrapperarounda"futurevalue,"whichletsyoureasonaboutandcomposethem

regardlessofifthevalueisreadyornotyet.Moreover,theyeffectivelysolvetheIoCtrustissuesbyroutingcallbacks

throughatrustableandcomposablepromisemechanism.

GeneratorsintroduceanewmodeofexecutionforJSfunctions,wherebythegeneratorcanbepausedat

yield

pointsand

beresumedasynchronouslylater.Thepause-and-resumecapabilityenablessynchronous,sequentiallookingcodeinthe

generatortobeprocessedasynchronouslybehindthescenes.Bydoingso,weaddressthenon-linear,non-local-jump

confusionsofcallbacksandtherebymakeourasynchronouscodesync-lookingsoastobemorereason-able.

Butit'sthecombinationofpromisesandgeneratorsthat"yields"ourmosteffectiveasynchronouscodingpatterntodatein

JavaScript.Infact,muchofthefuturesophisticationofasynchronycominginES7andlaterwillcertainlybebuiltonthis

foundation.Tobeseriousaboutprogrammingeffectivelyinanasyncworld,you'regoingtoneedtogetreallycomfortable

withcombiningpromisesandgenerators.

Ifpromisesandgeneratorsareaboutexpressingpatternsthatletourprogramsrunmoreconcurrentlyandthusgetmore

processingaccomplishedinashorterperiod,JShasmanyotherfacetsofperformanceoptimizationworthexploring.

Chapter5delvesintotopicslikeprogramparallelismwithWebWorkersanddataparallelismwithSIMD,aswellaslow-

leveloptimizationtechniqueslikeASM.js.Chapter6takesalookatperformanceoptimizationfromtheperspectiveof

properbenchmarkingtechniques,includingwhatkindsofperformancetoworryaboutandwhattoignore.

WritingJavaScripteffectivelymeanswritingcodethatcanbreaktheconstraintbarriersofbeingrundynamicallyinawide

rangeofbrowsersandotherenvironments.Itrequiresalotofintricateanddetailedplanningandeffortonourpartstotake

aprogramfrom"itworks"to"itworkswell."

TheAsync&Performancetitleisdesignedtogiveyouallthetoolsandskillsyouneedtowritereasonableandperformant

JavaScriptcode.

Nomatterhowmuchyoufeelyou'vemasteredJavaScripttothispoint,thetruthisthatJavaScriptisnevergoingtostop

evolving,andmoreover,therateofevolutionisincreasingrapidly.Thisfactisalmostametaphorforthespiritofthisseries,

toembracethatwe'llneverfullyknoweverypartofJS,becauseassoonasyoumasteritall,there'sgoingtobenewstuff

comingdownthelinethatyou'llneedtolearn.

Thistitleisdedicatedtoboththeshort-andmid-termvisionsofwherethelanguageisheaded,notjusttheknownstufflike

ES6butthelikelystuffbeyond.

WhileallthetitlesofthisseriesembracethestateofJavaScriptatthetimeofthiswriting,whichismid-waythroughES6

adoption,theprimaryfocusintheserieshasbeenmoreonES5.Now,wewanttoturnourattentiontoES6,ES7,and...

SinceES6isnearlycompleteatthetimeofthiswriting,ES6&BeyondstartsbydividinguptheconcretestufffromtheES6

landscapeintoseveralkeycategories,includingnewsyntax,newdatastructures(collections),andnewprocessing

capabilitiesandAPIs.WecovereachofthesenewES6features,invaryinglevelsofdetail,includingreviewingdetailsthat

aretouchedoninotherbooksofthisseries.

SomeexcitingES6thingstolookforwardtoreadingabout:destructuring,defaultparametervalues,symbols,concise

methods,computedproperties,arrowfunctions,blockscoping,promises,generators,iterators,modules,proxies,

weakmaps,andmuch,muchmore!Phew,ES6packsquiteapunch!

ThefirstpartofthebookisaroadmapforallthestuffyouneedtolearntogetreadyforthenewandimprovedJavaScript

ES6&Beyond

YouDon'tKnowJS:Up&Going

48

Chapter3:IntoYDKJS

background image

you'llbewritingandexploringoverthenextcoupleofyears.

Thelatterpartofthebookturnsattentiontobrieflyglanceatthingsthatwecanlikelyexpecttoseeinthenearfutureof

JavaScript.Themostimportantrealizationhereisthatpost-ES6,JSislikelygoingtoevolvefeaturebyfeatureratherthan

versionbyversion,whichmeanswecanexpecttoseethesenear-futurethingscomingmuchsoonerthanyoumight

imagine.

ThefutureforJavaScriptisbright.Isn'tittimewestartlearningit!?

TheYDKJSseriesisdedicatedtothepropositionthatallJSdeveloperscanandshouldlearnallofthepartsofthisgreat

language.Noperson'sopinion,noframework'sassumptions,andnoproject'sdeadlineshouldbetheexcuseforwhyyou

neverlearnanddeeplyunderstandJavaScript.

Wetakeeachimportantareaoffocusinthelanguageanddedicateashortbutverydensebooktofullyexplorealltheparts

ofitthatyouperhapsthoughtyouknewbutprobablydidn'tfully.

"YouDon'tKnowJS"isn'tacriticismoraninsult.It'sarealizationthatallofus,myselfincluded,mustcometotermswith.

LearningJavaScriptisn'tanendgoalbutaprocess.Wedon'tknowJavaScript,yet.Butwewill!

Review

YouDon'tKnowJS:Up&Going

49

Chapter3:IntoYDKJS

background image

Ihavemanypeopletothankformakingthisbooktitleandtheoverallserieshappen.

First,ImustthankmywifeChristenSimpson,andmytwokidsEthanandEmily,forputtingupwithDadalwayspecking

awayatthecomputer.Evenwhennotwritingbooks,myobsessionwithJavaScriptgluesmyeyestothescreenfarmore

thanitshould.ThattimeIborrowfrommyfamilyisthereasonthesebookscansodeeplyandcompletelyexplain

JavaScripttoyou,thereader.Iowemyfamilyeverything.

I'dliketothankmyeditorsatO'Reilly,namelySimonSt.LaurentandBrianMacDonald,aswellastherestoftheeditorial

andmarketingstaff.Theyarefantastictoworkwith,andhavebeenespeciallyaccommodatingduringthisexperimentinto

"opensource"bookwriting,editing,andproduction.

Thankyoutothemanyfolkswhohaveparticipatedinmakingthisbookseriesbetterbyprovidingeditorialsuggestionsand

corrections,includingShelleyPowers,TimFerro,EvanBorden,ForrestL.Norvell,JenniferDavis,JesseHarlin,KrisKowal,

RickWaldron,JordanHarband,BenjaminGruenbaum,VyacheslavEgorov,DavidNolen,andmanyothers.Abigthankyou

toJennLukasforwritingtheForewordforthistitle.

Thankyoutothecountlessfolksinthecommunity,includingmembersoftheTC39committee,whohavesharedsomuch

knowledgewiththerestofus,andespeciallytoleratedmyincessantquestionsandexplorationswithpatienceanddetail.

John-DavidDalton,Juriy"kangax"Zaytsev,MathiasBynens,AxelRauschmayer,NicholasZakas,AngusCroll,Reginald

Braithwaite,DaveHerman,BrendanEich,AllenWirfs-Brock,BradleyMeck,DomenicDenicola,DavidWalsh,TimDisney,

PetervanderZee,AndreaGiammarchi,KitCambridge,EricElliott,andsomanyothers,Ican'tevenscratchthesurface.

Sincethe"YouDon'tKnowJS"bookserieswasbornonKickstarter,Ialsowishtothankallmy(nearly)500generous

backers,withoutwhomthisbookseriescouldnothavehappened:

JanSzpila,nokiko,MuraliKrishnamoorthy,RyanJoy,CraigPatchett,pdqtrader,DaleFukami,rayhatfield,R0drigo

Perez[Mx],DanPetitt,JackFranklin,AndrewBerry,BrianGrinstead,RobSutherland,SergiMeseguer,Phillip

Gourley,MarkWatson,JeffCarouth,AlfredoSumaran,MartinSachse,MarcioBarrios,Dan,AimelyneM,Matt

Sullivan,DelnattePierre-Antoine,JakeSmith,EugenTudorancea,Iris,DavidTrinh,simonstl,RayDaly,UrosGruber,

JustinMyers,ShaiZonis,Mom&Dad,DevinClark,DennisPalmer,BrianPanahiJohnson,JoshMarshall,Marshall,

DennisKerr,MattSteele,ErikSlagter,Sacah,JustinRainbow,ChristianNilsson,Delapouite,D.Pereira,Nicolas

Hoizey,GeorgeV.Reilly,DanReeves,BrunoLaturner,ChadJennings,ShaneKing,JeremiahLeeCohick,od3n,

StanYamane,MarkoVucinic,JimB,StephenCollins,ÆgirÞorsteinsson,EricPederson,Owain,NathanSmith,

Jeanetteurphy,AlexandreELISÉ,ChrisPeterson,RikWatson,LukeMatthews,JustinLowery,MortenNielsen,

VernonKesner,ChetanShenoy,PaulTregoing,MarcGrabanski,DionAlmaer,AndrewSullivan,KeithElsass,Tom

Burke,BrianAshenfelter,DavidStuart,KarlSwedberg,Graeme,BrandonHays,JohnChristopher,Gior,manojreddy,

ChadSmith,JaredHarbour,MinoruTODA,ChrisWigley,DanielMee,Mike,Handyface,AlexJahraus,CarlFurrow,

RobFoulkrod,MaxShishkin,LeighPennyJr.,RobertFerguson,MikevanHoenselaar,HasseSchougaard,rajan

venkataguru,JeffAdams,TraeRobbins,RolfLangenhuijzen,JorgeAntunes,AlexKoloskov,HughGreenish,Tim

Jones,JoseOchoa,MichaelBrennan-White,NagaHarishMuvva,BarkócziDávid,KittHodsden,PaulMcGraw,

SaschaGoldhofer,AndrewMetcalf,MarkusKrogh,MichaelMathews,MattJared,Juanfran,GeorgieKirschner,

KennyLee,TedZhang,AmitPahwa,InbalSinai,DanRaine,SchabseLaks,MichaelTervoort,AlexandreAbreu,Alan

JosephWilliams,NicolasD,CindyWong,RegBraithwaite,LocalPCGuy,JonFriskics,ChrisMerriman,JohnPena,

JacobKatz,SueLockwood,MagnusJohansson,JeremyCrapsey,GrzegorzPawłowski,niconuzzaci,Christine

Wilks,HansBergren,charlesmontgomery,Arielבבל-רבFogel,IvanKolev,DanielCampos,HughWood,Christian

Bradford,FrédéricHarper,IonuţDanPopa,JeffTrimble,RupertWood,TreyCarrico,PanchoLopez,Joëlkuijten,

TomAMarra,JeffJewiss,JacobRios,PaoloDiStefano,SoledadPenades,ChrisGerber,AndreyDolganov,Wil

MooreIII,ThomasMartineau,Kareem,BenThouret,UdiNir,MorganLaupies,jorycarson-burson,NathanLSmith,

EricDamonWalters,DerryLozano-Hoyland,GeoffreyWiseman,mkeehner,KatieK,ScottMacFarlane,Brian

LaShomb,AdrienMas,christopherross,IanLittman,DanAtkinson,ElliotJobe,NickDozier,PeterWooley,John

AppendixA:Acknowledgments

YouDon'tKnowJS:Up&Going

50

AppendixA:ThankYou's!

background image

Hoover,dan,MartinA.Jackson,HéctorFernandoHurtado,andyennamorato,PaulSeltmann,MelissaGore,Dave

Pollard,JackSmith,PhilipDaSilva,GuyIsraeli,@megalithic,DamianCrawford,FelixGliesche,AprilCarterGrant,

Heidi,jimtierney,AndreaGiammarchi,NicoVignola,DonJones,ChrisHartjes,AlexHowes,johngibbon,DavidJ.

Groom,BBox,Yu'Dilys'Sun,NateSteiner,BrandonSatrom,BrianWyant,WesleyHales,IanPouncey,Timothy

KevinOxley,GeorgeTerezakis,sanjayraj,JordanHarband,MarkoMcLion,WolfgangKaufmann,PascalPeuckert,

DaveNugent,MarkusLiebelt,WellingGuzman,NickCooley,DanielMesquita,RobertSyvarth,ChrisCoyier,Rémy

Bach,AdamDougal,AlistairDuggin,DavidLoidolt,EdRicher,BrianChenault,GoldFireStudios,CarlesAndrés,

CarlosCabo,YuyaSaito,robertoricardo,BarnettKlane,MikeMoore,KevinMarx,JustinLove,JoeTaylor,Paul

Dijou,MichaelKohler,RobCassie,MikeTierney,CodyLeroyLindley,tofuji,ShimonSchwartz,Raymond,LucDe

Brouwer,DavidHayes,RhysBrett-Bowen,Dmitry,AzizKhoury,Dean,ScottTolinski-LevelUp,ClementBoirie,

DjordjeLukic,AntonKotenko,RafaelCorral,PhilipHurwitz,JonathanPidgeon,JasonCampbell,JosephC.,

SwiftOne,JanHohner,DerickBailey,getify,DanielCousineau,ChrisCharlton,EricTurner,DavidTurner,Joël

Galeran,DharmaVagabond,adam,DirkvanBergen,dave♥♫

★furf,VedranZakanj,RyanMcAllen,NataliePatrice

Tucker,EricJ.Bivona,AdamSpooner,AaronCavano,KellyPacker,EricJ,MartinDrenovac,Emilis,Michael

Pelikan,ScottF.Walter,JoshFreeman,BrandonHudgeons,vijaychennupati,BillGlennon,RobinR.,TroyForster,

otaku_coder,Brad,Scott,FrederickOstrander,AdamBrill,SebFlippence,MichaelAnderson,Jacob,AdamRandlett,

Standard,JoshuaClanton,SebastianKouba,ChrisDeck,SwordFire,HannesPapenberg,RichardWoeber,hnzz,

RobCrowther,JedidiahBroadbent,SergeyChernyshev,Jay-ArJamon,BenCombee,lucianobonachela,Mark

Tomlinson,KitCambridge,MichaelMelgares,JacobAdams,AdrianBruinhout,BevWieber,ScottPuleo,Thomas

Herzog,AprilLeone,DanielMizieliński,KeesvanGinkel,JonAbrams,ErwinHeiser,AviLaviad,Davidnewell,Jean-

FrancoisTurcot,NikoRoberts,ErikDana,CharlesNeill,AaronHolmes,GrzegorzZiółkowski,NathanYoungman,

Timothy,JacobMather,MichaelAllan,MohitSeth,RyanEwing,BenjaminVanTreese,MarceloSantos,DenisWolf,

PhilKeys,ChrisYung,TimoTijhof,MartinLekvall,Agendine,GregWhitworth,HelenHumphrey,DougalCampbell,

JohannesHarth,BrunoGirin,BrianHough,DarrenNewton,CraigMcPheat,OlivierTille,DennisRoethig,Mathias

Bynens,BrendanStromberger,sundeep,JohnMeyer,RonMale,JohnFCrostonIII,gigante,CarlBergenhem,B.J.

May,RebekahTyler,TedFoxberry,JordanReese,TerrySuitor,afeliz,TomKiefer,DarraghDuffy,Kevin

Vanderbeken,AndyPearson,SimonMacDonald,AbidDin,ChrisJoel,TomasTheunissen,DavidDick,PaulGrock,

BrandonWood,JohnWeis,dgrebb,NickJenkins,ChuckLane,JohnnyMegahan,marzsman,TatuTamminen,

GeoffreyKnauth,AlexanderTarmolov,JeremyTymes,ChadAuld,SeanParmelee,RobStaenke,DanBender,

Yannickderwa,JoshuaJones,GeertPlaisier,TomLeZotte,ChristenSimpson,StefanBruvik,JustinFalcone,Carlos

Santana,MichaelWeiss,PabloVilloslada,PeterdeHaan,DimitrisIliopoulos,seyDoggy,AdamJordens,Noah

Kantrowitz,AmolM,MatthewWinnard,DirkGinader,PhinamBui,DavidRapson,AndrewBaxter,FlorianBougel,

MichaelGeorge,AlbanEscalier,DanielSellers,SashaRudan,JohnGreen,RobertKowalski,DavidI.Teixeira

(@ditma,CharlesCarpenter,JustinYost,SamS,DenisCiccale,KevinSheurs,YannickCroissant,PauFracés,

StephenMcGowan,ShawnSearcy,ChrisRuppel,KevinLamping,JessicaCampbell,ChristopherSchmitt,Sablons,

JonathanReisdorf,BunniGek,TeddyHuff,MichaelMullany,MichaelFürstenberg,CarlHenderson,RickYoesting,

ScottNichols,HernánCiudad,AndrewMaier,MikeStapp,JesseShawl,SérgioLopes,jsulak,ShawnPrice,Joel

Clermont,ChrisRidmann,SeanTimm,JasonFinch,AidenMontgomery,ElijahManor,DerekGathright,JesseHarlin,

DillonCurry,CourtneyMyers,DiegoCadenas,ArnedeBree,JoãoPauloDubas,JamesTaylor,PhilippKraeutli,

MihaiPăun,SamGharegozlou,joshjs,MattMurchison,EricWindham,TimoBehrmann,AndrewHall,joshuaprice,

ThéophileVillard

Thisbookseriesisbeingproducedinanopensourcefashion,includingeditingandproduction.WeoweGitHubadebtof

gratitudeformakingthatsortofthingpossibleforthecommunity!

ThankyouagaintoallthecountlessfolksIdidn'tnamebutwhoInonethelessowethanks.Maythisbookseriesbe"owned"

byallofusandservetocontributetoincreasingawarenessandunderstandingoftheJavaScriptlanguage,tothebenefitof

allcurrentandfuturecommunitycontributors.

YouDon'tKnowJS:Up&Going

51

AppendixA:ThankYou's!


Document Outline


Wyszukiwarka

Podobne podstrony:
you don t know js scope closures
Adventure Midnight RPG Game Trade Magazine What You Don't Know
Dean Ing Devil You Don t Know
Spartiti Simply Red If You Don t Know Me By Now Sheet Music (Piano)
Computer Malware What You Don t Know Can Hurt You
Diana Ross Do You Know Where Youre Going To
Money Management for Women, Discover What You Should Know about Managing Your Money, but Don t!
Bearden Slides Visual Tour of what they don t want you to know about electrical circuits (www chen
Ernie Zelinski 101 Really Important Things You Already Know But Keep Forgetting
0210 You don't fool me Queen
How?n you make a good impression when going for a Job interview
things you don t always see
Teaching What You Dont Know
If You Don
Kate Sherwood Dark Horse SS (3) Sometimes You Just Know
What the EPA Don t Know Won t H Suzette Haden Elgin
Lewis Shiner You Never Know
I Don t know inst in C

więcej podobnych podstron