LasagnaAndroid
LasagnaAndroid

Reputation: 2945

How to know which condition was true in an if statement?

How can I know which condition in an if statement in JavaScript was true?

if(a === b || c === d){ console.log(correctValue) }

How can I know if it was either a === b or c === d?

Edit: I wanted to know if there was any way of doing this besides checking each condition on it's own if statement.

Upvotes: 3

Views: 3857

Answers (3)

Addy_dev
Addy_dev

Reputation: 1

You can try something like this:

if(e = (a === b) || (f= c === d)){ console.log(e, f, correctValue) }

Then You can check whether e or f is true, then make your changes.

I don't know about memory leak or something for this but yeah it works.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149088

If you really need to know which condition was true, just test them separately:

if(a == b) {
    console.log("a == b");
    return true; 
} else if(c == d) {
    console.log("c == d");
    return true; 
}

Alternatively, you might prefer something like this:

var result;
if ((a == b && result = "a == b") || (c == d && result = "c == d")) {
    console.log(result);
    return true;
}

This code is effectively equivalent to the former, however, I wouldn't recommend using this in a production system. It's much harder to read and guess the original intent of the code—it's likely that the person reading this after you would think the result = was supposed to be result ==. Also note that because empty strings are falsy, you must ensure that the string you assign to result is never empty, otherwise it would never enter the if-block.

Upvotes: 1

Dan Abramov
Dan Abramov

Reputation: 268323

You can't.
If it matters, it needs to be two different conditions.

if (a == b) {
  // it was a == b
  return true;
}

if (c == d) {
  // it was c == d
  return true;
}

Note that even so, you won't know if both or just one of these conditions is true.
If you want to know this as well, you'll want an additional if:

if (a == b && c == d) {
  // a == b and c == d
} else if (a == b) {
  // just a == b
} else if (c == d) {
  // just c == d
}

return (a == b || c == d);

Upvotes: 2

Related Questions