Conditionals

Master if, else, else if, and switch statements for decision making in JavaScript.

Present State

Conditionals are a core part of programming that allow you to make decisions based on certain conditions. In JavaScript, you can use if, else if, and else statements, as well as switch cases to control the flow of your program based on various expressions.

Code Example

This example demonstrates the use of conditional statements in JavaScript:

JavaScript Conditional Statements

let score = 85;

// if-else if-else
if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 75) {
  console.log("Grade: B");
} else if (score >= 60) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

// switch-case
let fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("Apples are red or green.");
    break;
  case "banana":
    console.log("Bananas are yellow.");
    break;
  case "orange":
    console.log("Oranges are orange.");
    break;
  default:
    console.log("Unknown fruit.");
}
          

This code demonstrates:

  • Using if, else if, and else to check multiple conditions.
  • Using switch to select among multiple values of a single variable.

Description

Conditional statements allow a program to perform different actions based on different conditions:
  • if: Executes a block of code if a specified condition is true.
  • else if: Specifies a new condition if the previous one is false.
  • else: Executes if none of the previous conditions are true.
  • switch: Tests a variable against a list of values, executing corresponding code blocks.
Using these constructs, developers can create complex decision trees in their applications.

Applications

  • User Input Handling: Respond to different user inputs with appropriate actions.
  • Form Validation: Check for valid data formats and requirements.
  • Game Logic: Determine actions based on player state or game conditions.
  • Feature Toggles: Enable or disable features based on flags or permissions.

Multiple Choice Questions

Q1: What will be the output of: if (0) { console.log("True"); } else { console.log("False"); }

  • A. True
  • B. False
  • C. Error
  • D. Undefined

Answer: B. False

Q2: Which keyword is used to check multiple possible values of a variable?

  • A. if
  • B. else
  • C. switch
  • D. case

Answer: C. switch

Q3: In a switch statement, what happens if you forget the break statement?

  • A. Only the matching case runs
  • B. The default case always runs
  • C. Execution falls through to the next case
  • D. It throws an error

Answer: C. Execution falls through to the next case

Q4: Which is the correct structure of an if-else statement?

  • A. if { condition } else { }
  • B. if (condition) { } else { }
  • C. if condition: then else
  • D. if then else

Answer: B. if (condition) { } else { }