Skip to content

JavaScript ternary operator | Multiple, nested and shortHand codes

  • by

JavaScript ternary operator is frequently used as a shortcut for the if statement. It’s a one-line shorthand for an if-else statement and is also called the conditional operator in JavaScript.

The ternary operator is the only JavaScript operator that takes three operands. First condition is followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

Syntax

condition ? exprIfTrue : exprIfFalse

Parameters values

  • condition: expression whose value is used as a condition.
  • exprIfTrue: Value or expression on true condition.
  • exprIfFalse: Value or expression on false condition.

Example of JavaScript ternary operator

Let’s see the example of how to use the ternary operator as the shortcut for the if-else statement in JavaScript

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	var age = 19;
	var canDrive = age > 16 ? 'YES' : 'No';
	alert(canDrive)
    </script>  
</head>  
</html> 

Output:

JavaScript ternary operator

Ternary operator multiple conditions JavaScript

The ternary operator seems more appropriate since you have fewer conditions, although an if would be much easier to read on Multiple conditions.

If-else statement for multiple conditions

String year = "senior";
if (credits < 30) {
  year = "freshman";
} else if (credits <= 59) {
  year = "sophomore";
} else if (credits <= 89) {
  year = "junior";
}

Contrast this with the ternary operator:

String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";

Nested ternary operator JavaScript

You must search first What is an Alternative to the nested ternary operator in JS? Because the nested ternary operator is a very complicated expression.

Here are alternatives:-

  1. That if/else you don’t want to do
  2. A switch combined with if/else

JavaScript ternary shorthand

use ||. Unlike PHP, JavaScript’s || operator will return the first non-falsy value, not a normalized Boolean.

foo || 'world'

Ternary operator without else in JavaScript

First of all, a ternary expression is not a replacement for an if/else construct – it’s equivalent to an if/else construct that returns a value. That is, an if/else clause is code, and a ternary expression is an expression, meaning that it returns a value.

Code for without else:-

var x = condition || null;

Do comment if you have doubts or suggestions on this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *