DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. JavaScript
  4. Using JavaScript Logic Statements to Make Decisions in Your Code

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.

Laurence Svekis user avatar by
Laurence Svekis
·
Maaike van Putten user avatar by
Maaike van Putten
·
Jul. 18, 22 · Tutorial
Like (4)
Save
Tweet
Share
1.65K Views

Join the DZone community and get the full member experience.

Join For Free

In 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:

JavaScript
 
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:

JavaScript
 
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:

JavaScript
 
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?

JavaScript
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:

JavaScript
 
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:

JavaScript
 
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:

  1. Create an array that contains the variables Rock, Paper, and Scissors.
  2. 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.
  3. 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. 
  4. Create a condition to handle the player and computer selections. If both are the same, this results in a tie. 
  5. 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.
  6. 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!

JavaScript
 
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.

Computer JavaScript Blocks

Published at DZone with permission of Laurence Svekis. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Introduction to Automation Testing Strategies for Microservices
  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Secure APIs: Best Practices and Measures
  • 5 Software Developer Competencies: How To Recognize a Good Programmer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: