Conditional Statements
Learn how to make decisions in your code using conditional statements like if, else if, switch, and the ternary operator in JavaScript.
What is a Conditional Statement?Link to this section
A conditional statement is a programming structure that performs different actions depending on whether a given condition evaluates to true or false. It allows your program to make decisions and follow different paths based on different inputs or states.
This basic check prints Pass because the score is greater than 50.
- `if` is the **keyword** that starts the condition
- `(score >= 50)` is the **condition** that checks if the score is 50 or higher
- `{ ... }` is the **code block** that runs only if the condition is true
- `console.log("Pass");` is the **action** executed when the condition passes
Conditional statements are used everywhere decisions are needed, such as validating user inputs, checking permissions, or calculating discounts.
Why Do We Need Conditional Statements?Link to this section
Without conditional statements, programs would run every line of code in a straight, inflexible line from top to bottom.
- Check user login status to show the dashboard or the login page
- Calculate shipping fees based on total order price
- Display a pass or fail grade depending on exam marks
- Apply a promotional discount if a coupon code is valid
- Show a dark mode or light mode theme based on user settings
- Verify if an entered age is old enough to purchase an item
- Enable or disable a submit button based on form validation
Checks if the account balance is enough to buy the item.
The code evaluates whether the user has enough money and prints the appropriate message to avoid overdrafts.
About Conditional StatementsLink to this section
Conditional statements rely heavily on boolean values, comparison operators, and logical operators. They can be structured as simple single-branch checks, multi-way branches, or compact inline expressions. Understanding how to group and sequence them correctly ensures your program handles every possible scenario.
| Statement Type | Best Used For | Example Keyword |
|---|---|---|
| if | Single condition check | if |
| if...else | Binary choice (either/or) | else |
| else if | Multiple mutually exclusive choices | else if |
| switch | Comparing one value against many exact options | switch |
| Ternary | Short inline assignments based on a condition | ? : |
Combining conditions using logical operators.
Types of Conditional StatementsLink to this section
1. The If StatementLink to this section
The if statement runs a block of code only when its specified condition evaluates to true. If the condition is false, the code block is skipped entirely.
Executes the message because 30 is greater than 25.
Practical example of checking membership status.
tip
warning
2. The If...Else StatementLink to this section
The if...else statement provides an alternative block of code to run when the primary if condition evaluates to false. It ensures that one of two code paths always executes.
Prints Good afternoon because 14 is not less than 12.
Practical age verification check.
note
3. The Else If StatementLink to this section
The else if statement allows you to chain multiple conditions together, checking them sequentially until one evaluates to true. Once a matching branch is found, its code runs and the rest of the chain is skipped.
Checks multiple grade thresholds in order.
Practical traffic light state handler.
tip
4. Nested If StatementsLink to this section
A nested if statement is an if statement placed inside another if or else block. It allows you to check a secondary condition only after the primary condition has already been met.
Checks ID only if the user already has a ticket.
warning
5. The Switch StatementLink to this section
The switch statement evaluates an expression and compares its value against multiple case clauses. It is cleaner and more readable than a long chain of else if statements when checking a single variable against many exact values.
Matches day 3 to Wednesday.
warning
6. The Ternary OperatorLink to this section
The ternary operator is a shorthand conditional operator that takes three operands: a condition followed by a question mark, an expression to execute if true, a colon, and an expression to execute if false.
Assigns Adult to status because the age condition is true.
Practical example of setting a greeting message.
tip
7. Logical Operators in ConditionsLink to this section
You can combine multiple conditions inside a single if statement using logical operators like AND, OR, and NOT to create complex decision criteria.
Requires both age to be 18 or older and hasLicense to be true.
note
Truthy and Falsy Values in ConditionsLink to this section
In JavaScript conditional statements, any value can be evaluated as true or false. Values that evaluate to false are called falsy, while all other values are truthy.
| Value Type | Example | Evaluates To |
|---|---|---|
| Boolean | false | Falsy |
| Number | 0 | Falsy |
| String | "Hello" | Truthy |
| Null | null | Falsy |
Non-empty string evaluates to truthy.
note
Complete Coding ExampleLink to this section
Calculates shipping fees based on cart total and membership status.
This program combines nested if statements, boolean checks, and arithmetic calculations to determine the final order total.
Important NotesLink to this section
- Conditional statements control the flow of execution in JavaScript.
- An if statement runs its block only when the condition is true.
- The else block acts as a fallback when all preceding conditions fail.
- Use else if to evaluate multiple exclusive conditions in sequence.
- Nested if statements place conditions inside other condition blocks.
- Switch statements provide a clean way to match a variable against multiple exact values.
- Always include break statements in switch cases to prevent fall-through.
- The ternary operator is a concise shorthand for simple if...else assignments.
- Logical operators like && and || allow combining multiple checks in one condition.
- JavaScript treats non-boolean values as truthy or falsy in conditional checks.
SummaryLink to this section
Conditional statements are essential building blocks that give your programs decision-making capabilities. By mastering if statements, switch cases, and ternary operators, you can build dynamic logic that responds intelligently to user inputs and data states. This sets the foundation for controlling loops and building complex algorithms.
Check Your UnderstandingLink to this section
Which keyword is used to specify a fallback block when an if condition fails?
Practice ChallengesLink to this section
1. Grade Checker
Write a program with a variable score = 82. Use an if...else if ladder to print 'A' if score is 90 or above, 'B' if 80 or above, 'C' if 70 or above, and 'F' otherwise.
Expected output
BHint: Check conditions from highest score threshold to lowest.
2. Even or Odd
Create a variable number = 7. Use an if...else statement and the modulo operator (%) to check if the number is even or odd, and print the result.
Expected output
OddHint: A number is even if number % 2 === 0.
3. Movie Ticket Pricing
Create a variable age = 15. Write a ternary operator that assigns a ticket price of 8 if age is under 18, and 15 otherwise. Print the price.
Expected output
8Hint: Use condition ? 8 : 15
4. Day of the Week
Create a variable dayNumber = 2. Use a switch statement to print 'Weekend' if dayNumber is 6 or 7, 'Weekday' if it is between 1 and 5, and 'Invalid' otherwise.
Expected output
WeekdayHint: You can stack multiple case statements without breaks to share the same code block.
5. Access Control System
Create variables age = 20 and hasID = true. Use nested if statements to print 'Access Granted' only if age is 18 or older AND hasID is true. Otherwise print specific denial reasons.
Expected output
Access GrantedHint: Check the outer condition for age first, then the inner condition for hasID.
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion