Claire
Claire

Reputation: 3785

Is there any way of determining which or statement is true in javascript?

So say I have an if statement:

if(a=='' || b==''){

    //which is true?
}

Is it possible to determine which statement satisfied the if statement without doing a switch statement or another if statement to check?

Upvotes: 0

Views: 90

Answers (6)

sgmonda
sgmonda

Reputation: 2729

You can define a token to store what condition was true:

var token = null;
if ((a == '' && (token = 'a')) || (b == '' && (token = 'b'))) {
    // Here token has an 'a' or a 'b'. You can use numbers instead of letters
}

I think it's the simplest way to do what you want.

Upvotes: 1

user2587132
user2587132

Reputation:

if(a=='' || b==''){ var x= a || b;
//if a is ''(falsy) x will be b, else a
}

var phone="";
var email="something";

 if(phone=='' || email==''){

   var x= (phone) ? 'phone':'email';
   console.log(x); //email

}

Upvotes: 0

collapsar
collapsar

Reputation: 17258

the simple solution:

if ((ia=(a=='')) || (b=='')) {
    // ia indicate whether the boolean expression a have been true.
    // ia -> a has been true, b may have, !ia -> b has been true, a has not
}

there is no ib in the simple solution as it won't be always be set due to shortcut evaluation.

to cater for shortcut evaluation try:

if (((ia=(a=='') || (ib=(b=='')) && ((ib=(b=='')) || (ia=(a==''))) {
    // ia, ib indicate whether the corresponding boolean expressions have been  true
}

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

As others have said, you have to test the conditions separately, but you can kind of mix worlds.

var test1 = 1 == 1;  // true
var test2 = 2 == 1;  // false

if (test1 || test2) {
  // If either conditions is true, we end up here.
  // Do the common stuff
  if (test1) {
    // Handle test1 true
  }

  if (test2) {
    // Handle test2 true
  }
}

Upvotes: 1

Jon
Jon

Reputation: 437694

If you care about which of the two conditions is true the only way to find out is to test them separately, e.g.

if(a==''){
    // ...
}
else if(b=='') {
    // ...
}

Sometimes, especially in more complicated conditionals, it helps if you store the result of each condition and reuse it later on:

var isFoo = a == '';
var isBar = b == '';

// You can now use isFoo and isBar whenever it's convenient

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882336

No, you have asked explicitly if one or both are true. There's no way to work out which of those sub-expressions is true without another conditional of some sort.

If you're interested in different behaviour based on which is true, you should probably separate them with a possibly-common bit, something like

either = false;
if (a == ' ') {
    doActionsForA();
    either = true;
}
if (b == ' ') {
    doActionsForB();
    either = true;
}
if (either) {
    doActionsForAorB();
}

Upvotes: 0

Related Questions