javascript
exercises
exercises.js⚡javascript
/**
* =====================================================
* 4.1 IF/ELSE STATEMENTS - EXERCISES
* =====================================================
* Practice conditional logic
*/
/**
* Exercise 1: Age Category
*
* Return the age category based on the age:
* - "infant" for ages 0-1
* - "toddler" for ages 2-4
* - "child" for ages 5-12
* - "teenager" for ages 13-19
* - "adult" for ages 20-64
* - "senior" for ages 65+
*/
function getAgeCategory(age) {
// TODO: Implement using if-else if-else
}
// Test cases:
console.log('Exercise 1:');
console.log(getAgeCategory(0)); // "infant"
console.log(getAgeCategory(3)); // "toddler"
console.log(getAgeCategory(8)); // "child"
console.log(getAgeCategory(16)); // "teenager"
console.log(getAgeCategory(35)); // "adult"
console.log(getAgeCategory(70)); // "senior"
/**
* Exercise 2: Number Sign
*
* Return "positive", "negative", or "zero" based on the number.
*/
function getNumberSign(num) {
// TODO: Check if number is positive, negative, or zero
}
// Test cases:
console.log('\nExercise 2:');
console.log(getNumberSign(10)); // "positive"
console.log(getNumberSign(-5)); // "negative"
console.log(getNumberSign(0)); // "zero"
/**
* Exercise 3: Login Validation
*
* Check if a user can log in based on:
* - username must not be empty
* - password must be at least 8 characters
* - user must not be banned
*
* Return appropriate error message or "Login successful"
*/
function validateLogin(username, password, isBanned) {
// TODO: Validate each condition and return appropriate message
}
// Test cases:
console.log('\nExercise 3:');
console.log(validateLogin('john', 'password123', false)); // "Login successful"
console.log(validateLogin('', 'password123', false)); // "Username is required"
console.log(validateLogin('john', 'short', false)); // "Password must be at least 8 characters"
console.log(validateLogin('john', 'password123', true)); // "Account is banned"
/**
* Exercise 4: Ticket Price
*
* Calculate ticket price based on:
* - Base price: $12
* - Children (under 12): 50% off
* - Seniors (65+): 25% off
* - Students (with valid ID): 20% off
* - If it's Tuesday: additional $2 off final price
*/
function calculateTicketPrice(age, isStudent, isTuesday) {
// TODO: Calculate and return the ticket price
}
// Test cases:
console.log('\nExercise 4:');
console.log(calculateTicketPrice(25, false, false)); // 12
console.log(calculateTicketPrice(10, false, false)); // 6
console.log(calculateTicketPrice(70, false, false)); // 9
console.log(calculateTicketPrice(20, true, false)); // 9.6
console.log(calculateTicketPrice(25, false, true)); // 10
/**
* Exercise 5: Grade Calculator
*
* Convert percentage to letter grade:
* - A+: 97-100, A: 93-96, A-: 90-92
* - B+: 87-89, B: 83-86, B-: 80-82
* - C+: 77-79, C: 73-76, C-: 70-72
* - D+: 67-69, D: 63-66, D-: 60-62
* - F: below 60
*/
function getLetterGrade(percentage) {
// TODO: Return the letter grade
}
// Test cases:
console.log('\nExercise 5:');
console.log(getLetterGrade(98)); // "A+"
console.log(getLetterGrade(85)); // "B"
console.log(getLetterGrade(72)); // "C-"
console.log(getLetterGrade(68)); // "D+"
console.log(getLetterGrade(55)); // "F"
/**
* Exercise 6: Leap Year
*
* Determine if a year is a leap year:
* - Divisible by 4
* - BUT not divisible by 100
* - UNLESS also divisible by 400
*/
function isLeapYear(year) {
// TODO: Return true or false
}
// Test cases:
console.log('\nExercise 6:');
console.log(isLeapYear(2020)); // true
console.log(isLeapYear(2021)); // false
console.log(isLeapYear(2000)); // true (divisible by 400)
console.log(isLeapYear(1900)); // false (divisible by 100 but not 400)
/**
* Exercise 7: Triangle Type
*
* Determine the type of triangle based on side lengths:
* - "equilateral" - all sides equal
* - "isosceles" - exactly two sides equal
* - "scalene" - no sides equal
* - "invalid" - doesn't form a valid triangle
*
* Triangle inequality: sum of any two sides must be greater than the third
*/
function getTriangleType(a, b, c) {
// TODO: Validate and classify the triangle
}
// Test cases:
console.log('\nExercise 7:');
console.log(getTriangleType(5, 5, 5)); // "equilateral"
console.log(getTriangleType(5, 5, 3)); // "isosceles"
console.log(getTriangleType(3, 4, 5)); // "scalene"
console.log(getTriangleType(1, 2, 10)); // "invalid"
/**
* Exercise 8: FizzBuzz
*
* Classic FizzBuzz:
* - Return "FizzBuzz" if divisible by both 3 and 5
* - Return "Fizz" if divisible by 3 only
* - Return "Buzz" if divisible by 5 only
* - Return the number as string otherwise
*/
function fizzBuzz(num) {
// TODO: Implement FizzBuzz logic
}
// Test cases:
console.log('\nExercise 8:');
console.log(fizzBuzz(15)); // "FizzBuzz"
console.log(fizzBuzz(9)); // "Fizz"
console.log(fizzBuzz(10)); // "Buzz"
console.log(fizzBuzz(7)); // "7"
/**
* Exercise 9: BMI Calculator
*
* Calculate BMI and return the category:
* - BMI = weight (kg) / height² (m)
* - "Underweight" if BMI < 18.5
* - "Normal" if BMI 18.5-24.9
* - "Overweight" if BMI 25-29.9
* - "Obese" if BMI >= 30
*/
function getBMICategory(weight, height) {
// TODO: Calculate BMI and return category
}
// Test cases:
console.log('\nExercise 9:');
console.log(getBMICategory(50, 1.75)); // "Underweight"
console.log(getBMICategory(70, 1.75)); // "Normal"
console.log(getBMICategory(85, 1.75)); // "Overweight"
console.log(getBMICategory(110, 1.75)); // "Obese"
/**
* Exercise 10: Nested Conditions - User Access
*
* Determine access level based on user properties:
* - If user is null: "No user"
* - If user is banned: "Access denied - banned"
* - If user is not verified: "Please verify your email"
* - If user is admin: "Full access"
* - If user is premium: "Premium access"
* - Otherwise: "Basic access"
*/
function getUserAccess(user) {
// TODO: Check conditions using guard clauses
}
// Test cases:
console.log('\nExercise 10:');
console.log(getUserAccess(null)); // "No user"
console.log(getUserAccess({ banned: true })); // "Access denied - banned"
console.log(getUserAccess({ verified: false })); // "Please verify your email"
console.log(getUserAccess({ verified: true, role: 'admin' })); // "Full access"
console.log(getUserAccess({ verified: true, role: 'premium' })); // "Premium access"
console.log(getUserAccess({ verified: true, role: 'user' })); // "Basic access"
// =====================================================
// BONUS CHALLENGES
// =====================================================
/**
* Bonus 1: Rock Paper Scissors
*
* Determine the winner of rock-paper-scissors.
* Return "Player 1 wins", "Player 2 wins", or "Tie"
*/
function rockPaperScissors(player1, player2) {
// player1 and player2 are "rock", "paper", or "scissors"
// TODO: Determine the winner
}
console.log('\nBonus 1:');
console.log(rockPaperScissors('rock', 'scissors')); // "Player 1 wins"
console.log(rockPaperScissors('paper', 'rock')); // "Player 1 wins"
console.log(rockPaperScissors('scissors', 'rock')); // "Player 2 wins"
console.log(rockPaperScissors('rock', 'rock')); // "Tie"
/**
* Bonus 2: Password Strength
*
* Evaluate password strength:
* - "weak" - less than 8 characters
* - "medium" - 8+ chars with only letters OR only numbers
* - "strong" - 8+ chars with letters AND numbers
* - "very strong" - 8+ chars with letters, numbers, AND special chars
*/
function getPasswordStrength(password) {
// TODO: Evaluate and return password strength
}
console.log('\nBonus 2:');
console.log(getPasswordStrength('abc')); // "weak"
console.log(getPasswordStrength('abcdefgh')); // "medium"
console.log(getPasswordStrength('abc12345')); // "strong"
console.log(getPasswordStrength('Abc123!@#')); // "very strong"
// =====================================================
// SOLUTIONS (Uncomment to check your answers)
// =====================================================
/*
// Exercise 1 Solution:
function getAgeCategory(age) {
if (age <= 1) {
return "infant";
} else if (age <= 4) {
return "toddler";
} else if (age <= 12) {
return "child";
} else if (age <= 19) {
return "teenager";
} else if (age <= 64) {
return "adult";
} else {
return "senior";
}
}
// Exercise 2 Solution:
function getNumberSign(num) {
if (num > 0) {
return "positive";
} else if (num < 0) {
return "negative";
} else {
return "zero";
}
}
// Exercise 3 Solution:
function validateLogin(username, password, isBanned) {
if (!username) {
return "Username is required";
}
if (password.length < 8) {
return "Password must be at least 8 characters";
}
if (isBanned) {
return "Account is banned";
}
return "Login successful";
}
// Exercise 4 Solution:
function calculateTicketPrice(age, isStudent, isTuesday) {
let price = 12;
if (age < 12) {
price = price * 0.5; // 50% off
} else if (age >= 65) {
price = price * 0.75; // 25% off
} else if (isStudent) {
price = price * 0.8; // 20% off
}
if (isTuesday) {
price = price - 2;
}
return price;
}
// Exercise 5 Solution:
function getLetterGrade(percentage) {
if (percentage >= 97) return "A+";
if (percentage >= 93) return "A";
if (percentage >= 90) return "A-";
if (percentage >= 87) return "B+";
if (percentage >= 83) return "B";
if (percentage >= 80) return "B-";
if (percentage >= 77) return "C+";
if (percentage >= 73) return "C";
if (percentage >= 70) return "C-";
if (percentage >= 67) return "D+";
if (percentage >= 63) return "D";
if (percentage >= 60) return "D-";
return "F";
}
// Exercise 6 Solution:
function isLeapYear(year) {
if (year % 400 === 0) {
return true;
} else if (year % 100 === 0) {
return false;
} else if (year % 4 === 0) {
return true;
} else {
return false;
}
// Or: return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
// Exercise 7 Solution:
function getTriangleType(a, b, c) {
// Check triangle inequality
if (a + b <= c || b + c <= a || a + c <= b) {
return "invalid";
}
if (a === b && b === c) {
return "equilateral";
} else if (a === b || b === c || a === c) {
return "isosceles";
} else {
return "scalene";
}
}
// Exercise 8 Solution:
function fizzBuzz(num) {
if (num % 3 === 0 && num % 5 === 0) {
return "FizzBuzz";
} else if (num % 3 === 0) {
return "Fizz";
} else if (num % 5 === 0) {
return "Buzz";
} else {
return String(num);
}
}
// Exercise 9 Solution:
function getBMICategory(weight, height) {
const bmi = weight / (height * height);
if (bmi < 18.5) {
return "Underweight";
} else if (bmi < 25) {
return "Normal";
} else if (bmi < 30) {
return "Overweight";
} else {
return "Obese";
}
}
// Exercise 10 Solution:
function getUserAccess(user) {
if (!user) return "No user";
if (user.banned) return "Access denied - banned";
if (!user.verified) return "Please verify your email";
if (user.role === "admin") return "Full access";
if (user.role === "premium") return "Premium access";
return "Basic access";
}
// Bonus 1 Solution:
function rockPaperScissors(player1, player2) {
if (player1 === player2) {
return "Tie";
}
if (
(player1 === "rock" && player2 === "scissors") ||
(player1 === "paper" && player2 === "rock") ||
(player1 === "scissors" && player2 === "paper")
) {
return "Player 1 wins";
}
return "Player 2 wins";
}
// Bonus 2 Solution:
function getPasswordStrength(password) {
if (password.length < 8) {
return "weak";
}
const hasLetters = /[a-zA-Z]/.test(password);
const hasNumbers = /[0-9]/.test(password);
const hasSpecial = /[^a-zA-Z0-9]/.test(password);
if (hasLetters && hasNumbers && hasSpecial) {
return "very strong";
} else if (hasLetters && hasNumbers) {
return "strong";
} else {
return "medium";
}
}
*/