Using JavaScript Logic Statements to Make Decisions in Your Code
This article will explore how logic statements empower your code to respond flexibly when provided with different inputs.
Join the DZone community and get the full member experience.
Join For FreeIn this excerpt, we will be dealing with logic statements. Logic statements allow us to make multiple paths in our code. Depending on the outcome of a certain expression, we will follow one code path or another.
We will look at if and if-else statements before testing your learning with a project.
if and if-else Statements
We can make decisions in our code using if and if-else statements. It is very much like this template:
if *some condition is true*, then *a certain action will happen*, else *another action will happen*
For example, if it is raining, I will take my umbrella, or else I will leave my umbrella at home. It is not that much different in code:
let rain = true;
if(rain){
console.log("** Taking my umbrella when I need to go outside **");
} else {
console.log("** I can leave my umbrella at home **");
}
In this case, the value of rain is true. And therefore, it will log to the console:
** Taking my umbrella when I need to go outside **
But let’s first take a step back and look at the syntax. We start with the word “if.” After this, we get something within parentheses. Whatever is between these parentheses will be translated to a Boolean. If the value of this Boolean is true, it will execute the block of code associated with if. You can recognize this block by the curly braces.
The next block is optional; it is an else block. It starts with the word “else” and is only executed in case of the Boolean having the value false. If there is no else block and the condition evaluates to false, the program will just skip ahead to the code underneath the if.
Only one of these two blocks will be executed; the if block when the expression is true, and the else block when the expression is false:
if(expression) {
// code associated with the if block
// will only be executed if the expression is true
} else {
// code associated with the else block
// we don't need an else block, it is optional
// this code will only be executed if the expression is false
}
Here is another example. If the age is below 18, log to the console that access is denied; otherwise, log to the console that the person is allowed to come in:
if(age < 18) {
console.log("We're very sorry, but you can't get in under 18");
} else {
console.log("Welcome!");
}
There is a common coding mistake related to if statements, which has been made in the following code snippet. Can you see what this code does?
let hobby = "dancing";
if(hobby = "coding"){
console.log("** I love coding too! **");
} else {
console.log("** Can you teach me that? **");
}
It will log the following:
** I love coding too! **
That might surprise you. The problem here is the single equal sign in the if statement. Instead of evaluating the condition, it is assigning coding to a hobby. And then, it is converting “coding” to a Boolean, and since it is not an empty string, it will become true, so the if block will be executed. So, always remember to use the double equal sign in this case.
else-if Statements
A variation of the if statement is an if statement with multiple else-if blocks. This can be more efficient in certain situations because you are always only going to execute one or zero blocks. If you have many if-else statements underneath one another, they are going to be evaluated and possibly executed even though one of the ones above already had a condition evaluated to true and proceeded to execute the associated code block.
Here is the written template:
If *a value falls into a certain category*, then *a certain action will happen*, else if *the value falls into a different category to the previous statement*, then *a certain action will happen*, else if *the value falls into a different category to either of the previous brackets*, then *a certain action will happen*
For example, take this statement to determine what the ticket price should be. If a person is younger than three, then access is free; else if a person is older than 3 and younger than 12, then access is 5 dollars else if a person is older than 12 and younger than 65, then access is 10 dollars, else if a person is 65 or older, then access is 7 dollars:
let age = 10;
let cost = 0;
let message;
if (age < 3) {
cost = 0;
message = "Access is free under three.";
} else if (age >= 3 && age < 12) {
cost = 5;
message ="With the child discount, the fee is 5 dollars";
} else if (age >= 12 && age < 65) {
cost = 10;
message ="A regular ticket costs 10 dollars.";
} else {
cost = 7;
message ="A ticket is 7 dollars.";
}
console.log(message);
console.log("Your Total cost "+cost);
Chances are that you will think the code is easier to read than the written template. In that case, nicely done! You are really starting to think like a JavaScript developer already.
The code gets executed top to bottom, and only one of the blocks will be executed. As soon as a true expression is encountered, the other ones will be ignored. This is why we can also write our sample like this:
if(age < 3){
console.log("Access is free under three.");
} else if(age < 12) {
console.log("With the child discount, the fee is 5 dollars");
} else if(age < 65) {
console.log("A regular ticket costs 10 dollars.");
} else if(age >= 65) {
console.log("A ticket is 7 dollars.");
}
Rock, Paper, Scissors Game
This is a game between a player and the computer, where both will make a random selection of either Rock, Paper, or Scissors (you could create a more involved version using real player input, but we are just aiming to test the use of logic statements here). Rock will beat out scissors, Paper will beat out Rock, and Scissors will beat out Paper. You can use JavaScript to create your own version of this game, applying the logic with an if statement. Since this project is a little more difficult, here are some suggested steps:
- Create an array that contains the variables Rock, Paper, and Scissors.
- Set up a variable that generates a random number 0-2 for the player and then do the same for the computer’s selection. The number represents the index values in the array of the 3 items.
- Create a variable to hold a response message to the user. This can show the random results for the player and then also the result for the computer of the matching item from the array.
- Create a condition to handle the player and computer selections. If both are the same, this results in a tie.
- Use conditions to apply the game logic and return the correct results. There are several ways to do this with the condition statements, but you could check which player’s index value is bigger and assign the victory accordingly, with the exception of rock beating scissors.
- Add a new output message that shows the player selection versus the computer selection and the result of the game.
Answers
As follows is the code to complete the preceding task—you can copy this into your development environment, or simply into your browser’s console window!
const myArr = ["Rock", "Paper", "Scissors"];
let computer = Math.floor(Math.random() * 3);
let player = Math.floor(Math.random() * 3);
let message = "player " + myArr[player] + " vs computer " + myArr[computer] + " ";
if (player === computer) {
message += "it's a tie";
} else if (player > computer) {
if (computer == 0 && player == 2) {
message += "Computer Wins";
} else {
message += "Player Wins";
}
} else {
if (computer == 2 && player == 0) {
message += "Player Wins";
} else {
message += "Computer Wins";
}
}
console.log(message);
Now, let’s wrap things up. In this excerpt, we have covered conditional statements. We focused on if and else statements. Whenever the condition associated with the if is true, the if block gets executed. If the condition is false and there is an else block present, that will be executed. We then looked at a practical exercise to put this logic to the test.
Published at DZone with permission of Laurence Svekis. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments