How to simplify multiple if statements javascript?

29,762

Solution 1

The first half of you code looks fine. For the second half of your code you should make use of a switch statement. These replace the if-else statements you are using and decide what to do when certain "cases" occur. For example:

switch(status) {
    case 'active':
        //background green
        break;
    case 'onhold':
        //background yellow
        break;
    case 'inactive':
        //background red
        break;
    default:
        //background grey
        break;
}

Solution 2

My idea is:

var icons = {
    a: 'a.png',
    b: 'b.png',
    c: 'c.png',
    d: 'd.png',
}

if (date != -1) {
    Object.keys(icons).forEach(function(key) {
        if (data[key]) {
            //Add icon icons[key]
        }
    });
}

var statusColors = {
    active: 'Green',
    onhold: 'Yellow',
    inactive: 'Grey',
}

//Background statusColors[status]

Solution 3

I think it is pretty good as it is. Is is better to have understandable code than complex code that does exactly the same thing.

You don't have to do

if (a === true)

as it's equivalent to

if ( a )

Share:
29,762
Aasim Hussain Khan
Author by

Aasim Hussain Khan

Updated on August 09, 2020

Comments

  • Aasim Hussain Khan
    Aasim Hussain Khan almost 4 years

    I have multiple conditions to check. I have to add icons based on the conditions, Then I need to change the background color based on some other set of conditions. I am using if statement. This is my code.

    JSON:

    {
      "date": "2017-05-12",  
      "a": false,
      "b": true,
      "c": true,  
      "d": false,
      "status": "active"
    }
    

    Javascript:

     if (date != -1) {
      //do something
      if (a) {
        //Add icon a
      }
      if (b) {
        //Add icon b
      }
      if (c) {
        //Add icon c
      }
      if (d) {
        //Add icon d
      }
    }
    
    if(status == "active"){
      //Background Green
    }
    else if (status == "onhold"){
      //Background Yellow
    }
    else if (status == "inactive"){
      //Background Red
    }
    else{
      //Backgeound Grey
    }
    

    How do I simplify it?