In Focus

Ternary Conditional Operator In TypeScript

In this article, I will explain the ternary operator and how to use it in TypeScript with an example.

Introduction
 
The ternary conditional operator(?) is not a statement but it creates conditional logic. It is used to assign a certain value to a variable based on a condition.
 
It will return the value on the left of the colon ( : ) if the expression is true, and return the value on the right of the colon if the expression is false.
 
TypeScript ternary operators take three operands.
 
Syntax
 
condition ? result1 : result2;
 
The following example shows how to use a ternary condition operator in TypeScript.
 
Step 1
 
Open Visual Studio 2012 and click "File" -> "New" -> "Project...". A window is opened. In this window, click HTML Application for TypeScript under Visual C#.
 
Provide the name of your application as "Ternary_Operator" and then click "Ok".
 
Step 2
 
After this session the project has been created; a new window is opened on the right side. This window is called the Solution Explorer. The Solution Explorer contains the ts file, js file andcss files.
 
Coding
 
ternary_operator.ts
  1. class ternary_operator  
  2. {  
  3.     condition()  
  4.     {  
  5.         var first = 5;  
  6.         var second = 3;  
  7.         var result = (first > second) ? "That is true : 5>3" : "That is false : 5<3";  
  8.         alert(result);  
  9.     }  
  10. }  
  11. window.onload = () =>  
  12. {  
  13. var obj = new ternary_operator();  
  14. obj.condition();  
  15. };  
ternaryoperatot_Demo.htm
  1. <!DOCTYPEhtml>  
  2. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta charset="utf-8"/>  
  5. <title>Ternary operator</title>  
  6. <link rel="stylesheet" href="app.css"type="text/css"/>  
  7. <script src="app.js"></script>  
  8. </head>  
  9. <body>  
  10. <h2>Ternary Condition Operator in TypeScript</h2>  
  11. <div id="content"/>  
  12. </body>  
  13. </html>  
app.js
  1. var ternary_operator = (function() {  
  2. function ternary_operator() { }  
  3. ternary_operator.prototype.condition = function()  
  4. {  
  5.     var first = 5;  
  6.     var second = 3;  
  7.     var result = (first > second) ? "That is true : 5>3" : "That is false : 5<3";  
  8.     alert(result);  
  9. };  
  10. return ternary_operator;  
  11. })();  
  12. window.onload = function()  
  13. {  
  14.     var obj = new ternary_operator();  
  15.     obj.condition();  
  16. };  
  17. //@ sourceMappingURL=app.js.map  
Output
 
ternary conditional operator
 
Reference By