Module: Comparing Values Using Conditional Statements

What This Challenge Will Help You With:

  • Using if, else if, and else statements
  • Comparing values using comparison operators (>, <, ===)
  • Practicing logical thinking with conditionals

Helpful Tips if You Get Stuck:

  • Remember that > means "greater than" and < means "less than."
  • === is used to check if two values are exactly equal.
  • Each if statement evaluates a condition; if it's true, the corresponding block of code runs.
  • If none of the if or else if conditions are true, the else block runs.

Starter Code (Copy and Paste This):

1let johnAnimals = 10; 2let billyAnimals = 10;

Your Task:

Compare johnAnimals and billyAnimals using conditional statements. Your program should print:

  • "John has more animals than Billy." if John has more animals.
  • "Billy has more animals than John." if Billy has more animals.
  • "John and Billy have the same amount of animals." if they have an equal number of animals.

Solution Walkthrough


Solution with Explanation:

let johnAnimals = 10; let billyAnimals = 10; if (johnAnimals > billyAnimals) { console.log("John has more animals than Billy."); } else if (johnAnimals < billyAnimals) { console.log("Billy has more animals than John."); } else { console.log("John and Billy have the same amount of animals."); }

Breakdown:

  1. We declare two variables: johnAnimals and billyAnimals, and assign them numbers.
  2. We use an if statement to check if johnAnimals is greater than billyAnimals.
    • If true, we print: "John has more animals than Billy."
  3. If the first condition is false, we move to the else if statement to check if billyAnimals is greater than johnAnimals.
    • If true, we print: "Billy has more animals than John."
  4. If neither condition is true, we reach the else block and print: "John and Billy have the same amount of animals."

Refactored Code (Cleaner Version):

1let johnAnimals = 10; 2let billyAnimals = 10; 3 4const result = johnAnimals > billyAnimals 5 ? "John has more animals than Billy."\ : johnAnimals < billyAnimals 6 ? "Billy has more animals than John."\ : "John and Billy have the same amount of animals."; 7 8console.log(result);

Why Is This Better?

  • Uses a ternary operator for a more concise conditional check.
  • Stores the result in a variable called result and logs it once.
  • Reduces the number of console.log() calls and makes the code easier to read.