JavaScript ternary operator | Multiple, nested and shortHand codes

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 also called the conditional operator in JavaScript.

The ternary operator is the only JavaScript operator that takes three operands. First condition 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

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

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

Contrast this with the ternary operator:

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.

Ternary operator without else in JavaScript

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

Code for without else:-

Do comment if you have doubts and suggestion 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.