Skip to content

How to avoid if else in JavaScript

  • by

If else is a conditionals block in the Programing world. Sometimes it usually ends up having switches statements to avoid if else in JavaScript.

But you can replace them if statements with other kinds of code to make our code more readable, shorter, and cleaner. Here are some:-

  1. Ternary operator
  2. Short circuit (Using && , || operators)
  3. Object lookups
  4. Early returns and less nesting
  5. Function delegation

How to avoid if else in JavaScript

Simple example code of if-else options.

Ternary Operator

<!DOCTYPE html>
<html>
<body>
  <script>
   let age = 15;
   let result;

   if (age >= 18) {
    result = "You are eligible to vote.";
  } else {
    result = "You are not eligible to vote yet.";
  }

  console.log(result);

</script>

</body>
</html>

Output:

How to avoid if else in JavaScript

Short-circuiting operators

By putting these ideas into a conditional block we can remove the if-else statements.

The logical AND (&&) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true. Otherwise, it will be false.

const a = 3;
const b = -2;

console.log(a > 0 && b > 0);

The logical OR (||) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true.

const a = 3;
const b = -2;

console.log(a > 0 || b > 0);
// expected output: true

Object lookups

This method is used to replace switch statements and if-else ladder. The idea is to create an object or a map and get the value using a function by passing the key as an argument.

//using switch


switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

//using object look-ups


const days = {
 0:"Sunday",
 1:"Monday",
 2:"Tuesday",
 3: "Wednesday",
 4:"Thursday",
 5: "Friday",
 6:"Saturday"
}

const getDay = () => days[new Date().getDay()]

//using map look-ups

const days =new Map()
.set(0,"Sunday")
.set(1,"Monday")
.set(2,"Tuesday")
.set(3,"Wednesday")
.set(4,"Thursday")
.set(5,"Friday")
.set(6,"Saturday")


const getDay = () =>  days.get(new Date().getDay())

Source: https://www.linkedin.com/

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

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