Make Your Code Cleaner with JavaScript Ternary Operator
文章推薦指數: 80 %
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
延伸文章資訊
- 1Conditional or Ternary Operator (?:) in C/C++ - GeeksforGeeks
The conditional operator is kind of similar to the if-else statement as it does follow the same a...
- 2What is a Ternary Operator? - Computer Hope
The ternary operator is an operator that exists in some programming languages, which takes three ...
- 3Ternary Operator(三元運算子) | 歷史共業
Ternary Operator(三元運算子) - Ronnie Chang.
- 4Ternary Operator in C Explained - freeCodeCamp
Programmers use the ternary operator for decision making in place of longer if and else condition...
- 5?: operator - C# reference | Microsoft Docs
Learn about the C# ternary conditional operator that returns the result of one of the two express...