Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu December 24, 2022 › #Javascript #Js-Tutorial

Ternary Operator Javascript

Today our topic is what the ternary operator is in JavaScript and how we can use it.

The ternary operator is a JavaScript conditional operator that is often used as an alternative to the if...else statement.

Example : Javascript Ternary Operator. #
<script> 
  // using if statement
  let x2 =  50;
  let result2 = '';

  if(x2 >  40){
   result2 = 'Passed';
  }else{
    result2 = 'Failed';
  }
  console.log(result2)
  
  // using ternary operator
  let x = 50;
  let result = x > 40 ? ' Passed' : 'Failed';
  
  console.log(result)

</script>

The ternary operator takes three operands: the condition, value if true, and value if false.

Syntax #

condition ? value if true : value if false
  1. condition : An expression whose value is used as a condition and returns a boolean value.
  2. value if true : An expression that is executed if the condition results in a true state.
  3. value if false : An expression that is executed if the condition results in a false state.
<script> 
 function getGender(isMale) {
   return (isMale ? 'Yes' : 'No');
 }

 console.log(getGender(true));
 // output: Yes

 console.log(getGender(false));
 // output: No

 console.log(getGender(null));
 // output: No
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All