Try it here
Subscribe
Ternary Operator

Ternary (Conditional) operator in Javascript

ternary_(conditional)_operator_in_javascript

The Ternary operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is true followed by a colon (:), and finally the expression to execute if the condition is false. This operator is frequently used as a shortcut for the if statement.

Syntax:

 condition ? expression if condition is true : expression if condition is false

Example:

<script>
  var a =10;
  var b =5;
  c = if a > b ? a : b ;
  alert(c);
</script>

Conditional chains:

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:

Example :

fun()
{
 return condition1 ? value1
       :condition2 ? value12
       :condition3 ? value13
       :value14
}

Writer profile pic

Amit on Apr 18, 2020 at 12:04 am


This article is contributed by Amit. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.