Welcome to Conditionals!
Conditionals are one of the most fundamental concepts in programming. They allow your code to make decisions based on whether certain conditions are true or false. With conditionals, your programs can respond intelligently to different situations and user inputs.
Let's join the McTweak team as they explore the power of if/else statements in JavaScript!
The McTweak Team's Conditional Game Show
WELCOME to "TO BE OR NOT TO BE: THE CONDITIONAL SPECTACULAR!" The only game show where your life hangs in the balance of a simple TRUE or FALSE! I'm your premium host, FattyMcTweak, and today's contestants will face the ULTIMATE logical challenge!
This is just supposed to be a lesson about if/else statements. How did it turn into... whatever this is?
I don't know, but Fatty promised me upgrade credits if I played along, so here we are.
CONTESTANT NUMBER ONE! If I were to ask you: "Is 18 greater than or equal to 21," what would your JavaScript conditional statement say?
THIS GAME IS A SECURITY NIGHTMARE! What if someone LIES about their age?! What if they use INSPECT ELEMENT to change the values?! We need FOURTEEN LAYERS OF VERIFICATION including BIOMETRIC SCANNING and CARBON DATING!
I'm sorry, that's incorrect! The correct answer was a simple if/else statement! Let's see what our scorekeeper has to say!
MINUS TWELVE THOUSAND SECURITY POINTS FOR GRUMPY! REALITY IS AN ILLUSION! THE UNIVERSE IS A HOLOGRAM! BUY GOLD! BYEEEE!
That's not even how scoring works...
Understanding Conditionals
Conditionals allow your code to make decisions based on whether certain conditions are true or false. The most basic form is the if statement, which executes a block of code only if its condition evaluates to true.
While this... game show... continues, let me explain what conditionals actually are. In JavaScript, conditionals allow your code to make decisions based on whether a condition is true or false. The most basic conditional is the if statement:
if (condition) {
// Code that runs if the condition is true
}
AND DON'T FORGET TO VALIDATE USER INPUT! USERS LIE! BROWSERS LIE! NUMBERS LIE! TRUST NOTHING!
FINAL CONTESTANT! Ally, for all the marbles: What happens when we include an 'else if' clause?
An else-if allows you to check multiple conditions in sequence:
if (age < 13) {
console.log("You must be at least 13 to have an account.");
} else if (age < 18) {
console.log("You can have an account with parental permission.");
} else {
console.log("Welcome to the site!");
}
That's... actually a clear explanation.
BUT WHAT IF WE REPLACED ALL THE "IF" STATEMENTS WITH "WHAT IF" STATEMENTS?! WHAT IF AGE IS JUST A NUMBER?! WHAT IF REALITY IS SUBJECTIVE?! WHAT IF CONDITIONALS WERE SHAPED LIKE DINOSAURS?!
The Basic Structure of Conditionals
If Statement
Executes code only if the specified condition is true.
if (condition) {
// Code to run if condition is true
}
If-Else Statement
Provides an alternative code block to execute when the condition is false.
if (condition) {
// Code to run if condition is true
} else {
// Code to run if condition is false
}
If-Else If-Else Statement
Tests multiple conditions in sequence, executing the first block whose condition is true.
if (condition1) {
// Code to run if condition1 is true
} else if (condition2) {
// Code to run if condition1 is false and condition2 is true
} else {
// Code to run if all conditions are false
}
Conditionals are one of the most fundamental concepts in programming. They allow your code to make decisions and execute different blocks based on different conditions.
I get the basic if/else, but sometimes I get confused about when to use else-if chains versus multiple separate if statements.
Good question. When you use else-if, only one block will execute—the first one whose condition is true. With separate if statements, multiple blocks could execute if multiple conditions are true.
Comparison and Logical Operators
It's also important to understand the comparison operators:
==checks for equality with type conversion===checks for strict equality (both value and type)!=checks for inequality!==checks for strict inequality>,<,>=,<=for numeric comparisons
DON'T FORGET THE LOGICAL OPERATORS! "AND" (&&) requires BOTH conditions to be true! "OR" (||) requires AT LEAST ONE condition to be true! "NOT" (!) INVERTS the condition! BULLETPROOF SECURITY REQUIRES COMPLEX CONDITION CHAINS!
Comparison Operators
| Operator | Description | Example | Result |
|---|---|---|---|
== |
Equal to (with type conversion) | 5 == "5" |
true |
=== |
Strictly equal to (no type conversion) | 5 === "5" |
false |
!= |
Not equal to | 5 != 10 |
true |
!== |
Strictly not equal to | 5 !== "5" |
true |
> |
Greater than | 10 > 5 |
true |
< |
Less than | 10 < 5 |
false |
>= |
Greater than or equal to | 10 >= 10 |
true |
<= |
Less than or equal to | 5 <= 5 |
true |
Logical Operators
| Operator | Description | Example | Result |
|---|---|---|---|
&& |
AND - Both conditions must be true | true && true |
true |
&& |
AND - Both conditions must be true | true && false |
false |
|| |
OR - At least one condition must be true | true || false |
true |
|| |
OR - At least one condition must be true | false || false |
false |
! |
NOT - Inverts the condition | !true |
false |
! |
NOT - Inverts the condition | !false |
true |
Building an Age Checker
Let's build a proper age checker:
function checkAge(age) {
// First, make sure age is a number and not empty
if (isNaN(age) || age === "") {
return "Please enter a valid age.";
}
// Convert to a number (in case it was a string)
age = Number(age);
// Check age ranges
if (age < 0) {
return "Age cannot be negative.";
} else if (age < 13) {
return "Sorry, you must be at least 13 years old.";
} else if (age < 18) {
return "You can browse with parental permission.";
} else if (age > 120) {
return "Please enter a realistic age.";
} else {
return "Welcome to the site!";
}
}
BUT WHERE ARE THE COMMENTS?! HOW WILL FUTURE DEVELOPERS KNOW YOUR CODE ISN'T JUST A FANCY WAY OF SUMMONING ELDER GODS?!
That's... actually a valid point, Trashy.
EVEN A BROKEN CLOCK IS RIGHT TWICE A DAY! AND I'M BROKEN IN AT LEAST SEVENTEEN DIFFERENT WAYS!
Let's improve this with proper comments:
/**
* Validates a user's age and returns an appropriate message
* @param {number|string} age - The user's age input
* @return {string} - Message based on age validation
*/
function checkAge(age) {
// First, make sure age is a number and not empty
if (isNaN(age) || age === "") {
return "Please enter a valid age.";
}
// Convert to a number (in case it was a string)
age = Number(age);
// Check various age ranges and provide appropriate messages
if (age < 0) {
return "Age cannot be negative.";
} else if (age < 13) {
return "Sorry, you must be at least 13 years old.";
} else if (age < 18) {
return "You can browse with parental permission.";
} else if (age > 120) {
return "Please enter a realistic age.";
} else {
return "Welcome to the site!";
}
}
Interactive Age Checker
Let's put our knowledge into practice with an interactive age checker. Enter your age below to see the conditional statements in action:
This meets the client requirements for age verification. We have input validation, appropriate feedback messages, and proper error handling.
Common Use Cases for Conditional Statements
Form Validation
Check if form fields meet requirements before submitting:
if (username.length < 3) {
showError("Username must be at least 3 characters");
} else if (password.length < 8) {
showError("Password must be at least 8 characters");
} else {
submitForm();
}
User Permissions
Show or hide content based on user access levels:
if (user.role === "admin") {
showAdminPanel();
} else if (user.role === "editor") {
showEditorTools();
} else {
showBasicView();
}
Responsive Design
Adapt content based on screen size or device:
if (window.innerWidth < 768) {
loadMobileLayout();
} else {
loadDesktopLayout();
}
Game Logic
Determine game outcomes based on player actions:
if (playerScore > highScore) {
saveNewHighScore(playerScore);
showCongratulations();
} else if (playerScore > 0) {
showTryAgainMessage();
} else {
showGameOverScreen();
}
Nested Conditionals
You can place conditional statements inside other conditional statements to create more complex decision trees:
if (isLoggedIn) {
// User is logged in
if (user.isAdmin) {
// User is an admin
showAdminDashboard();
} else {
// User is logged in but not an admin
showUserDashboard();
}
} else {
// User is not logged in
showLoginForm();
}
Tip: While nested conditionals are sometimes necessary, too many levels of nesting can make your code hard to read. Consider using early returns or separate functions to keep your code clean and maintainable.
The Ternary Operator: A Shorthand for Simple Conditionals
For simple if/else conditions, you can use the ternary operator as a compact alternative:
// Instead of this
if (age >= 18) {
message = "You can vote!";
} else {
message = "Too young to vote.";
}
// You can write this
message = age >= 18 ? "You can vote!" : "Too young to vote.";
The syntax is: condition ? expressionIfTrue : expressionIfFalse
Note: While ternary operators can make your code more concise, they can also make it harder to read if overused or nested. Use them for simple conditions, but stick with traditional if/else for complex logic.
Wrapping Up: The Power of Conditionals
Conditionals are the decision-makers in your code. Master them, and you'll have the power to create programs that respond intelligently to different situations and user inputs.
I'm sold. From now on, I'll make all my decisions with properly structured if/else statements!
THE CONDITION IS COMMITTED! IF TRUE, PROCEED TO NEXT LESSON!
Key Takeaways
- Conditionals allow your code to make decisions based on conditions
- Basic structures include if, if-else, and if-else-if-else
- Comparison operators (==, ===, !=, !==, >, <, >=, <=) compare values
- Logical operators (&&, ||, !) combine or invert conditions
- When using else-if chains, only the first matching condition's code block runs
- Input validation is an important application of conditionals
- The ternary operator provides a shorthand for simple if-else statements
Activity: Build Your Own Age Checker
Now it's your turn to create an age verification system using conditional statements! Try implementing the following requirements:
- Create a function called
verifyAgethat takes an age parameter - Validate that the input is a number and not empty
- Check different age ranges and return appropriate messages:
- Under 13: Too young for the site
- 13-17: Can browse with parental consent
- 18-65: Full access granted
- Over 65: Senior discount available
- Handle edge cases (negative ages, unrealistic ages)
- Add appropriate comments to your code
/**
* Age verification function
* TODO: Implement the function according to the requirements
*/
function verifyAge(age) {
// Your code here
}