JavaScript Ternary Operator (with Examples) - Programiz

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

What is a Ternary operator? ... A ternary operator evaluates a condition and executes a block of code based on the condition. ... The ternary operator evaluates the ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials OperatorsinJavaScript JavaScriptforLoop FunctionsinJavaScript JavaScriptObjects ArraysinJavaScript StartLearningJavaScript PopularExamples JavaScript"HelloWorld"Program Calculatetheareaofatriangle Checkifanumberisoddoreven FindtheGCD PrinttheFibonacciseries ExploreJavaScriptExamples ReferenceMaterials StringMethods ArrayMethods MathObject Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials OperatorsinJavaScript JavaScriptforLoop FunctionsinJavaScript JavaScriptObjects ArraysinJavaScript StartLearningJavaScript AllJavaScriptTutorials ReferenceMaterials StringMethods ArrayMethods MathObject Viewall Python JavaScript C C++ Java Kotlin PopularExamples JavaScript"HelloWorld"Program Calculatetheareaofatriangle Checkifanumberisoddoreven FindtheGCD PrinttheFibonacciseries AllJavaScriptExamples JSIntroduction GettingStarted JSVariables&Constants JSconsole.log JavaScriptDatatypes JavaScriptOperators JavaScriptComments JSTypeConversions JSControlFlow JSComparisonOperators JavaScriptifelseStatement JavaScriptforloop JavaScriptwhileloop JavaScriptbreakStatement JavaScriptcontinueStatement JavaScriptswitchStatement JSFunctions JavaScriptFunction VariableScope JavaScriptHoisting JavaScriptRecursion JSObjects JavaScriptObjects JavaScriptMethods&this JavaScriptConstructor JavaScriptGetterandSetter JavaScriptPrototype JSTypes JavaScriptArray JSMultidimensionalArray JavaScriptString JavaScriptfor...inloop JavaScriptNumber JavaScriptSymbol ExceptionsandModules JavaScripttry...catch...finally JavaScriptthrowStatement JavaScriptModules JSES6 JavaScriptES6 JavaScriptArrowFunction JavaScriptDefaultParameters JavaScriptTemplateLiterals JavaScriptSpreadOperator JavaScriptMap JavaScriptSet DestructuringAssignment JavaScriptClasses JavaScriptInheritance JavaScriptfor...of JavaScriptProxies JavaScriptAsynchronous JavaScriptsetTimeout() JavaScriptCallBackFunction JavaScriptPromise Javascriptasync/await JavaScriptsetInterval() Miscellaneous JavaScriptJSON JavaScriptDateandTime JavaScriptClosure JavaScriptthis JavaScript'usestrict' IteratorsandIterables JavaScriptGenerators JavaScriptRegularExpressions JavaScriptBrowserDebugging UsesofJavaScript RelatedTopics JavaScriptif...elseStatement JavaScriptComparisonandLogicalOperators JavaScriptwhileanddo...whileLoop JavaScriptOperators JavaScriptSwitchStatement JavaScriptnullandundefined JavaScriptTernaryOperator Inthistutorial,youwilllearnabouttheconditional/ternaryoperatorinJavaScriptwiththehelpofexamples. Aternaryoperatorcanbeusedtoreplacean if..elsestatementincertainsituations.Beforeyoulearnaboutternaryoperators,besuretochecktheJavaScriptif...elsetutorial. WhatisaTernaryoperator? Aternaryoperatorevaluatesaconditionandexecutesablockofcodebasedonthecondition. Itssyntaxis: condition?expression1:expression2 Theternaryoperatorevaluatesthetestcondition. Iftheconditionistrue,expression1isexecuted. Iftheconditionisfalse,expression2isexecuted. Theternaryoperatortakesthreeoperands,hence,thenameternaryoperator.Itisalsoknownasaconditionaloperator. Let'swriteaprogramtodetermineifastudentpassedorfailedintheexambasedonmarksobtained. Example:JavaScriptTernaryOperator //programtocheckpassorfail letmarks=prompt('Enteryourmarks:'); //checkthecondition letresult=(marks>=40)?'pass':'fail'; console.log(`You${result}theexam.`); Output1 Enteryourmarks:78 Youpasstheexam. Supposetheuserenters78.Thentheconditionmarks>=40ischeckedwhichevaluatestotrue.Sothefirstexpressionpassisassignedtotheresultvariable. Output2 Enteryourmarks:35 Youfailtheexam. Supposetheuseenters35.Thentheconditionmarks>=40evaluatestofalse.Sothesecondexpressionfailisassignedtotheresultvariable. TernaryOperatorUsedInsteadofif...else InJavaScript,aternaryoperatorcanbeusedtoreplacecertaintypesofif..elsestatements.Forexample, Youcanreplacethiscode //checktheagetodeterminetheeligibilitytovote letage=15; letresult; if(age>=18){ result="Youareeligibletovote."; }else{ result="Youarenoteligibletovoteyet."; } console.log(result); with //ternaryoperatortochecktheeligibilitytovote letage=15; letresult= (age>=18)?"Youareeligibletovote.":"Youarenoteligibletovoteyet"; console.log(result); Theoutputofbothprogramswillbethesame. Output Youarenoteligibletovoteyet. Nestedternaryoperators Youcanalsonestoneternaryoperatorasanexpressioninsideanotherternaryoperator.Forexample, //programtocheckifnumberispositive,negativeorzero leta=3; letresult=(a>=0)?(a==0?"zero":"positive"):"negative"; console.log(`Thenumberis${result}.`); Output Thenumberispositive.   Note:Youshouldtrytoavoidnestedternaryoperatorswheneverpossibleastheymakeyourcodehardtoread. TableofContents WhatisaTernaryoperator? Ternaryoperatorusedinsteadif...else Nestedternaryoperators Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsJavaScriptTutorialJavaScriptif...elseStatementJavaScriptTutorialJavaScriptComparisonandLogicalOperatorsJavaScriptTutorialJavaScriptwhileanddo...whileLoopJavaScriptTutorialJavaScriptSwitchStatement



請為這篇文章評分?