How to improve this "if, else if" code?

I tried to use the OR operator || to improve this code, but it didn't work the way I though. Is there anyway to simplify this code. The number are all integers.

if (HeatPumpTemp_MB === 19) {HeatPumpTemp_MB = HeatPumpTemp_MB + 1;}
else if (HeatPumpTemp_MB === 21) {HeatPumpTemp_MB = HeatPumpTemp_MB + 1;}
else if (HeatPumpTemp_MB === 23) {HeatPumpTemp_MB = HeatPumpTemp_MB + 1;}
else if (HeatPumpTemp_MB === 25) {HeatPumpTemp_MB = HeatPumpTemp_MB + 1;}
else {HeatPumpTemp_MB = HeatPumpTemp_MB + 2;}

The only option I could think of was:

if (HeatPumpTemp_MB === 19 || HeatPumpTemp_MB === 21 || HeatPumpTemp_MB === 23 || HeatPumpTemp_MB === 25) {HeatPumpTemp_MB = HeatPumpTemp_MB + 1;}

Which is a slight improvement, but I thought there might have been a better option.

Not sure what you are trying to achieve; if < 19 then +2 ?

If you create an array of your HeatPumpTemp_MB(s) of interest, you can simply check to see if your current HeatPumpTemp_MB is in your array, if so add one, if not add two:

let interestingMB = [19,21,23,25];

I think you can figure it out from here :slight_smile:

PS: This has very little to do with Node-RED as is just a basic programming 101 question, regardless of the language you are programming in.

What are the else conditions if any?

Personally, I like to use the JS switch statement for cases like this...
https://www.w3schools.com/jsref/jsref_switch.asp

So your example could be rewritten something like this (untested):

switch(HeatPumpTemp_MB) {
  case 19:
  case 21:
  case 23:
  case 25:
    HeatPumpTemp_MB += 1;
    break;
  default:
    HeatPumpTemp_MB += 2;
}
1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.