Make Your Code Cleaner with JavaScript Ternary Operator

文章推薦指數: 80 %
投票人數:10人

Introduction to JavaScript ternary operator ... In this syntax, the condition is an expression that evaluates to a Boolean value, either true or false . If the ... SkiptocontentHome»JavaScriptTutorial»JavaScriptTernaryOperatorSummary:inthistutorial,youwilllearnhowtousetheJavaScriptternaryoperatortomakeyourcodemoreconcise. IntroductiontoJavaScriptternaryoperatorWhenyouwanttoexecuteablockifaconditionevaluatestotrue,youoftenuseanif…elsestatement.Forexample:letage=18; letmessage; if(age>=16){ message='Youcandrive.'; }else{ message='Youcannotdrive.'; } console.log(message);Codelanguage:JavaScript(javascript)Inthisexample,weshowamessagethatapersoncandriveiftheageisgreaterthanorequalto16.Alternatively,youcanuseaternaryoperatorinsteadoftheif-elsestatementlikethis:letage=18; letmessage; age>=16?(message='Youcandrive.'):(message='Youcannotdrive.'); console.log(message);Codelanguage:JavaScript(javascript)Oryoucanusetheternaryoperatorinanexpressionasfollows:letage=18; letmessage; message=age>=16?'Youcandrive.':'Youcannotdrive.'; console.log(message);Codelanguage:JavaScript(javascript)Here’sthesyntaxoftheternaryoperator:condition?expressionIfTrue:expressionIfFalse;Codelanguage:JavaScript(javascript)Inthissyntax,theconditionisanexpressionthatevaluatestoaBooleanvalue,eithertrueorfalse.Iftheconditionistrue,thefirstexpression(expresionIfTrue)executes.Ifitisfalse,thesecondexpression(expressionIfFalse)executes.Thefollowingshowsthesyntaxoftheternaryoperatorusedinanexpression:letvariableName=condition?expressionIfTrue:expressionIfFalse;Codelanguage:JavaScript(javascript)Inthissyntax,iftheconditionistrue,thevariableNamewilltaketheresultofthefirstexpression(expressionIfTrue)orexpressionIfFalseotherwise.JavaScriptternaryoperatorexamplesLet’stakesomeexamplesofusingtheternaryoperator.1)UsingtheJavaScriptternaryoperatortoperformmultiplestatementsThefollowingexampleusestheternaryoperatortoperformmultipleoperations,whereeachoperationisseparatedbyacomma.Forexample:letauthenticated=true; letnextURL=authenticated ?(alert('Youwillredirecttoadminarea'),'/admin') :(alert('Accessdenied'),'/403'); //redirecttonextURLhere console.log(nextURL);//'/admin'Codelanguage:JavaScript(javascript)Inthisexample,thereturnedvalueoftheternaryoperatoristhelastvalueinthecomma-separatedlist.2)SimplifyingternaryoperatorexampleSeethefollowingexample:letlocked=1; letcanChange=locked!=1?true:false;Codelanguage:JavaScript(javascript)Ifthelockedis1,thenthecanChangevariableissettofalse,otherwise,itis set totrue.Inthiscase,youcansimplifyitbyusingaBooleanexpressionasfollows:letlocked=1; letcanChange=locked!=1;Codelanguage:JavaScript(javascript)3)UsingmultipleJavaScriptternaryoperatorsexampleThefollowingexampleshowshowtousetwoternaryoperatorsinthesameexpression:letspeed=90; letmessage=speed>=120?'TooFast':speed>=80?'Fast':'OK'; console.log(message);Codelanguage:JavaScript(javascript)Output:FastCodelanguage:JavaScript(javascript)It’sagoodpracticetousetheternaryoperatorwhenitmakesthecodeeasiertoread.Ifthelogiccontainsmanyif...elsestatements,youshouldavoidusingtheternaryoperators.SummaryUsetheJavaScriptternaryoperator(?:)tomakethecodemoreconcise.PreviouslyJavaScriptifelseifUpNextJavaScriptObjectSpreadSearchfor:GettingStartedJavaScriptFundamentalsJavaScriptOperatorsControlFlowJavaScriptFunctionsJavaScriptObjectsClassesAdvancedFunctionsPromises&Async/AwaitJavaScriptModulesJavascriptErrorHandlingJavaScriptRuntime



請為這篇文章評分?