Muhammad Umer
Muhammad Umer

Reputation: 18097

How do i simplify this conditional logic in javascript?

So here is the situation i don't want to have to write doA twice...and i feel it should be possible to achieve that without resorting to functions.

How can i do it?

Also i remember reading on SO about labels to do something like this. Can you show me how's that done.

if (condition)
    if (condition)
        ...
    else if (condition)
        ...
    else
        doA
else 
    doA

The code above simply says this:

if true then (if true (...) else if true (...) else doA) else doA.. so it's like i want main if's else to run in some situations that come inside main if.

Upvotes: 0

Views: 97

Answers (2)

C Nimmanant
C Nimmanant

Reputation: 7

Maybe this...

var a = <condition a>,
    b = <condition b>,
    c = <condition c>,
    doDoA = true;

if (a) {
    if (b) {
        doB;
        doDoA = false;
    } else if (c) {
        doC;
        doDoA = false;
    }
}

if (doDoA) {
    doA
}

Upvotes: 0

Sam Jacobs
Sam Jacobs

Reputation: 346

if (conditionA)
    if (conditionB)
        ...
    else if (conditionC)
        ...
    else
        doA
else 
    doA

can be

if (conditionA && condition B)

else if (conditionA && conditionC)

else 
    doA

Upvotes: 2

Related Questions