lock
lock

Reputation: 13

How to optimize nested if?

Hi I want to know is there a better way to do this? condition_a is more important than b, b is more important than c, etc.

var slot = condition_a

if (!slot) {
  slot = condition_b
  if (!slot) {
    slot = condition_c
    if (!slot) {
      slot = condition_d
      if (!slot) {
        slot = condition_e
      }
    }
  }
}

if (slot) {
  //do something
}

Upvotes: 0

Views: 106

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382170

You do a OR:

if (condition_a || condition_b || condition_c || condition_d || condition_e) {
      // do something
}

This is equivalent to your code. If a condition evaluates to true, the following ones aren't checked (it's called short circuit evaluation). It makes it possible to have checks like this:

if (a===null || a.b===0) {

Be careful that so many conditions at the same place look like a code smell: there's probably something which hasn't be designed semantically enough.

Upvotes: 3

ssilas777
ssilas777

Reputation: 9764

You can use || condition like this also,

slot = condition_a||condition_b||condition_c||condition_d;

Example Fiddle

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

if you need slot to have a value (and not just using it to test the condition at the end)

var slot = condition_a || condition_b || condition_c || condition_d || condition_e;
if (slot) {
  // do soemthing
}

Upvotes: -1

Related Questions