Learning Goals
At the end of this Tutorial, you will be able to:
- Create decision-making structures in JavaScript with if, else if and else code blocks.
Download a new workfile on your computer as described at the link below.
Decision-making with if
In JavaScript, as in other programming languages, the if keyword is at the basis of most decision-making. The code structure is as follows:
if (condition is true) {
// code to execute if condition is true;
}
Note the following:
- The statement begins with the keyword if – not IF or If or iF.
- The condition tested is enclosed within parenthesis ( ).
- When the condition is true, the code to be run is enclosed inside a pair of curly braces { }.
The if
statement in action
Consider the following example that tests the value in the variable named 'temperature'. If the value in the variable exceeds a certain amount, the condition is satisfied and the script shows an alert box. The right angle bracket (>) is the JavaScript greater than operator.
Copy the following code to your making-decisions.html workfile.
// Testing the value of a variable
let tempValue = 21;
if (tempValue > 15) {
console.log(`Temperature is greater than 15 degrees.`);
}
Comparison operators
You use a comparison operator to make some kind of comparison between two values. Here are the main ones.
Comparison Operators |
Description |
== |
Tests if the two values are the same. |
!= |
Tests if the two values are not the same. |
> |
Tests if the first value is greater than the second. |
>= |
Tests if the first value is greater than or equal to the second. |
< |
Tests if the first value is less than the second. |
<= |
Tests if the first value is less than or equal to the second. |
Let's try another example. Copy this code to your making-decisions.html workfile.
// Testing a number in range 1-100
let userNumber = 25;
if (userNumber < 50 ) {
console.log("The tested number is less than 50.");
}
Handling multiple conditions with else if
It is good practice to provide user feedback in all situations.
One way to do this is to combine an if command with the else if command in a single JavaScript code block. You can then evaluate more than two possible outcomes.
Update the code in your workfile as follows.
// Testing a number in range 1-100
let userNumber = 25;
if (userNumber < 50 ) {
console.log("The tested number is less than 50.");
}
else if (userNumber > 50 ) {
console.log("The tested number is greater than 50.");
}
Save and run the updated code. Update the userNumber value to 75 and view the result.
Here is the basic decision-making structure of an if clause combined with an else if clause.
if (first condition true) { // perform first instruction; } else if (second condition true) { // perform second other instruction; }
The all-purpose else
command
If you have ever organised physical items in a room or workplace you probably ended up with a drawer or shelf called 'miscellaneous' or 'other stuff'.
Similarly, there are many programming situations where no amount of if and else if statements is enough to cope with every possible value.
The solution is to use the else command. This is JavaScript’s way of handling values that fall in the category of ‘other’ or ‘miscellaneous’.
Update the code in your workfile as follows.
// Testing a number in range 1-100
let userNumber = 50;
if (userNumber < 50 ) {
console.log("The tested number is less than 50.");
}
else if (userNumber > 50 ) {
console.log("The tested number is greater than 50.");
}
else {
console.log("The tested number is exactly 50.");
}
Verify your new code can deal with various numbers in the range 1-100.
The general form of the if, if else and else decision-making structure is as follows.
if (first condition true) { // perform first instruction; } else if (second condition true) { // perform second other instruction; } else { // perform some other instruction; }
Linking conditions with logical operators
There are times when one condition is not enough. You can join multiple conditions together to form a single statement using the so-called logical operators.
The following code tests both temperature and humidity with the AND (&&) operator.
// Testing with the logical AND operator
let temperature_1 = 21;
let humidity_1 = 61;
if ( (temperature_1 > 20) && (humidity_1 > 60) ) {
console.log("Temperature and humidity conditions are met");
}
The logical AND (&&) operator is found in user login forms, where the user needs to enter the correct email address and correct password.
The following code uses the AND (&&) and the OR (||) operators and is satisfied when:
- The two AND time conditions are true.
- Either the isWeekend conition OR the isHoliday condition is false.
// Testing with both logical operators
let time = 14; // 2 PM
let isWeekend = true;
let isHoliday = false;
if (time >= 9 && time <= 17) { // Between 9 AM and 5 PM
if (isWeekend || isHoliday) {
console.log("It's business hours but we're closed for weekend/holiday");
} else {
console.log("We're open for business!");
}
} else {
console.log("Sorry, we're closed!");
}
Copy each of the above two code examples into your making-decisions.html workfile verify they run correctly.
The following table describes the two logical operators.
Logical Operators |
Description |
&& |
The AND operator. Joins multiple conditions in such a way that the output is true only if all the individual conditions are true. |
|| |
The OR operator. Joins multiple conditions in such a way that the output is true if any one (or more or all) of the individual conditions is true. |
Improving your user-entered number testing code
Update your code for testing numbers in the range 1-100 as shown below.
// Testing a number in range 1-100
let userNumber = 250;
if ( (userNumber < 1 ) || (userNumber > 100 ) ) {
console.log("The tested number is not within the allowed 1-100 range.");
}
else if (userNumber < 50 ) {
console.log("The tested number is between 0 and 50.");
}
else if (userNumber > 50 ) {
console.log("The tested number is between 50 and 100.");
}
else {
console.log("The tested number is exactly 50.");
}
Save your workfile and test your new code by entering various numbers inside the 1-100 range and also greater than 100.
Try it yourself
In your workfile...
---
Write a script that checks a temperature number value and displays different messages in the console:
- If temperature is above 30, display "Heat warning!"
- If temperature is between 25-30, display "Warm weather"
- If temperature is between 15-24, display "Pleasant weather"
- If temperature is below 15, display "Cool weather"
Include comments explaining your logic.
---
Create a script with two string variables, username and password. Use the AND (&&) operator to check if:
- The username is "student123" AND
- The password is "webdev2024"
In the console, display "Access granted" if both conditions are met, otherwise display "Access denied"
Include comments explaining your logic.
More learning resources
Tutorial Quiz
Tutorial Podcast
Sample AI prompts
I'm learning about if statements in JavaScript. Can you provide examples showing how each of these comparison operators works: <, >, <=, >=, ==, and !=? Include examples with numbers that help me understand when each operator would return true or false.
Can you explain explain how an if...else if...else
structure works in JavaScript. Provide an example where a user's score is checked to assign a grade (A, B, C, or F), and describe how each part of the structure contributes to the decision-making process.
Describe a scenario where you would use both the && (AND) and || (OR) logical operators in a single conditional statement. Provide a code example and explain how the conditions are evaluated.
Could you help me understand when to use else if
versus else
in JavaScript? Here's my code that tests a number between 1-100:
let num = 75;
if (num < 50) {
console.log("Less than 50");
}
else if (num > 50) {
console.log("Greater than 50");
}