How to Create a Popcorn Pricing System Using JavaScript Conditional Statements Practice QS

How to Create a Popcorn Pricing System Using JavaScript Conditional Statements   Practice QS

Building a Popcorn Pricing System with Conditional Statements in JavaScript

Imagine a popcorn stand where customers can order popcorn of different sizes. Each size has a specific price, and the system calculates the cost based on the size chosen by the customer. In this blog, we’ll create a simple JavaScript program to achieve this using conditional statements.


The Challenge

We need to design a system that calculates the price of popcorn based on the selected size. Here are the pricing rules:

  • Extra Large (XL): Rs. 250

  • Large (L): Rs. 200

  • Medium (M): Rs. 100

  • Small (S): Rs. 50

If an invalid size is selected, the system should either show a default price or an error message.


Using Conditional Statements

Code Implementation

Here’s how we can implement this in JavaScript:

// Uncomment the size variable as needed to test different cases
// let size = "XL";
let size = "L";
// let size = "M";
// let size = "S";

if (size === "XL") {
    console.log("Price is Rs.250");
} else if (size === "L") {
    console.log("Price is Rs.200");
} else if (size === "M") {
    console.log("Price is Rs.100");
} else if (size === "S") {
    console.log("Price is Rs.50");
} else {
    console.log("Invalid size selected.");
}

How It Works

  1. The variable size holds the customer’s choice of popcorn size.

  2. The if-else structure checks the value of size against predefined options: "XL", "L", "M", and "S".

  3. If a match is found, the corresponding price is displayed.

  4. If no match is found, the program falls back to the else block, which handles invalid inputs.


Output Examples

Case 1: Large (L) Size

let size = "L";

Output:

Price is Rs.200

Case 2: Medium (M) Size

let size = "M";

Output:

Price is Rs.100

Case 3: Small (S) Size

let size = "S";

Output:

Price is Rs.50

Case 4: Invalid Input

let size = "XXL";

Output:

Invalid size selected.

Enhancing the System

Adding a Default Price

To ensure the system always displays a price, even for invalid sizes, we can add a default option in the else block:

else {
    console.log("Price is Rs.50"); // Default price
}

This makes the system more user-friendly by providing a fallback option.

Case Sensitivity Handling

The program can be improved to handle case-insensitive input using the toUpperCase() method:

if (size.toUpperCase() === "XL") {
    console.log("Price is Rs.250");
}

Best Practices

  1. Input Validation: Ensure user input matches the expected values.

  2. Dynamic Pricing: Use a dictionary or object for scalable pricing management.

  3. Default Behavior: Always handle invalid or unexpected inputs gracefully.