DEV Community

Karthick Narayanan
Karthick Narayanan

Posted on

JavaScript Programs Using If-Else

1) Shopping Discount System

A user gets a discount based on the purchase amount. Members get an extra discount.

let amount = 6000;
let isMember = true;
let discount = 0;

if (amount >= 5000) {
    discount = 0.20;
} else if (amount >= 2000) {
    discount = 0.10;
} else {
    discount = 0;
}

let finalPrice = amount - (amount * discount);

if (isMember) {
    finalPrice = finalPrice - (finalPrice * 0.10);
}

console.log("Final Price:", finalPrice);
Enter fullscreen mode Exit fullscreen mode

2) Login Access Check

Checks if user credentials are correct and not blocked.

let username = "admin";
let password = "1234";
let isBlocked = false;

if (isBlocked) {
    console.log("User is blocked");
} else if (username === "admin" && password === "1234") {
    console.log("Login successful");
} else {
    console.log("Invalid username or password");
}
Enter fullscreen mode Exit fullscreen mode

3) Traffic Signal System

Simple program to show actions based on signal color.

let color = "red";

if (color === "red") {
    console.log("Stop");
} else if (color === "yellow") {
    console.log("Get Ready");
} else if (color === "green") {
    console.log("Go");
} else {
    console.log("Invalid signal");
}
Enter fullscreen mode Exit fullscreen mode

4) ATM Withdrawal

Checks balance and withdrawal rules.

let balance = 5000;
let withdrawAmount = 2000;

if (withdrawAmount > balance) {
    console.log("Insufficient funds");
} else if (withdrawAmount <= 0) {
    console.log("Invalid amount");
} else {
    balance = balance - withdrawAmount;
    console.log("Remaining Balance:", balance);
}
Enter fullscreen mode Exit fullscreen mode

5) Mobile Data Usage

Checks if the user is nearing or exceeding the data limit.

let dataUsed = 8;
let limit = 10;

let usage = (dataUsed / limit) * 100;

if (usage >= 100) {
    console.log("Limit exceeded");
} else if (usage >= 80) {
    console.log("Warning: nearing limit");
} else {
    console.log("Usage normal");
}
Enter fullscreen mode Exit fullscreen mode

6) Electricity Bill Calculation

Calculates bill based on slab system.

let units = 350;
let bill = 0;

if (units <= 100) {
    bill = units * 5;
} else if (units <= 300) {
    bill = (100 * 5) + ((units - 100) * 7);
} else {
    bill = (100 * 5) + (200 * 7) + ((units - 300) * 10);
}

console.log("Total Bill:", bill);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)