Home > Software engineering >  How to simplify multiple if else conditions in JavaScript - React JS
How to simplify multiple if else conditions in JavaScript - React JS

Time:12-22

how to reduce this condition logic in a simpler way. if the status values increase the conditions go on and on, please help to write a clean code

const getColor = status => {
    if (status === 'positive') {
      return { backgroundColor: 'red' }
    } else if (status === 'negative') {
      return { backgroundColor: 'orange' }
    } else if (status === 'neutral') {
      return { backgroundColor: 'blue' }
    }else if (status === 'none') {
      return { backgroundColor: 'white' }
    }else if (status === 'all') {
      return { backgroundColor: 'black' }
    }
  }

     <p style={getColor(result.sentiment_label)}>test</p>

CodePudding user response:

For your usecase, you can use switch :

switch (status) {
  case 'positive':
    return { backgroundColor: 'red' }
  case 'negative':
    return { backgroundColor: 'orange' }
  ...
  default:
    return { backgroundColor: 'black' }
}

Another solution, which is shorter (but can be harder to read) can be :

const statusBgColorMap = {
  positive: 'red',
  negative: 'orange',
  ...
}

return { backgroundColor: statusBgColorMap[status] || 'defaultcolor' }

CodePudding user response:

Use object instead:

const COLORS = {
  positive: "red",
  negative: "orange",
  neutrla: "blue",
  none: "white",
  all: "black",
}

<p style={{ backgroundColor: COLORS[result.sentiment_label] }}>
  test
</p>

CodePudding user response:

switch statement maybe? Itll certainly read much nicer:

    const getColor = status => {
      switch(status) {
        case 'positive':
          return 'red';
        break;
        case ''negative:
          return 'orange'
        break;
        case ''neutral:
          return 'blue'
        break;
       case ''none:
          return 'white'
        break;
      default:
        return 'black'
     }
    }
    
  <p style={{backgroundColor: getColor(result.sentiment_label) }}>test</p>

CodePudding user response:

One way could be the following:

const getColor = status => {
        if (status === 'positive') return { backgroundColor: 'red' }
        if (status === 'negative') return { backgroundColor: 'orange'}
        if (status === 'neutral') return { backgroundColor: 'blue' }
        if (status === 'none') return { backgroundColor: 'white' }
        if (status === 'all') return { backgroundColor: 'black' }
        return null
      }

Considering that you return inside the if statement next conditions won't run, thus you don't need else if. Furthermore you can remove curly brackets considering that you only have one command per if statement

  • Related