JavaScript Conditional Statements
# JavaScript Conditional Statements
In real life, we make decisions every day based on conditions: "If it rains, I will take an umbrella; else, I will wear sunglasses." Programming is no different!
In this chapter, we will learn how to make our JavaScript code "think" and make decisions using conditional statements.
1. Introduction
Conditional statements are used to perform different actions based on different conditions. Without them, a program would just run top-to-bottom doing the exact same thing every time. With conditionals, your program can react dynamically to user input, data changes, and environment states.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Use the
ifstatement to execute code only when a condition is true.
-
Use the
elsestatement to provide an alternative path.
-
Chain multiple conditions using
else if.
-
Use the
switchstatement for testing a single variable against many values.
- Nest conditions inside other conditions.
- Build a working Grade Calculator mini-project.
3. The if Statement
The if statement is the most fundamental decision-making tool. It evaluates a condition (usually wrapped in parentheses). If that condition is true, the code block inside the curly braces {} runs. If it is false, the code block is entirely skipped.
4. The else Statement
What if the condition is false and you want something else to happen? You use the else statement. It catches everything that fails the if test.
5. The else if Statement
When you have more than two possible outcomes, you use else if. It allows you to chain multiple tests together. The first one that evaluates to true will execute, and the rest will be ignored.
---
6. Real-world Examples & Code Snippets
Example 1: Basic if Statement
Output Explanation: Because 15 is strictly less than 20, the console will print the warning.
Example 2: if...else Statement
Output Explanation: Because isUserLoggedIn is false, it skips the first block and executes the else block.
Example 3: else if Ladder
Output Explanation: 14 is not less than 12, so it checks the else if. 14 IS less than 18, so it prints "Good Afternoon!" and ignores the rest.
Example 4: Nested Conditions
You can place if statements inside other if statements. This is called nesting.
Output Explanation: First it checks if the user is online (True). Then it goes inside and checks if they have credits (False). It executes the inner else block.
Example 5: Using Logical Operators with if
Instead of nesting, we can often use Logical AND (&&) to combine conditions.
Example 6: The switch Statement
When you need to test a single variable against many specific values, switch is much cleaner than writing ten else if statements.
Output Explanation: Checks dayOfWeek. It matches case 3, assigns "Wednesday" to the variable, hits break, and exits the switch statement.
Example 7: The Importance of break in Switch
If you forget the break keyword, the code will "fall through" and execute the remaining cases even if they don't match!
Output Explanation: It will print BOTH prices. Apples are $1.00 AND Bananas are $0.50. This is a very common bug!
Example 8: Checking for Data Types
Remember that inputs from HTML are strings.
Output Explanation: The strict equality (===) fails because "10" (string) is not 10 (number). It hits the else if and succeeds.
Example 9: Truthy and Falsy Values
In JavaScript, you don't always have to use ==. Some values are naturally evaluated as false when put inside an if() statement. These are called Falsy values: 0, "" (empty string), null, undefined, NaN, and false. Everything else is Truthy.
Example 10: Early Return Pattern (Advanced Best Practice)
Instead of huge nested if/else blocks inside functions, developers often return early to keep code clean.
---
7. Common Mistakes for Beginners
-
1.
Using
=instead of===:if (x = 10)assigns 10 to x. It does NOT check if x equals 10. Always use===.
-
2.
Forgetting curly braces
{}: While technically JavaScript allows single-lineifstatements without braces, it is a terrible habit that leads to bugs when you try to add a second line of code later.
-
3.
Forgetting
breakin aswitchstatement: As shown in Example 7, this causes logic to bleed into places it shouldn't.
8. Best Practices
-
Always use curly braces
{}even for single-line if-statements to maintain readability.
-
If you have more than 4
else ifconditions checking the exact same variable against specific values, switch to aswitchstatement.
-
Keep nesting to a minimum. If you have an
ifinside anifinside anif, try combining them with&&to make the code cleaner.
9. Mini Project: Grade Calculator
Let's build an app where a teacher types in a numerical score, and the JavaScript logic calculates their letter grade.
HTML:
grades.js:
10. Exercises
-
1.
Write an
ifstatement that checks if a variabletemperatureis strictly greater than 30. If it is, console log "It's hot outside".
-
2.
Write an
if...elseblock that checks if a variableisWeekendis true. If true, print "Relax", otherwise print "Go to work".
-
3.
Convert the following logic to a
switchstatement: Ifstatusis "success", print "Green". If "error", print "Red". If "warning", print "Yellow".
11. MCQs (Multiple Choice Questions)
Q1: Which of the following is considered a "Falsy" value in JavaScript?
A) "false" (string)
B) 1
C) 0
D) [] (empty array)
*Answer: C (0 is mathematically falsy. "false" as a string is truthy!)*
Q2: What keyword is used to stop a switch statement from bleeding into the next case?
A) stop
B) exit
C) return
D) break
*Answer: D*
Q3: If x = 5, what will if (x = 10) evaluate to?
A) true
B) false
C) error
*Answer: A (Because assigning a truthy value like 10 evaluates to true. This is why you must use ===)*
12. Interview Questions
Q: Can you explain the concept of Truthy and Falsy values?
*A: In JavaScript, every value has an inherent boolean state. Falsy values evaluate to false when placed in a boolean context (like an if statement). The only falsy values are false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, and NaN. Everything else is truthy.*
Q: When should you use a switch statement instead of if...else?
*A: A switch statement is best used when you are testing a single expression or variable against multiple distinct, specific, constant values. It makes the code more readable and can sometimes be slightly more performant than a long chain of else if statements.*
13. FAQs
Q: Do I have to write else after an if?
*A: No. You can write an if statement entirely on its own. If the condition is false, the program simply moves on to the next line of code below the if block.*
14. Summary
-
ifevaluates a condition.
-
elseprovides a fallback if the condition is false.
-
else ifallows you to chain multiple checks.
-
switchis great for checking one variable against many specific values.
-
Remember to use
breakinsideswitchcases!
- Input validation (checking if the user's data makes sense) is a crucial part of conditional logic.