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