FabricioG
FabricioG

Reputation: 3320

Why is multiple if or conditions not being recognized?

The following works:

key = ['_id', 'something', 'joe', 'latitude', 'longitude']

let's assume we loop through the key:

if(key != 'longitude') {
// to ahead and execute if key is NOT longitude }

However I have three conditions I have to look for so I tried this:

    if(key != '_id' || key != 'latitude' || key != 'longitude') {
// I don't want you to execute if you're '_id', 'latitude' or 'longitude'
    }

The second one is not recognized. It allows _id, latitude, longitude to be executed. What am I doing wrong?

Upvotes: 1

Views: 44

Answers (2)

Gerhard van Zyl
Gerhard van Zyl

Reputation: 11

So the i would suggest you go look at logic gates cause they help with boolean logic in programming.. To your question. In the second case lets say the value is _id key!="latitude" will return true. So like Nina said you would have to use and (&&) and not or (||) so that the if statement is true when all 3 cases are met

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386883

You need logical AND &&, because all condition have to be true.

if (key != '_id' && key != 'latitude' && key != 'longitude') {

A shorter approach would be Array#includes.

if (!['_id', 'latitude', 'longitude'].includes(key)) {

Upvotes: 2

Related Questions