Conditionals, Logical Operators, and Object Basics
Workplace Context
As a developer, you will frequently encounter situations where your code needs to make decisions based on various conditions. For example, you may need to display different messages to users based on their input, or manage different behaviors depending on the state of an object.
Your supervisor has assigned you a task to build a simple object-oriented JavaScript game, but first, you must review some of the core concepts necessary to build it.
Learning Objectives
By the end of this lesson, you will be able to:
- Use conditional statements (
if
,else if
,else
) to control the flow of your program. - Apply logical operators (
&&
,||
) to evaluate multiple conditions. - Create and manipulate JavaScript objects to store data and methods.
Conditional Statements
Conditional statements allow you to execute code based on certain conditions. The most common conditional statement is the if
statement, which checks if a given condition is true
.
Basic if
Statement
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
In the example above, if age
is greater than or equal to 18, the message “You are eligible to vote” is logged.
if...else
Statement
The else
statement is used to execute a block of code when the if
condition is false.
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not old enough to vote.");
}
else if
Statement
You can chain multiple conditions using else if
.
let temperature = 25;
if (temperature > 30) {
console.log("It's too hot!");
} else if (temperature < 10) {
console.log("It's too cold!");
} else {
console.log("The weather is just right.");
}
switch
, break
, and continue
Statements
In addition to if...else
statements, JavaScript provides the switch
statement, which allows you to compare a value against multiple possible cases and execute different blocks of code depending on the result. Additionally, the break
and continue
statements are used to control the flow of loops and switch
cases.
switch
Statement
The switch
statement is a control structure that allows you to compare one value against multiple possible options (called cases). It is an alternative to using multiple if...else
statements, and can make your code more readable when you are working with many different conditions.
Syntax
switch (expression) {
case value1:
// code block to execute if expression === value1
break;
case value2:
// code block to execute if expression === value2
break;
// more cases
default:
// code block to execute if no cases match
}
The break
statement tells JavaScript to exit the switch
statement once a matching case has been found. If you do not include break
, the code will “fall through” and continue executing the next case, even if it does not match. This can be useful in very niche cases when used properly, but it can be confusing when used incorrectly.
Example: Using a switch
Statement to Respond to User Input
Let us say we are building a simple menu system for a program. The user can choose from several options, and the switch
statement will decide which action to take based on the user’s input.
let choice = prompt("Choose an option: 1. Start 2. Settings 3. Exit");
switch (choice) {
case '1':
console.log("Starting the game...");
break;
case '2':
console.log("Opening settings...");
break;
case '3':
console.log("Exiting the game...");
break;
default:
console.log("Invalid option, please try again.");
}
The switch
statement is like a multiple-choice question where you choose one answer, and based on the answer you select, the program runs a specific block of code. It is often much more readable than multiple if...else
statements.
Here is what the code above would look like if it used if...else
statements instead:
let choice = prompt("Choose an option: 1. Start 2. Settings 3. Exit");
if (choice === '1') {
console.log("Starting the game...");
} else if (choice === '2') {
console.log("Opening settings...");
} else if (choice === '3') {
console.log("Exiting the game...");
} else {
console.log("Invalid option, please try again.");
}
break
Statement
The break
statement is used to immediately exit a switch
statement or a loop. It prevents further execution of the loop or cases, which can be useful when you’ve found the answer or condition you’re looking for.
Example: Breaking Out of a Loop
In the following example, we use break
to exit a loop once we find a specific value in an array:
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) {
console.log("Found 3! Exiting the loop.");
break; // Exit the loop when 3 is found
}
console.log(numbers[i]);
}
In this example, the loop will stop once it finds the number 3, and no further numbers will be printed.
continue
Statement
The continue
statement skips the current iteration of a loop and continues with the next iteration. Unlike break
, it does not exit the loop entirely; it just skips over the current pass.
Example: Skipping Certain Values with continue
In the following example, we use continue
to skip over even numbers and only print odd numbers:
for (let i = 1; i <= 5; i++) {
if (i % 2 === 0) continue; // Skip even numbers
console.log(i); // Only odd numbers will be printed
}
In this example, the loop will skip over 2 and 4, and only print 1, 3, and 5.
Logical Operators
Logical operators allow you to combine multiple conditions.
AND Operator (&&
)
The &&
operator checks if both conditions are true
.
let isLoggedIn = true;
let isAdmin = true;
if (isLoggedIn && isAdmin) {
console.log("Welcome, admin.");
}
In this case, the message is only logged if both isLoggedIn
and isAdmin
are true.
OR Operator (||
)
The ||
operator checks if at least one condition is true
.
let hasMembership = false;
let hasCoupon = true;
if (hasMembership || hasCoupon) {
console.log("You are eligible for a discount.");
}
In this case, the message is logged if the user has either a membership or a coupon.
Introduction to Objects
An object is a data structure in JavaScript that allows you to store properties (key-value pairs) and methods (functions). Objects are essential for managing structured data in JavaScript applications.
Creating an Object
Here is an example of a simple object:
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function () {
console.log("Hello, my name is " + this.firstName + " " + this.lastName);
},
};
In this example:
firstName
,lastName
, andage
are properties of theperson
object.greet
is a method (a function defined inside an object).
Accessing Object Properties
You can access object properties using dot notation or bracket notation:
console.log(person.firstName); // Output: John
console.log(person["age"]); // Output: 30
Calling Object Methods
You can call object methods like this:
person.greet(); // Output: Hello, my name is John Doe
Hands-On: Build a Simple Decision-Based Game
In this activity, you will create a simple game that uses conditionals, logical operators, and objects. The game will simulate a user trying to guess a secret number.
Time: 60 minutes
Instructions:
Using the template provided below, build a simple game where:
- A random number between 1 and 10 is generated as the secret number.
- The player has 3 chances to guess the number.
- Each guess is compared to the secret number, and the game provides feedback (too high, too low, or correct).
- If the player exceeds the allowed number of guesses, the game ends.
Step 1: Define an Object to Store Game Data
Create an object called game
to store properties such as the secret number and the maximum number of guesses.
let game = {
secretNumber: Math.floor(Math.random() * 10) + 1,
maxGuesses: 3,
currentGuesses: 0,
};
Step 2: Write a Function to Handle User Guesses
Write a function called makeGuess
that takes a guess as a parameter, compares it to the secret number, and returns appropriate messages based on whether the guess is correct, too high, or too low.
function makeGuess(guess) {
game.currentGuesses++;
if (guess === game.secretNumber) {
return "Congratulations! You guessed the secret number.";
} else if (guess > game.secretNumber) {
return "Too high! Try again.";
} else {
return "Too low! Try again.";
}
}
Step 3: Add Logic to Track Guesses
Modify the makeGuess
function to check if the user has exceeded the maximum number of guesses and display a message when they do.
function makeGuess(guess) {
if (game.currentGuesses >= game.maxGuesses) {
return "No more guesses left! Game over.";
}
game.currentGuesses++;
if (guess === game.secretNumber) {
return "Congratulations! You guessed the secret number.";
} else if (guess > game.secretNumber) {
return "Too high! Try again.";
} else {
return "Too low! Try again.";
}
}
Step 4: Refactor
How might one turn the makeGuess
function into a method of the game
object? Do additional research if necessary, as is often the case in the workplace, and then complete this task.
Step 5: Create an Interface
Once your game has been completed, build a simple HTML interface to interact with the game, and hook the game’s information and methods into the interface. With any remaining time, style the game using CSS.
Knowledge Check
let person = { age: 30 };
Which of the following is the correct way to access the 'age' property in the object above?
- Select an answer to view feedback.
let isMember = true;
let hasDiscount = false;
if (isMember || hasDiscount) {
console.log("You are eligible for a discount.");
} else {
console.log("No discount available.");
}
What will the code above output?
- Select an answer to view feedback.
What is the purpose of the break
statement in a switch block?
- Select an answer to view feedback.
Summary
In this lesson, you reviewed how to use conditional statements and logical operators to make decisions in your code. You also explored the basics of JavaScript objects and applied these concepts by building a simple number-guessing game. Mastering conditionals and objects will help you write more dynamic and flexible code in JavaScript applications.