1

I have an if statement which checks multiple conditions. I would like it to skip the conditional statement if at least one thing returns false. I can see that it is currently picking up the conditional statement if at least one thing is true.

if((api != 'abosp') || (api !='sersp') || (api !='volsp') || (api !='consp') || (api !='givsp') || (api !='blosp')){
console.log("api: " + api  );
api = 'cussp'
}

What would be the correct way to implement this kind of logic?

Currently if api == 'abosp' it will still pass into the conditional statement instead of skipping it.

1
  • this concept is called "short circuit evaluation" Commented Mar 18, 2015 at 20:39

3 Answers 3

4

You should change your || for and operator: &&. Still, a more "clean" method would be:

banned = ["abosp", "sersp", "volsp", "consp", "givsp", "blosp"]

if(banned.indexOf(api) == -1){ // if api is not in list
   console.log("api: " + api  );
   api = 'cussp'  
}
Sign up to request clarification or add additional context in comments.

Comments

1

Actually your if can't be evaluated to true since api can't be all the values you check. I guess you need an and (&&) instead of an or (||):

if ((api != 'abosp') && (api !='sersp') && ...

In this case, you can use an associative array to have more succinct code:

d = {abosp: 1, sersp: 1, volsp: 1, consp: 1, givsp: 1, blosp: 1};
if (!d[api]) api = 'cussp';

Comments

0

I think you are looking for && rather than ||.

This will skip the conditional statement if any of the individual comparisions return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.