Nested conditional statements


#1

Should the conditional statements really be nested? Doesn't seem like the ideal way to code this.


#2

yes, this is common in programming, nested conditionals are fine.
for a visual representation, look below.

each of those are yes/no conditionals, each of those would be considered nested, if translated into code.


#3

It is a good question. thingsofyourmind's answer with the flowchart is good description of where you use nested ifs. It shows well how control flow direction is changed to execute code on a dependent condition. Which is what nesting is for.

However in the rock paper scissors example of this, it is actually substituting for '&&' - 'And' where it is testing if two conditions are true. In this example then it is one way of doing it. If execution speed is very similar, then making code easy to read is also really important and if you want to connect conditions together that have to be passed to make a true statement, then using the syntax which most clearly shows it is a consideration.

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";
}

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

console.log("User",userChoice, "Computer", computerChoice);
console.log(compare(userChoice, computerChoice));

The code above replaces the nested ifs with conditions connected with 'And', and does the same thing but you will see it requires extra tests to cover the choices being the other way around. This is where coding choices and style of programming become important. If you had 3 players to compare, And / Or usage would get even more complicated, you could end up with a lot to test to cover all situations.

You will be learning about 'Case' statements and doing more practice on control flow. It is a good question to always ask is this the most efficient way to write this code. Generally the target is everything you must test, in the simplest to understand way. The hard bit when coding, which leaves space for bugs and security flaws is knowing you've covered all the possible choices or conditions users might do with the program.