Sei sulla pagina 1di 4

On&&and||inJavascript

April3rd,2009
Forabetterunderstandingofthe&&(and)and||(or)operatorsinJavascript,youneedtoknow
abouttwooftheirproperties:
1. Theyshortcircuitevaluations
2. Theyevaluatetotheirlastevaluatedoperator

Shortcircuitingevaluations
LikemanyotherlanguagesJavascripts&&and||operatorsshortcircuitevaluations,thatis,for&&if
thefirstoperandevaluatestofalse,thesecondoperandisneverevaluatedbecausetheresultwould
alwaysbefalse.Similarly,for||iftheresultofthefirstoperandistrue,thesecondoperandisnever
operated.
Thismeansthatinthefollowingexpression,xwillneverbecomparedtoy.
true || x == y

Thisshortcircuitingisgreatforperformance,asitallowssignificantbitsofcalculationstobeskipped.
Inadditiontothat,itletsyoutowritee.g.thefollowinginoneexpressionwithoutgettinganobject
hasnopropertieserror:
oNode && oNode.firstChild

Bemindfulthoughwhenusing&&withcodethathassideeffects,e.g.sayyouhavetwoobjectswith
anisValid()methodwhichreturnsfalsewhenavalidationerroroccursandadditionallyoutputsan
errormessage:
x.isValid() && y.isValid()

Here,ifxhasanerror,ywillneverbeevaluatedandthustheerrormessagewillneverbeshown.

Evaluationtothelastevaluatedoperator
Onedetailpeopleoftendonotrealiseabouttheoperators&&and||inJavascript,isthattheydonot
returnabooleanvalue(trueorfalse),butthevalueofthelastoperandtheyevaluate.So:
false || null

Willreturnnull,andnotfalse.Additionally,becauseoftheabovementionedshortcircuiting:
null && false

Willreturnnullaswell.
Usually,youdontevennoticethisbehaviourbecausetheifstatementdoesntcarewhetheritgetsa
booleanornot,butoccasionallythismayleadtounexpectedresultswhenyouarenotawareofthis.
Upsideofthestoryisthatbyusingthisbehaviourandapplyingtheseoperatorsmoregenerally,you

canmakeyourcodeshorterbyremovingduplication,andevaluatetomorepredictableresults.Some
examplesthatshowsomeusefulapplicationsofthis,alongwiththeirequivalentexpressionusingthe
ternary?:operator:
oObject.textValue || ''
oObject.textValue ? oObject.textValue : ''

Thisuses||tospecifyadefaultvalueincasetextValueisundefinedornull,andavoidswriting
oObject.textValuetwice.
Similarly,InternetExplorerdoesnotsupportthelocalNamepropertyonXMLelements,youhavetouse
baseNameinstead.Using||,itiseasytowrite:
(oElm.localName || oElm.baseName) == 'data'
(oElm.localName ? oElm.localName : oElm.baseName) == 'data'

Ifyouneedsomepropertyfromeitheroftwoobjects:
(oElm1 || oElm2).firstChild
(oElm1 ? oElm1 : oElm2).firstChild

Using&&isusefulifyouonlyneedtoreturnsomepropertyiftheobjectisnotnull:
oNode && oNode.firstChild
oNode ? oNode.firstChild : null

Thisofcourseonlyworksiftheexpressionbeforethe&&evaluatestoavaluethatyouwanttoreturn.
Ifyoucombine&&with||,yougetaguardlikeconstructsimilartotheternaryoperator:
oNode && oNode.firstChild || null
oNode ? oNode.firstChild ? oNode.firstChild : null : null

Similar,butdifferentinthedetails,asyoucanseeinthe?:equivalentthe&&||versionwill
additionallymakesurethatfirstChildreturnsnullifeitheroNodeoroNode.firstChilddonotexist,
insteadofpossiblyreturningundefined.Perhapsthisisnotthebestofexamples,becauseintheDOM
firstChildisnullwhenthereisnone,butyougettheidea.
Funfact,foraverylongtimethePythonprogramminglanguagedidnothaveaternaryoperatorand
insteadprogrammersusedthePythonandandoroperators.
Justasmallevolutionofthelastexample:
oNode && oNode.firstChild || oNode || null
oNode ? oNode.firstChild ? oNode.firstChild : oNode : null

