Why should we use shorthand if instead of if/else statement in JS?

JS Shorthand if

In JavaScript, we call the ternary operator shorthand if statement. We can use the ternary operator instead of if/else statement. It’s also called the conditional operator, and it’s a shorthand way for an if-else statement in a single line of code. So, in this article, we will see about shorthand if operator in JS.

Why should we use shorthand if instead of if/else statement?

In some cases where using the ternary operator can be more concise and easier to read than using an if/else statement

  • Conciseness: Using the ternary operator allows you to write a conditional statement in a single line, whereas an if/else statement typically requires multiple lines.
  • Readability: If we use a ternary operator, it ternary operator can be easier to read than an if/else statement, especially when the condition is simple and the resulting code is short.
  • Code style: Some developers prefer to use the ternary operator because they find it more aesthetically pleasing or consistent with other parts of their code.

So, we take the decision to use the ternary operator or an if/else statement comes down to personal preference and the specific requirements of the code you are working on.

Syntax of shorthand if

condition ? expressionIfTrue : expressionIfFalse

In this above syntax:

  • The ‘condition‘ is an expression that evaluates to a boolean value.
  • The ‘expressionIfTrue‘ will be executed if the given expression is true.
  • And ‘expressionIfFalse‘ will be executed if the given expression is false.

Example of shorthand if in js

let age = 20;
let isAdult;

// Using an if/else statement
if (age >= 18) {
  isAdult = true;
} else {
  isAdult = false;

console.log(isAdult); // Output: true

// Using a ternary operator
isAdult = age >= 18 ? true : false;

console.log(isAdult); // Output: true

In this code:

  • We have initialized the variable ‘age’ to 20 and declared ‘isAdult’.
  • Then we check if a person is an adult based on their age.
  • Using the if/else statement, we check if the age is greater than or equal to 18, and assign the true or false value to the isAdult variable accordingly.
  • Using the ternary operator, we can achieve the same result more concisely by using the ternary operator to assign the true or false value based on the same condition.

Leave a Reply