If’s, Else’s, and Pugs! Oh My!


Life is full of ifs…sounds like the beginning of a cheesy quote. However, I don’t see it that way. I am a developer so I know clearly that life is actually full of if’s and else’s.

Before getting to the nitty gritty, I’ll start with an example. Here is a question: Do you think pugs are the cutest dogs on the planet?

pug1


if (youranswer == "yes") {

return "You are awesome!";

}

else {

return "We can't be friends :(";

}

In the world of JavaScript, the if/else statement is an awesome tool we use to perform different actions based on different conditions. In a nutshell, if a certain condition is met, then the corresponding block of code is executed. If that first condition is not met, then it moves on to the next condition located in the else portion. In the last example, if you answered yes to my question, then I would say “You are awesome!”  If you said anything else like “maybe” or “no”, then unfortunately I would say “We can’t be friends :(”.

This is the basic if/else statement. You can potentially have more than two conditions by including an else if in between. I’ll add it to the previous example:


if (youranswer == "yes") {

    return "You are awesome!";

}

else if (youranswer == "maybe") {

    return "But they're so ugly they're cute!";

}

else {

    return "We can't be friends :(";

}

Now if you say “maybe”, I’ll tell you “But they’re so ugly they’re cute!” You can continue to add as many if/else statements as possible but keep in mind your first condition must start with an IF by itself and the last condition must end with an ELSE by itself.

pug2

As I stated earlier this is a powerful tool, especially for developing simple video games using only JavaScript. For example, we can make the all-time classic game of Rock Paper Scissors using if/else statements.


function RockPaperScissors(){

    var computerChoice = (Math.random() * 100);

    if (computerChoice < 33) {

        computerChoice = "rock";

    } else if (computerChoice <= 67) {

        computerChoice = "paper";

    } else {

        computerChoice = "scissors";

    }

    return computerChoice;

}

If you follow along, we make a computerChoice variable produce a random number between 0 – 100. Then we get into our if statement. If the random number is between 0-33, the computer chooses “rock”. Else if the number is between 34 and 67, then the computer chooses “paper”. And finally, if the random number is 68 – 100, then the computer will choose “scissors”.  Now all you need to do is call the RockPaperScissors function and you have yourself a worthy opponent to test your skills.

And in case you are wondering, that’s my 7-month old pug Thor. And he is as mighty as his name suggests!

Buy our games!

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.