If vs else if


#1

Is there a big difference if I decide to use if's instead of else if's when i define compare?

both of these answers work when i run it in the compiler

for example

option A

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else return "scissors wins";
}
if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";
}
else {
return "scissors wins";}
}
};

compare(userChoice, computerChoice)

option B

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else return "scissors wins";
}
else if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";
}
else {
return "scissors wins";}
}
};

compare(userChoice, computerChoice)

//I am trying to learn if there is a big benefit or reason to use 'else if's here when defining 'compare'?

thoughts?


#2

Here it is not because the return immediately exits the function so it is not possible to get another case as well but if you have a look at the first one:

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

here this counts as one conditional statement because only one case is chosen but e.g.

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

would be 3 independent conditions and it would be possible to choose more then just one as e.g 0.2 would fit for both "rock" and "paper".