(1)What is if Statement in JavaScript?
An if statement in JavaScript is a fundamental control structure that allows code to execute only if a specified condition evaluates to true. If the condition evaluates to false, the code inside the if block is not executed.
Syntax of if Statement
How to Use an if Statement
- Define a Condition – The condition inside the parentheses (
()) is evaluated. - Execute Code – If the condition is
true, the code block within the curly braces ({}) runs. - Skip if False – If the condition is
false, the code block is bypassed.
Example:
Output:
If age were less than 18, nothing would appear because the condition would not be satisfied.
Why Use if Statements?
- Decision Making –
ifstatements allow programs to make decisions based on user input, data, or other variables. - Control Flow – They help direct the flow of the program by executing certain parts of the code selectively.
- Validation – Useful for form validation, error checks, and ensuring specific conditions are met.
- Dynamic Behavior –
ifstatements enable responsive, interactive websites and applications by reacting to different scenarios.
When to Use if Statements?
- Conditional Execution – When a task should only run under specific circumstances.
- User Input – Check if a form is filled correctly or if a user is authorized.
- Calculations – Perform operations based on variable values.
- Form Validation – Verify data before submission.
- Error Handling – Prevent errors by running checks before executing certain logic.
Real-World Example:
Checking Even or Odd Numbers
Since 7 is not divisible by 2, nothing will print.
Example with else for Full Control
Output:
Nested if Statements
if statements can be nested to check multiple conditions.
Output:
Advantages of if Statements
- Simple and Easy to Implement – Basic conditional checks are easy to write.
- Readable – Clear and intuitive to understand for beginners.
- Flexible – Can handle a wide range of conditions and scenarios.
Common Mistakes to Avoid
- Omitting Braces – Always use
{}even for single-line statements to avoid errors.
- Assignment Instead of Comparison
Fix:
- Complex Conditions – Simplify with logical operators (
&&,||).
Key Takeaways
- The
ifstatement executes code conditionally based on whether a condition istrue. - It’s a core part of creating dynamic, interactive websites and applications.
- Use
ifstatements to validate, filter, and manage data dynamically.
(2)What is if-else Statement in JavaScript?
An if-else statement in JavaScript is a control structure that allows the program to execute one block of code if a condition is true, and a different block if the condition is false. This provides a way to handle two possible outcomes based on a condition.
Syntax of if-else Statement
How to Use an if-else Statement
- Condition Evaluation – The condition inside the if parentheses is checked.
- True Block – If the condition evaluates to true, the code inside the if block runs.
- False Block – If the condition is false, the code within the else block will execute.
Example:
Output:
If the temperature were 15, the output would be:
Why Use if-else Statements?
- Two-Path Decisions – When you need to execute different code based on a condition.
- User Interaction – Tailor responses according to user input.
- Validation – Handle form input or data validation by providing alternative logic.
- Error Handling – Manage errors or provide fallback options when conditions are not met.
When to Use if-else Statements?
- Binary Decisions – For situations with two possible outcomes (e.g., success or failure).
- Validation Checks – When verifying if a user meets a requirement or not.
- Simple Alternatives – To choose between two options based on variable values.
- Form Submission – Check if a form is filled correctly, and respond accordingly.
Real-World Example:
Checking Age for Voting Eligibility
Output:
Example: User Login System
Output:
Nested if-else Statements
You can place if-else statements inside each other to handle more complex conditions.
Output:
Benefits of if-else Statements
- Simple to Implement – Easy to understand and write.
- Efficient Control Flow – Helps make logical decisions and control program behavior.
- Dynamic Logic – Reacts to changing inputs or data conditions.
- Flexible – Can be nested or combined for complex scenarios.
Common Mistakes to Avoid
- Forgetting the
elseBlock – If noelseblock is written, nothing happens when the condition isfalse. - Assignment Instead of Comparison
Fix:
- Incorrect Bracket Usage
Fix:
Ternary Operator (Shorter Alternative to if-else)
For simple if-else logic, a ternary operator can be used to make the code more concise.
Best Practices for Using if-else
- Keep It Simple – Avoid overly complex if-else chains by breaking down logic into smaller functions.
- Readable Conditions – Use clear and simple conditions.
- Avoid Deep Nesting – Excessive nesting can make the code harder to read.
- Use Logical Operators – Combine conditions using && (AND) or || (OR) to reduce code repetition.
Key Takeaways
- The if-else statement lets you manage two possible outcomes, controlling the execution flow based on conditions.
- A fallback (
else) ensures alternative code runs if the primary condition fails. - Ternary operators provide a shorter alternative for simple
if-elselogic.
(3)What is an if-else if Statement in JavaScript?
An if-else if statement in JavaScript allows you to evaluate multiple conditions in sequence. It enables the program to execute different blocks of code depending on which condition is true.
- If the first condition is true, its block executes, and the rest are ignored.
- If the first condition is false, the next condition is checked.
- If none of the conditions are true, the
elseblock (if provided) will run.
Syntax of if-else if Statement
How to Use an if-else if Statement
- Start with
if– The first condition is checked. - Add
else if– Additional conditions are checked if the previous ones are false. - Optional
else– A final block runs if no conditions are met.
Example:
Output:
- If
scoreis85, the output is "Grade: B". - If
scoreis95, the output is "Grade: A".
Why Use if-else if Statements?
- Multiple Condition Checks – When more than two possible outcomes exist.
- Hierarchical Decisions – To prioritize conditions in a specific order.
- Validation and Control – Apply different actions depending on the user's input or data.
- Grading Systems, Pricing, or Permissions – Ideal for systems that require different outputs for different ranges.
When to Use if-else if Statements?
- Complex Logic – When handling more than two possible scenarios.
- Range Checks – Grading systems, pricing tiers, or age verifications.
- Form Validation – Check if fields meet multiple conditions (e.g., length, format).
- Role-Based Access – Provide different access levels for different users.
Real-World Example: Age-Based Ticket Pricing
Output:
Example: Light Control Based on Time
Output:
Benefits of if-else if Statements
- Readable – Clear structure that improves code readability.
- Efficient – Once a condition is met, no further conditions are checked.
- Flexible – Allows for an unlimited number of conditions.
- Organized Logic – Helps break down complex decision-making into simpler steps.
Common Mistakes to Avoid
- Skipping
else if– Withoutelse if, multipleifstatements could lead to unnecessary checks.
Fix: Use else if to avoid running multiple blocks.
- Condition Overlap – Make sure conditions don't overlap, or the first
truecondition will execute.
Even though number is 50, the output will be "Above 40" because the second condition won’t run.
Nested if-else if Statements
You can nest if-else if statements inside each other to handle more specific cases.
Output:
Ternary Alternative (Simple if-else if)
For simpler cases, a ternary operator can replace if-else if statements.
Best Practices for if-else if
- Avoid Deep Nesting – Use
switchstatements or separate functions if the logic becomes too complex. - Order Matters – Place the most specific conditions first and general ones later.
- Simplify with Functions – Extract repeated logic into functions to improve readability.
Key Takeaways
if-else ifallows multiple condition checks in sequence.- It ensures only one block of code executes based on the first true condition.
- Ideal for handling graded, tiered, or hierarchical conditions.
- Use it when more than two outcomes are possible.