Bystringingabunchofthesetogether,youcanuseitinevencrazierwayswhichcanmakeyourcode
shorterandeasiertoreadifyouunderstandthelanguageconstructproperly.
Grauw

Comments

ThanksbyLukeGedeonat2012063022:32
GreatexplanationofandandorinJS.Ineverreallythoughtaboutstringingthemthatway
before.Youhavejustincreasedmycodequalitysignificantly.
byCeasarat2012123100:34
Whatdoyoumean:
```
Infact,foraverylongtimethePythonprogramminglanguagedidnothave?:andinstead
programmersusedthePythonandandoroperators.
```
Pythonstilldoesnothaveaternaryoperator(itdoeshave`aifbelsec`ifthatswhatyoumean).
Re:aifbelsecbyGrauwat2012123112:33
YesthatswhatImean.Syntaxisdifferentbutfunctionisthesame.Whyareyousayingthatisnot
theternaryoperator?Whatelsewouldyouimagineittobe?
(p.s.Iupdatedthatparagraphtosayternaryoperatorinsteadof?:giventhesyntacticdifference,
andaddedalinktovanRossumsannouncement.)
StrongWork,KeepItUpbyBryanO'Doyleat2013081721:16
Thanksforthetimeandeffortwhichwentintopreparingthisthoroughtreatmentofthe
subject.Untiltheproperuseofthesebecomessecondnature,Illkeepalinktoyour
resourcehandy!
NicearticlebyFSat2013111018:33
Goodarticleonthe&&and||operators.
Justwannadiscussonequestionwithyou:
Inthelastsmallevolutionexample,itreads,
oNode&&oNode.firstChild||oNode||null
oNode?oNode.firstChild?oNode.firstChild:oNode:null
Doesthissectionwanttoexpresstheresultisthesameorthelogicisthesame?
Forexample,ifweuseamoregenericformtoexpressthatexample:
varA=true,B=false,C=undefined,a
a=A&&B||C||null//InS0,aisnull
a=A?B?B:C:null//InS1,aisundefined
a=A?B?B:C?C:null:null//InS2,aisnull
S2getsthesamevalueasS0does,butS1doesntsinceS2andS0runtheequivalentchecking
logics.
HoweverifwereplaceCsvaluewithAsvaluethenS0,S1andS2wouldgetthesamevalue.

SoIamwonderingwhatthelastexampleisexpressing?
Re:NicearticlebyGrauwat2014010517:26
HiFS,
HoweverifwereplaceCsvaluewithAsvaluethenS0,S1andS2wouldgetthesame
value.
Indeed,inthelastexample,thereisnoC,justAandB(whereAappearstwice).Imeantto
illustratethattheversionusing&&and||isabitshorterandnicerontheeyes.
However,IthinkiftherewasaC,the&&||versionyieldsabetterresult(neverundefined).The?:
versionwouldhavetogetevenlongertoreplicatethat.
questionaboutx.hasError()&&y.hasError()bySerchat2014020605:31
Hi!,Thanksforsuchahandyresource.Imnotsurewhatyoumeanwhenyousay:
x.hasError()&&y.hasError()
Here,ifxhasanerror,ywillneverbeevaluatedandthustheerrormessagewillneverbeshown.
WhatIunderstandisthefollowing:
varx={hasError:function(){console.log(erroronx)returntrue}}
vary={hasError:function(){console.log(errorony)returntrue}}
inthiscasevartest=x.hasEror&amp&ampy.hasError()willevaluatebothxandy,
output:
erroronx
errorony
Couldyouclarifythatpoint?
Thanks,
Serch
Re:questionaboutx.hasError()&&y.hasError()byGrauwat2014020719:19
HeySerch,youreright,itsabadexampleIvechangedit!
Addacomment

Potrebbero piacerti anche