IT Beginner Series: JavaScript IF/ELSE Exercises (2)

Andrei Diaconu
5 min readAug 29, 2023

--

More in the IT Beginner Series

As you embark on your journey to learn programming, understanding conditional statements is a fundamental step. These statements allow you to create decision-making structures in your code, directing its flow based on specific conditions. In this IT Beginner Series, we’ll delve into the world of JavaScript if/else statements – a cornerstone of programming logic – and provide you with a set of 10 simple exercises to grasp their usage effectively.

Introduction

In the realm of programming, control flow is essential. You need the ability to dictate which code should run under certain circumstances. This is where conditional statements come into play. JavaScript offers the if/else statement as a powerful tool to achieve precisely that. This statement empowers your code to make choices based on conditions, allowing you to execute specific blocks of code depending on whether those conditions are met.

Syntax

Before diving into our exercises, let’s familiarise ourselves with the syntax of the JavaScript if/else statement:

if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

The condition is a logical expression that evaluates to either true or false. If the condition is true, the code within the first block executes. If the condition is false, the code within the else block (if present) is executed.

Exercises

Now, let’s jump into the exercises to gain hands-on experience with if/else statements. We'll provide a scenario, the code solution, and the expected output for each exercise.

Exercise list

  1. Write a program that determines whether a given number is positive or negative.
  2. Write a program that checks if a number is even or odd.
  3. Write a program to determine the greater of two numbers.
  4. Write a program that transforms a numerical grade to a letter grade (e.g grade 10 should display “A”).
  5. Write a program that calculates the ticket price based on age with the following conditions: age below 12 pay a ticket price of 5, age below 18 pay a ticket price of 10, age below 60 pay a ticket price of 20, age over 60 play a ticket price of 15.
  6. Write a program that determines if a year is a leap year.
  7. Write a program that calculates a discount based on the purchase amount.Prices equal or over 100 discount have a discount of 20. Prices equal or over 50 have a discount of 10. Otherwise discount is 0
  8. Write a program that greets the user based on the time of day. Display good morning, good afternnon or good evening based on the time of day when you run the code.
  9. Write a program that calculates the Body Mass Index (BMI) and categorizes it. The formula for BMI is: weight / (height * height).
  10. Write a simple number guessing game. Provide a secret number and a guess. Based on those numbers give players clues if their guess is higher, lower or correct.

Exercise solutions — spoiler alert, solutions below

Exercise #1 — Determine If a Number Is Positive

Scenario: Write a program that determines whether a given number is positive or not.

Solution:

var number = 5;

if (number > 0) {
console.log("The number is positive.");
} else {
console.log("The number is not positive.");
}

Output:

The number is positive.

Exercise #2 — Check Even or Odd

Scenario: Write a program that checks if a number is even or odd.

Solution:

var number = 7;
if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}

Output:

The number is odd.

Exercise #3 — Determine the Greater Number

Scenario: Write a program to determine the greater of two numbers.

Solution:

var num1 = 10;
var num2 = 15;

if (num1 > num2) {
console.log("num1 is greater.");
} else {
console.log("num2 is greater.");
}

Output:

num2 is greater.

Exercise #4 — Grade Calculator

Scenario: Write a program that assigns a letter grade based on a numerical grade.

Solution:

var score = 85;
var grade;

if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
console.log("Grade: " + grade);

Output:

Grade: B

Exercise #5 — Ticket Pricing

Scenario: Write a program that calculates the ticket price based on age.

Solution:

var age = 25;
var ticketPrice;

if (age < 12) {
ticketPrice = 5;
} else if (age >= 12 && age < 18) {
ticketPrice = 10;
} else if (age >= 18 && age < 60) {
ticketPrice = 20;
} else {
ticketPrice = 15; // Senior citizen discount
}
console.log("Ticket Price: $" + ticketPrice);

Output:

Ticket Price: $20

Exercise #6 — Determine Leap Year

Scenario: Write a program that determines if a year is a leap year.

Solution:

var year = 2024;

if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
console.log(year + " is a leap year.");
} else {
console.log(year + " is not a leap year.");
}

Output:

2024 is a leap year.

Exercise #7 — Shopping Discount

Scenario: Write a program that calculates a discount based on the purchase amount.

Solution:

var purchaseAmount = 120;
var discount;

if (purchaseAmount >= 100) {
discount = 20;
} else if (purchaseAmount >= 50) {
discount = 10;
} else {
discount = 0;
}
console.log("Discount: " + discount + "%");

Output:

Discount: 20%

Exercise #8 — Time of Day Greeting

Scenario: Write a program that greets the user based on the time of day.

Solution:

var currentTime = new Date();
var currentHour = currentTime.getHours();
var greeting;

if (currentHour < 12) {
greeting = "Good morning!";
} else if (currentHour < 18) {
greeting = "Good afternoon!";
} else {
greeting = "Good evening!";
}
console.log(greeting);

Output (depending on the time of day you execute the code):

Good afternoon!

Exercise #9 — BMI Calculator

Scenario: Write a program that calculates the Body Mass Index (BMI) and categorizes it.

Solution:

var weight = 70; // in kilograms
var height = 1.75; // in meters
var bmi = weight / (height * height);
var category;

if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 24.9) {
category = "Normal weight";
} else if (bmi < 29.9) {
category = "Overweight";
} else {
category = "Obese";
}
console.log("BMI: " + bmi.toFixed(2)); // .toFixed(2) limits the number of decimals to 2
console.log("Category: " + category);

Output:

BMI: 22.86
Category: Normal weight

Exercise #10 — Number Guessing Game

Scenario: Write a simple number guessing game.

Solution:

var secretNumber = 7;
var guess = 5; // The player's guess, change this to see that different code lines are executed based on the conditions
if (guess === secretNumber) {
console.log("Congratulations! You guessed the correct number.");
} else if (guess < secretNumber) {
console.log("Try a higher number.");
} else {
console.log("Try a lower number.");
}

Output (depending on the player’s guess):

Try a higher number.

Conclusion

Congratulations! You’ve completed the JavaScript if/else exercises in the IT Beginner Series. You've gained hands-on experience in using conditional statements to make decisions in your code. These exercises have provided you with a solid foundation for understanding how if/else statements work

Good luck,
Andrei

More in the IT Beginner Series

--

--

Andrei Diaconu

Software Engineer keen on automating stuff, learning new things, and sharing knowledge.