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>
   let age = 15;
   let result;

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





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";
  case 1:
    day = "Monday";
  case 2:
     day = "Tuesday";
  case 3:
    day = "Wednesday";
  case 4:
    day = "Thursday";
  case 5:
    day = "Friday";
  case 6:
    day = "Saturday";

//using object look-ups

const days = {
 3: "Wednesday",
 5: "Friday",

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

//using map look-ups

const days =new Map()

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


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

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