6

My question is this: I'm new to JavaScript, I am trying to understand the difference between the " if { " and " else if { " statements. Thus far the only answers I have found are related to someone inheriting my code later, obviously no one is ever going to inherit my class project! My question specifically is this:

I am doing the rock paper scissor game project on codecademy. My Math.random() method produces a random number. I first implemented my code if (computerChoice <= 0.33){

and its alternative as:

if (computerChoice > 0.67){......    Which checked out and produced a viable answer. 

In its suggestion however it used the else if statement. My specific question is in either situation I essentially set a low range and a high range, leaving else to represent the middle. Else means not the previous condition. But if my condition for a second if already logically excludes the previous answer (which would have to be logically excluded in the else if alternative anyway) what exactly is the difference and why use else if/ when would else if be necessary?

My code follows:

Option one (else if):

var userChoice = prompt("do you want rock paper or scissors?");
var computerChoice = Math.random();

if (computerChoice <= 0.33){
  computerChoice = "rock";
}
else if (computerChoice >= 0.67){
 computerChoice = "scissors";
}
else {
 computerChoice = "paper";
}

console.log(computerChoice);

Option two (2 if's):

var userChoice = prompt("do you want rock paper or scissors?");
var computerChoice = Math.random();

if (computerChoice <= 0.33){
 computerChoice = "rock";
}
if (computerChoice >= 0.67){
 computerChoice = "scissors";
}
else {
 computerChoice = "paper";
}

console.log(computerChoice);
MJ Hdesigner
  • 77
  • 1
  • 4
  • Your second option will never produce "rock" – basilikum Aug 08 '13 at 22:09
  • That would be true if he were using a second value to hold the name of the selected entity -- but once he assigns a string value to computerChoice, all subsequent comparatives are going to return false. – Kevin Nielsen Aug 08 '13 at 22:19
  • @ basilikum - I don't understand, I tried both methods and both produced all three answers at random several times... – MJ Hdesigner Aug 08 '13 at 22:37
  • the two if statements are not connected. So with the first `if` statement you assign "rock" or don't assign "rock" - these are the two possibilities. In the second if-else block you either assign "scissors" or "paper", but it is definitly one of those. http://jsfiddle.net/N9bP9/ – basilikum Aug 09 '13 at 08:24
  • 1
    @KevinNielsen and if "all subsequent comparatives are going to return false" then the `else` block comes along and changes the value to "paper". – basilikum Aug 09 '13 at 08:26
  • Yep, @basilikum is right about that else block -- good call, sir. – Kevin Nielsen Aug 09 '13 at 18:25

3 Answers3

4

If-else if-else logic is more elegant than your second example because it will stop evaluating conditionals after the correct assignment has been made.

Consider how your second case (without else if) would work if computerChoice is 0.25. The first if condition would evaluate to true and computerChoice would be reassigned to "rock." Instead of considering itself done, however, the logic would then proceed, and check to see if computerChoice >= 0.67. Since computerChoice is now "rock," the interpreter will attempt to convert it to a numeric value. Since rock won't convert, my guess is your logic will, for now, work as intended.

However, consider a situation where you decide to define your entities -- rocks, paper, and scissors -- as an object, and to use the index of that object as the output of your processing. For instance:

var myentities = 
{
    1: { name: "rock", image_url: "..." },
    2: { name: "paper", image_url: "..." },
    3: { name: "scissors", image_url: "..." }
};

And suppose you also decide to stop using the name of the object, but instead to use its ID. In that case, your first if would assign the value of 1 to computerChoice -- and then the second if would check to see if 1 >= 0.67. As a result, your code would (quite innocently) pick paper 100% of the time, confounding you greatly for a short while.

Moral of the story: unnecessary evaluation will never help you and may hurt you.

Kevin Nielsen
  • 4,383
  • 19
  • 26
1

If you are checking for different conditions of the same variable (or something like that) then else if is faster. If it matches a condition, it executes and then you are done in the statement. A whole bunch of if statements means the code has to run through every one of those no matter if it finds the first one true or not. Be aware though, with 'else if' you must be only looking for one of the conditions to match. If you want it still to check anything after that, it will have to be another 'if' statement.

Seano666
  • 2,143
  • 1
  • 13
  • 14
  • So if I use else if to check an outcome it will stop asking if oce a condition is satisfied? So else if is only for when multiple outcomes are possible? – MJ Hdesigner Aug 08 '13 at 22:45
0

But if my condition for a second if already logically excludes the previous answer (which would have to be logically excluded in the else if alternative anyway) what exactly is the difference and why use else if/ when would else if be necessary?

=> None, however the else statement enforces it in case you made a mistake in your "logical exclusion".

Even if it's a bit outside the scope of your question it's also worth noting that there is no "else if" construct in JavaScript. When you write:

if (...) {

} else if (...) {

}

what you are basically doing is:

if (...) {

} else {
  if (...) {

  }
}

it works because you can either pass any statement after the else keyword. See http://www.ecma-international.org/ecma-262/5.1/#sec-12.5 :-)

Update 1

if (weight <= 130) {
  fighter = "lightweight";
} else if (weight >= 205) {
  fighter = "heavyweight";
} else {
  fighter = "middleweight";
}

which, in javascript, is equivalent to:

if (weight <= 130) {
  fighter = "lightweight";
} else {
  if (weight >= 205) {
    fighter = "heavyweight";
  } else {
    fighter = "middleweight";
  }
}

Update 2

In your original post, Option 2, you do:

if (computerChoice <= 0.33){
  computerChoice = "rock";
}

if (computerChoice >= 0.67){
 computerChoice = "scissors";
}
else {
  computerChoice = "paper";
}

If computerChoice is <= 0.33, what's going to happen is the following:

if (0.33 <= 0.33) ... // => computerChoice = "rock"

if ("rock" >= 0.67) ... else [THE ELSE PART IS EXECUTED!]

So basically computerChoice will be "paper" any time it should be "rock". You will have "paper" 67% of the time and "scissors" 33% of the time! This happens because Javascript doesn't throw an error when you try to compare values of different types (i.e. here a string, "rock", and a number "0.67"; instead it tries to convert the values in the same type by some magical coercion rules (http://webreflection.blogspot.be/2010/10/javascript-coercion-demystified.html) and then happily answer "false!". As a math major I could probably scare you by saying that due to those coercion rules you can prove, in javascript, that true = false...

PS: I just noticed Kevin Nielsen explained it above way better than I did. Here you go!

Aegis
  • 1,679
  • 11
  • 12
  • So is this to say: when condition 1 is not met, if option two... if option three.... In which case since condition one was already skipped, wouldn't it then evaluate more if statements anyway? In other words why isn't specifying else in this situation redundant as a second if statement being considered would already have excluded the rock string as a possible answer? What would be a situation to use else { if {} } then? only if I wasn't certain what the outcome of the first if would be? – MJ Hdesigner Aug 08 '13 at 22:43
  • I am not so sure about what you mean here? – Aegis Aug 08 '13 at 22:55
  • Thanks for bearing with me! Let me put it like this: If a fighter weighs more than or equal to 205 pounds he is a heavyweight. If he weighs less than or equal to 130 pounds he is a light weight. If he weighs anything else he is a middle weight. We can represent this mathematically as " heavy >= 205 " " 205 > middle > 130 " and " light <= 130 " Being that there are no secondary conditions. else if to me (thinking like a linear mathematics major) implies a second condition or alternator set of possibilities. There are however only three perfectly framed mathematical possibilities! – MJ Hdesigner Aug 08 '13 at 23:20
  • Ooops I didn't see the end of your comment. Well, instead of the last else statement you could do "else if (x > 130 && x < 205)"; mathematically it will include all values but be careful, javascript is dynamically typed so if, for some random reason, weight = "helloworld" (a string), then it won't pass any of the if statements and fighter will be "undefined". Got it? I can write some examples if you want to – Aegis Aug 08 '13 at 23:29
  • YES PLEASE!!! I guess what I need is an example where else if would satisfy a condition while if would not... THANK YOU SO MUCH!! – MJ Hdesigner Aug 09 '13 at 00:12