MJ Hdesigner
MJ Hdesigner

Reputation: 77

Basic JavaScript if vs. else if

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);

Upvotes: 6

Views: 8642

Answers (3)

Aegis
Aegis

Reputation: 1789

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!

Upvotes: 0

Kevin Nielsen
Kevin Nielsen

Reputation: 4433

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.

Upvotes: 6

Seano666
Seano666

Reputation: 2238

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.

Upvotes: 2

Related Questions