Shorthand If Else in JavaScript

Shorthand If Else in JavaScript | Employing the ternary operator to use a shorthand for an if-else statement. The ternary operator begins with a condition, which is then continued by a question mark ‘(? )’, a value to be returned if the condition is true, a colon ‘(:)’, and a value to be returned if the condition is false. See in detail:- Ternary Operator in JavaScript

Example-1:- Shorthand If Else in JavaScript

Assume we have a program to find whether the given number is odd or even using the simple if-else statement.

let result = null;
if(5 % 2 === 0) {
    result = "Even";
} else {
    result = "Odd";
}
console.log(result); 

Output:-

Odd

The same program can be written using shorthand if else in JavaScript as follows:-

let result = (5 % 2 === 0) ? "Even" : "Odd";
console.log(result); 

Output:-

Odd

We shortened an if-else statement using the ternary operator. Before the question mark (?) condition is placed, similar to a condition in an if statement enclosed in parenthesis. The value before the colon (:) is returned if the condition evaluates to a true value; otherwise, the value following the colon is returned.

All values in JavaScript that are truthy are those that are not false. False, null, undefined, 0, "" (empty string), and NaN are examples of false values (not a number). The value before the colon is returned by the ternary operator if the condition evaluates to any other value.

Here’s a simple way to consider it:- Your if block is the value before the colon, and your else block is the value following the colon.

Let us see another example for shorthand if else in JavaScript.

Example-2:- Shorthand If Else in JavaScript

const result1 = 5 > 2 ? "true" : "false";
console.log(result1); //true

const result2 = 10 > 50 ? "true" : "false";
console.log(result2); //false

Output:-

true
false

Example-3:- Shorthand If Else in JavaScript

function sum(a, b) {
  return a + b;
}

const result = sum(1, 5) > 5 ? sum(10, 5) : sum(1, 1);
console.log(result); // 15

Output:-

true

To determine the return value from a ternary operator, we can use expressions. In the above example, we saw that the console returned 15 as the sum of 1 and 5 is greater than 5. If it would’ve been less, the console would return 2.

In this case, the condition evaluates to true, the function to the left of the colon is called, and the operator returns the value of the function. This article helped us with understanding using the ternary operator as shorthand instead of if-else statements. 

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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