0

I want to have a logic that returns a value based on 2 variables: a received value and a current value. I have simplified it from multiple else-if's to an operator.

The code is something like this:

var receivedState = 2;
var currentState = 1;
var allowedState = true;

if(receivedState == 2 && currentState !== 1) { 
  allowedState = 1;
} else if ((receivedState == 3 || 4 || 5) && (currentState !== 2)) { 
    allowedState = 2;
}

console.log(allowedState);

So what I am trying to do is if the received state is "2" AND current state is not "1" then I want to set the value of allowedState to 1.

What happens now is that it sets the value to 2.

For the other it does work. When the state is 3, 4 or 5 and the current state is not 2 then the value of allowedState is set to 2 except when the current state is something else than the value of 2, then the value of allowedState is 2.

How do I change my code so that the logic works as following:

If received value is 2 and current value is not 1 then return 1, else do nothing (return true). If received value is one of 3, 4 or 5 and current value is not 2 then return 2, else do nothing.

Thanks in advance.

Tolga
  • 1
  • Nina's duplicate will help some, but I can see where it may not help fully. Your terminology is a bit confused. When you say `return` some value that has a distinct link to a function, yet you have none. When you `return` something from a function, it should be the same data type (Number, String, Boolean, etc). In your description you indicated you want to `return 1` or `return 2` or `return true` or "do nothing". Thinking this way will get you into trouble. Just for your consideration. – Randy Casburn Nov 30 '21 at 14:09
  • 1
    @RandyCasburn hi, sorry for my terminology. What I mean by the return is actually just setting the value of allowedState. So I want to set the value of allowedState to 1 or 2 or doing nothing based on the conditions So for example if the received state is 2 and the current state is 1 I want it to do nothing. But if the current state is something else than 1 I want to set the value of allowedState to 1. – Tolga Nov 30 '21 at 14:33

0 Answers0