Nikki Mehta
Nikki Mehta

Reputation: 19

confusion: basic If else

if (condition) {
    // Yes
} else {
    // No
}

we can also write

if (condition) {
        // No
    } else {
        // Yes
    }

OR is there any rule that we can only execute "true" in IF and False in ELSE ?

Upvotes: 0

Views: 48

Answers (4)

Diogo
Diogo

Reputation: 171

Both ways can be done, there's no rule for that, as the if statement check any logical condition that you specify. Example(like yours but just to imagine better) in node.js:

var x = 10;

if (x == 10) {
    console.log("Yes");
} else {
    console.log("No");
}

That will print "Yes", but we can make it print a "No" by only changing the logical operator:

var x = 10;

if (x != 10) {
    console.log("Yes");
} else {
    console.log("No");
}

The if statement will check if the condition is true, but it don't need to only be a true return in the if, as it is this way, we can adapt it better to our needs and sometimes we will not even need the else in our code, so just use it for your needs keeping a good code readability.

Talking about readability, there's a good topic about how it should be arranged, and radarbob's answer is something that i use as a good pattern:

Order by their likelihood of being executed. The most common, most likely, etc. condition(s) should go first.

The "difficulty of dealing with them" should be dealt with by code structure, abstraction, etc. in the example the else block could be refactored to single method call. You want your if clauses to be at the same abstract level.

if ( ! LotteryWinner ) {
    GoToWorkMonday();
} else {
    PlanYearLongVacation();
}

Upvotes: 0

Matt F.
Matt F.

Reputation: 31

No, there's no rule, and it doesn't matter how you check for values. You could easily replace the !true to check the value of a variable. Say, variable x being a user response. So, if (!x), then the user didn't respond, so theelse statement will execute.

// if a condition is false
if (!true) {
  // ...
}
// else, it's true
else {
  // ...
}

Upvotes: 1

Krishnadas PC
Krishnadas PC

Reputation: 6519

If condition will be executed if the condition returns boolean true. It's upto the developer to decide what needs to be done. For example age= 18

If(age>= 18){
//allowed to drive
} else {
// not allowed to drive
}

Even if you change the condition like this

If(age< 18){
    //not allowed to drive
    } else {
    // allowed to drive
    }

Both leads to the same result.

Upvotes: 0

filipbarak
filipbarak

Reputation: 1905

You can execute whatever you want in whichever block you want.

Meaning you can write:

if (condition) {
   // don't do something
} else {
  // do something.
}

Example:

   if (userHasAccess) {
    // do something
} else {
    // deny him entry
}

or

   if (!userHasAccess) {
    // deny him entry
} else {
   // do something
}

Upvotes: 0

Related Questions