What is a ternary operator (?:) in JavaScript?

The conditional operator or ternary operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

S.NoOperator & Description
1? : (Conditional )
If Condition is true? Then value X: Otherwise value Y

Example

You can try to run the following code to understand how Ternary Operator works in JavaScript

<html>
   <body>
      <script>
         var a = 10;
         var b = 20;
         var linebreak = "<br />";

         document.write ("((a > b) ? 100 : 200) => ");
         result = (a > b) ? 100 : 200;
         document.write(result);
         document.write(linebreak);

         document.write ("((a < b) ? 100 : 200) => ");
         result = (a < b) ? 100 : 200;
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>

Related Posts

Top String Functions / Methods in JavaScript

Regular Expression in JavaScript for password validation with special character and number and string.

Password Validation in JavaScript / React

Minimum eight characters, at least one letter, one number and one special character: let ppattern = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/ Regular Expression in JavaScript for password validation with special character…

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…