Guide to the Ternary Operator in JavaScript - Stack Abuse
文章推薦指數: 80 %
A ternary operator is a three-operand operator that is supported in most programming languages, including JavaScript, Java, C++, C#, ... SALogotypeArticlesLearnWritewithUsSigninSignupPythonJavaScriptJavaHomeArticlesGuidetotheTernaryOperatorinJavaScriptJoelOlawanleIntroduction Aternaryoperatorisathree-operandoperatorthatissupportedinmostprogramminglanguages,includingJavaScript,Java,C++,C#,andmanyothers.Itisalsoreferredtoasaconditionaloperatorbecauseitisconsideredtobeamoreconcisealternativetotheconditional(if-else)statement. Inthisguide,wewilllearnwhattheternaryoperatorisandhowitworksinJavaScript.Also,we'lldoabriefcomparisonwiththeif-elsestatement,soweknowwhentousewhichone. TernaryOperatorinJavaScript Asinanyotherlanguage,ternaryoperatorinJavaScripthasthreeoperands: (condition)?returnExpressionIfTrue:returnExpressionIfFalse; Wecaneasilytranslatethistothecorrespondingif-elsestatement: if(condition){ returnExpressionIfTrue; }else{ returnExpressionIfFalse; } ThisbasicallymeansthattheconditionandthereturnExpressionIfTruecorrespondtotheifclauseofthecorrespondingif-elsestatement,andthereturnExpressionIfFalsecorrespondstotheelsesectionofthementionedstatement. Iftheconditionevaluatesastrue,thereturnExpressionIfTrueexpressionisexecuted.Ontheotherhand,iftheconditionisevaluatedasfalse,thereturnExpressionIfFalseisexecuted. Note:Tobemoreprecise,JavaScriptchecksiftheconditionevaluatesastruthyorasfalsyvalue.FalsyvaluesareallvaluesthatJavaScriptevaluatesasfalseinabooleanexpression-false,none,undefined,NaN,0,-0,0n,and"".Alltheothervaluesareevaluatedastrueinabooleanexpression-thusconsideredtruthy. HowtoUseTernaryOperator Aperfectwaytoexplaintheternaryoperatorwouldbetocompareitwiththeif-elsestatement.Supposewehaveacertainageandwewanttocheckwhetherauserisyoungerthanthatornot: letage=21; letresult; if(age>=20){ result="Usercanviewcontent"; }else{ result="Usercannotviewcontent"; } console.log(result); Let'srewritethisif-elseblockusingternaryoperator: letage=21; letresult=age>=20?"Usercanviewcontent":"Usercannotviewcontent"; console.log(result); Basically,anythingbeforethequestionmark(?)istheconditionwearechecking.Theothertwooperandsareexpressions,thefirstonebeforethesemi-colon(:)andthesecondafter.Iftheconditionistrue,thevalueoftheresultwillbe"Usercanviewthecontent".Otherwise,thevalueassignedtotheresultwillbe"Usercannotviewthecontent". Let'stakealookatanotherinterestingexample: letname="JohnDoe"; if(name){ console.log("Hello"+name); }else{ console.log("Hello"+"Guest"); } Sincethenameisanon-emptystring,itisconsideredtobeatruthyvalue.Therefore,thisexamplewillresultinlogging"HelloJohnDoe"intheconsole.Ifthenamewereanemptystring-theoutputwillbe"HelloGuest".Thisscenarioiseasilyconvertibletotheternaryoperator: letname="JohnDoe"; name?console.log("Hello"+name):console.log("Hello"+"Guest"); Althoughmaybeabovethescopeofthisguide,anotherinterestingsolutionistousethelogicaloroperatorinsteadoftheternaryoperator.Thiswillyielduswiththeabsolutelythesameresultastheothertwoapproaches: console.log("Hello"+(name||"Guest")); HandlingMulti-LineExpressionsWiththeTernaryOperator Takingalookatthefirstexpression,wewillnoticethatwewereabletocollapseafive-lineif-elseblockintoasingle-lineternarystatement.Supposewewanttohandlemulti-lineexpressionswiththeternaryoperator: constage=22; letyouth; if(age<=30){ youth=true; console.log("IamaYouth!"); }else{ youth=false; console.log("IamanAdult!"); } console.log(youth); Wewouldhavetoplacetheseexpressionsinbracketsandthenseparateeachbyacomma: age<=30 ?((youth=true),console.log("IamaYouth!")) :((youth=false),console.log("IamanAdult!")); Eventhoughthecodeusingternaryoperatorsisshorter,eventhistwo-lineexpressionmakestheternaryoperatorprettyhardtoreadandunderstand.That'sthereasonwhyit’sbestnottousetheternaryoperatorformulti-lineexpressions-abetteralternativeistostickwiththeif-elseblockinsituationslikethis. NestedTernaryOperators Anestedternaryoperatorreferstotheabilitytoplaceaternaryoperatorwithinanother.Thesestatementsareusedwhenwewanttoevaluatemultipleconditions.Forexample,withtheif-elsestatementwecanusetheelseifstatementtonestmultipleconditionstogether: FreeeBook:GitEssentialsCheckoutourhands-on,practicalguidetolearningGit,withbest-practices,industry-acceptedstandards,andincludedcheatsheet.StopGooglingGitcommandsandactuallylearnit!DownloadtheeBook letstudentScore=65; letstudentGrade; if(studentScore>=70){ studentGrade="A"; }elseif(studentScore>=60){ studentGrade="B"; }elseif(studentScore>=50){ studentGrade="C"; }elseif(studentScore>=45){ studentGrade="D"; }else{ studentGrade="E"; } console.log(`Yourgradeis${studentGrade}`); Whenweimplementthiswiththeternaryoperator,wewillhavesomethinglikethis: letstudentScore=65; letstudentGrade=studentScore>=70?"A" :studentScore>=60?"B" :studentScore>=50?"C" :studentScore>=45?"D" :"E"; console.log(`Yourgradeis${studentGrade}`); Thiscanquicklybecomedifficulttoreadifwedon'tpayattentionandproperlyunderstandhowtheternaryoperatorworks.Moreimportantly-evenifyoucanreadthis-whataboutyourcolleagues?Incaseslikethis,itisrecommendedweusetheif-elseortheswitchstatementsratherthanwritingcodethatcanconfuseothers. Conclusion Aswe'veseeninthisguide,ternaryoperatorandif-elsestatementcanbeusedprettymuchinterchangeablyandit'suptoyoutodecidewhentochooseoneovertheother.Generallyspeaking,theternaryoperatorisnotdesignedtoultimatelyreplacetheif-elsestatement.Instead,itaimstobeavalidalternativeinscenarioswhereif-elsejustcreatesunnecessaryoverhead-whentheoutcomeissosimplethatanythingbesidesasimpleternaryoperatortakestoomuchspaceinthecode. Inthisguide,wetookalookatwhataternaryoperatorisandhowtomakeuseofitinJavaScript.Itmayseemabitintimidatinginthebeginning,butafterreadingthisguideyoushouldunderstandhowitworksandwhatisthedifferencebetweenaternaryoperatorandif-else,soyouknowwhentochooseoneovertheother. #javascriptLastUpdated:May30th,2022Wasthisarticlehelpful?Youmightalsolike...JavaScript:CheckifFirstLetterofaStringisUpperCaseUsingMocksforTestinginJavaScriptwithSinon.jsFor-eachOveranArrayinJavaScriptUsingGlobalVariablesinNode.jsCommentingCodeinJavaScript-TypesandBestPracticesImproveyourdevskills!Gettutorials,guides,anddevjobsinyourinbox.EmailaddressSignUpNospamever.Unsubscribeatanytime.ReadourPrivacyPolicy.JoelOlawanleAuthorFrontendDeveloper&TechnicalWriter DimitrijeStamenicEditorInthisarticleIntroductionTernaryOperatorinJavaScriptHowtoUseTernaryOperatorHandlingMulti-LineExpressionsWiththeTernaryOperatorNestedTernaryOperatorsConclusionGettingStartedwithAWSinNode.jsBuildthefoundationyou'llneedtoprovision,deploy,andrunNode.jsapplicationsintheAWScloud.LearnLambda,EC2,S3,SQS,andmore!Learnmore Wantaremotejob? MoreJobsJobsbyHireRemote.ioTwitterGitHubFacebook©2013-2022StackAbuse.Allrightsreserved.DisclosurePrivacyTermsDonotsharemyPersonalInformation.
延伸文章資訊
- 1How do you use the ? : (conditional) operator in JavaScript?
The conditional (ternary) operator is the only JavaScript operator that takes three operands. Thi...
- 2JavaScript Ternary Operator - Pi My Life Up
This is the only conditional operator supported by JavaScript and is useful for setting a value b...
- 3JavaScript Ternary Operator (with Examples) - Programiz
A ternary operator evaluates a condition and executes a block of code based on the condition. Its...
- 4Ternary Operator in JavaScript - Scaler Topics
A Ternary Operator in Javascript is a special operator which accepts three operands. · It is also...
- 5Guide to the Ternary Operator in JavaScript - Stack Abuse
A ternary operator is a three-operand operator that is supported in most programming languages, i...