Skip to the content.

Fall 2024 - P4

CSP Period 4 Unit 3.6.4 Conditionals in JavaScript Hacks

In this lesson, students will practice using if-else statements in JavaScript through interactive exercises. They will work on solving problems that require making decisions in their code based on different conditions. The exercises will cover how to use if, else if, and else statements to handle multiple outcomes. Students will also practice combining conditions with logical operators like && (and), || (or), and ! (not). By the end of the lesson, students will have improved their ability to write programs that respond dynamically based on different scenarios.

Hack 1: Check Voting Eligibility

Description: This hack checks if a person is eligible to vote based on their age.

  1. Define a function named checkVotingEligibility that takes one parameter called age.
  2. Inside the function, use an if statement to check if the age is 18 or older.
    • Return the message "You are eligible to vote!" if true; otherwise, return "You are not eligible to vote yet.".

Call the function with different age values to test your work

Hack 2: Grade Calculator

Description: This hack assigns a letter grade based on a numerical score.

  1. Define a function named getGrade that takes one parameter called score.
  2. Use if...else if...else statements to determine the letter grade based on the score:
    • Return "Grade: A" for scores 90 and above.
    • Return "Grade: B" for scores between 80 and 89.
    • Return "Grade: C" for scores between 70 and 79.
    • Return "Grade: F" for scores below 70.

Call the function with different scores to test your work.

Hack 3: Temperature Converter

Description: This hack converts temperatures between Celsius and Fahrenheit.

  1. Define a function named convertTemperature that takes two parameters: value (the temperature) and scale (either “C” or “F”).
  2. Use an if statement to check the scale:
    • If it’s “C”, convert the temperature to Fahrenheit using the formula (value * 9/5) + 32 and return the result with "°F".
    • If it’s “F”, convert to Celsius using (value - 32) * 5/9 and return the result with "°C".
    • If the scale is neither, return an error message.

Test the function with different values and scales to check your work