Skip to content

JavaScript if else shorthand | Example code

  • by

You can use the ternary operator as an if-else shorthand in JavaScript. It lets us write shorthand if..else statements exactly as we want.

Syntax

condition ? exprIfTrue : exprIfFalse

Using

var hasName = (name === 'john') ? 'Y' :'N';

It looks like this:

(name === 'john') – our condition

? – the ternary operator itself

'Y' – the result if the condition evaluates to true

'N' – the result if the condition evaluates to false

JavaScript if else shorthand

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script type="text/javascript">
   var age = 26;
   var beverage = (age >= 21) ? "Beer" : "Juice";
   
   console.log(beverage); 

 </script>

</body>
</html>

Output:

JavaScript if else shorthand

Conditional chains

The ternary operator can be “chained” in the following way, similar to a if … else if … else if … else chain:

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

source: developer.mozilla.org

How to use shorthand for if/else statement in JavaScript

Answer: To use a shorthand for an if-else statement, use the ternary operator. The ternary operator starts with a condition that is followed by a question mark ?, then a value to return if the condition is truthy, a colon :, and a value to return if the condition is falsy.

const result1 = 10 > 5 ? 'yes' : 'no';
console.log(result1); // 'yes'

const result2 = 10 > 100 ? 'yes' : 'no';
console.log(result2); // 'no'

Do comment if you have any doubts or suggestions on this JS if else topics.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading