user13861136
user13861136

Reputation:

How to detect if some, but not all variables are equal to `null`

I have been having some problems with the if statement detecting if some but not all variables are equal to null can someone help me with this?


 else if (co != 2 || o != 0 || d != 0 || e != 6)
                       
                       if (co == null && o == null && d == null && e == null) {
                          alert("foo") 
                      document.getElementById("e1").innerHTML += "<div class='alert alert-danger alert-dismissible fade show' role='alert'><strong>Error</strong> You didn't enter anything.<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button></div>"
                
                       } else if (co != null || o != null || d != null || e != null){
                           alert("bar")
                       document.getElementById("e1").innerHTML += "<div class='alert alert-danger alert-dismissible fade show' role='alert'><strong>Nope.</strong> You entered the wrong code.<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button></div>"
                       }

PS: I copied the part of the JS that’s why you see the else not actually having an if to start it ( also i wanted to keep things secret)

Upvotes: 1

Views: 62

Answers (2)

user13861136
user13861136

Reputation:

I actually Ended up changing the first part of the comparison to === instead == and i also realized that i put the value to ’null’ (as a string) and actually not as a number therefore the 1st if was failing to successfully detect if null=‘null’ there fore making the 2nd if appear true

Upvotes: 0

Mureinik
Mureinik

Reputation: 311308

I'd put all these variables in an array and then use some to check that some of them are null and some aren't:

const arr = [co, o, d, e];
if (arr.some(x => x === null) && arr.some(x => x !== null)) {
    alert("some are null and some aren't");
}

Upvotes: 4

Related Questions