JavaScript Real-World Practice Questions with solutions

Introductions

Real-world JavaScript practice helps you understand how JavaScript is used in websites and everyday applications. These examples combine variables, arrays, objects, functions, conditions, loops, DOM, events, and practical problem-solving. JavaScript Real-World practice questions with solutions help to understand the concepts.

The questions in this chapter are designed to feel like small tasks you may actually build while working on a website or frontend project.


Question 1: Calculate a Shopping Cart Total

Problem

A customer buys three products. Calculate the total price of all products.

Solution

const products = [
    {
        name: "Keyboard",
        price: 1200
    },
    {
        name: "Mouse",
        price: 800
    },
    {
        name: "Headphones",
        price: 1500
    }
];

let total = 0;

for (const product of products) {
    total += product.price;
}

console.log("Cart Total:", total);

Output

Cart Total: 3500

Step-by-step Explanation

The products are stored inside an array of objects.

Each product has:

name
price

The total starts at:

let total = 0;

Then the loop adds every product’s price:

total += product.price;

The calculation becomes:

1200 + 800 + 1500 = 3500

So the final cart total is:

3500

Question 2: Apply a Discount to a Product

Problem

A product costs ₹2,000. Give the customer a 10% discount and calculate the final price.

Solution

const price = 2000;
const discountPercentage = 10;

const discountAmount =
    price * discountPercentage / 100;

const finalPrice =
    price - discountAmount;

console.log("Discount:", discountAmount);
console.log("Final Price:", finalPrice);

Output

Discount: 200
Final Price: 1800

Step-by-step Explanation

First calculate the discount:

2000 × 10 / 100 = 200

Then subtract it from the original price:

2000 - 200 = 1800

This type of calculation is commonly used in:

  • E-commerce websites
  • Shopping carts
  • Coupon systems
  • Billing applications

Question 3: Create a Login Validation

Problem

Check whether the entered username and password match the correct login details.

Solution

const correctUsername = "admin";
const correctPassword = "12345";

const username = "admin";
const password = "12345";

if (
    username === correctUsername &&
    password === correctPassword
) {
    console.log("Login successful");
} else {
    console.log("Invalid username or password");
}

Output

Login successful

Step-by-step Explanation

The program stores the correct credentials:

const correctUsername = "admin";
const correctPassword = "12345";

Then it compares the entered values.

Both conditions must be true:

username === correctUsername &&
password === correctPassword

If both match:

Login successful

Otherwise:

Invalid username or password

In a real application, passwords should not be stored or checked this way in frontend JavaScript. Authentication should be handled securely on the server.


Question 4: Find Products That Are in Stock

Problem

You have a list of products. Display only the products whose stock is greater than zero.

Solution

const products = [
    {
        name: "Laptop",
        stock: 5
    },
    {
        name: "Keyboard",
        stock: 0
    },
    {
        name: "Mouse",
        stock: 10
    },
    {
        name: "Monitor",
        stock: 0
    }
];

const availableProducts = products.filter(
    function(product) {
        return product.stock > 0;
    }
);

console.log(availableProducts);

Output

[
    { name: "Laptop", stock: 5 },
    { name: "Mouse", stock: 10 }
]

Step-by-step Explanation

filter() creates a new array containing only items that satisfy a condition.

The condition is:

product.stock > 0

Therefore:

Laptop → 5 → Available
Keyboard → 0 → Not available
Mouse → 10 → Available
Monitor → 0 → Not available

This type of logic is commonly used in product listing pages.


Question 5: Create a Temperature Converter

Problem

Convert a temperature from Celsius to Fahrenheit.

Solution

const celsius = 30;

const fahrenheit =
    (celsius * 9 / 5) + 32;

console.log(
    celsius + "°C = " +
    fahrenheit + "°F"
);

Output

30°C = 86°F

Step-by-step Explanation

The formula is:

Fahrenheit = (Celsius × 9/5) + 32

For 30°C:

(30 × 9/5) + 32
= 54 + 32
= 86°F

Temperature converters are a simple example of how JavaScript can process user input and produce useful results.


Question 6: Create an Employee Salary Calculator

Problem

An employee has a basic salary of ₹30,000. Calculate the salary after adding a 20% bonus.

Solution

const salary = 30000;
const bonusPercentage = 20;

const bonus =
    salary * bonusPercentage / 100;

const finalSalary =
    salary + bonus;

console.log("Bonus:", bonus);
console.log("Final Salary:", finalSalary);

Output

Bonus: 6000
Final Salary: 36000

Step-by-step Explanation

Calculate the bonus:

30000 × 20 / 100 = 6000

Add the bonus:

30000 + 6000 = 36000

The same pattern can be used for:

  • Salary calculators
  • Commission calculators
  • Tax calculations
  • Invoice systems
  • Pricing tools

Question 7: Build a Searchable Employee List

Problem

Create an employee list and search for employees by name.

Solution

const employees = [
    "Rahul",
    "Priya",
    "Aman",
    "Neha",
    "Rohit"
];

const searchText = "ra";

const results = employees.filter(
    function(employee) {
        return employee
            .toLowerCase()
            .includes(searchText.toLowerCase());
    }
);

console.log(results);

Output

["Rahul"]

Step-by-step Explanation

The filter() method checks every employee.

The name is converted to lowercase:

employee.toLowerCase()

The search text is also converted to lowercase:

searchText.toLowerCase()

Then:

includes()

checks whether the employee name contains the search text.

This makes the search case-insensitive.

For example:

RA
ra
Ra
rA

can all match "Rahul".


Question 8: Create an Expense Tracker Calculation

Problem

You have several expenses. Calculate the total amount spent and find the highest expense.

Solution

const expenses = [
    {
        name: "Food",
        amount: 500
    },
    {
        name: "Travel",
        amount: 1200
    },
    {
        name: "Shopping",
        amount: 2500
    },
    {
        name: "Books",
        amount: 800
    }
];

let total = 0;
let highestExpense = expenses[0];

for (const expense of expenses) {

    total += expense.amount;

    if (expense.amount > highestExpense.amount) {
        highestExpense = expense;
    }

}

console.log("Total Expense:", total);

console.log(
    "Highest Expense:",
    highestExpense.name,
    highestExpense.amount
);

Output

Total Expense: 5000
Highest Expense: Shopping 2500

Step-by-step Explanation

First, total expense starts at:

let total = 0;

Every expense is added:

total += expense.amount;

At the same time, the program compares each expense with the current highest expense:

if (expense.amount > highestExpense.amount)

The largest expense is:

Shopping → ₹2500

This combines looping, objects, comparison, and calculation.


Question 9: Generate a Student Result

Problem

Calculate a student’s total marks, percentage, and result.

The student has marks in five subjects.

Solution

const marks = [80, 75, 90, 85, 70];

let total = 0;

for (const mark of marks) {
    total += mark;
}

const percentage =
    total / marks.length;

let result;

if (percentage >= 40) {
    result = "Pass";
} else {
    result = "Fail";
}

console.log("Total Marks:", total);
console.log("Percentage:", percentage + "%");
console.log("Result:", result);

Output

Total Marks: 400
Percentage: 80%
Result: Pass

Step-by-step Explanation

The marks are:

80 + 75 + 90 + 85 + 70

Total:

400

There are five subjects:

400 / 5 = 80

Therefore:

Percentage = 80%

Because the percentage is greater than 40:

Result = Pass

This logic can be expanded into a complete student result system.


Question 10: Build a Simple Shopping Cart with Quantity

Problem

Create a shopping cart where each product has a price and quantity. Calculate the final cart total.

Solution

const cart = [
    {
        name: "Keyboard",
        price: 1200,
        quantity: 2
    },
    {
        name: "Mouse",
        price: 800,
        quantity: 1
    },
    {
        name: "Headphones",
        price: 1500,
        quantity: 2
    }
];

let total = 0;

for (const product of cart) {

    const itemTotal =
        product.price * product.quantity;

    total += itemTotal;

    console.log(
        product.name + ": ₹" + itemTotal
    );
}

console.log("Final Cart Total: ₹" + total);

Output

Keyboard: ₹2400
Mouse: ₹800
Headphones: ₹3000
Final Cart Total: ₹6200

Step-by-step Explanation

For each product, calculate:

Price × Quantity

Keyboard:

1200 × 2 = 2400

Mouse:

800 × 1 = 800

Headphones:

1500 × 2 = 3000

Now add everything:

2400 + 800 + 3000 = 6200

So:

Final Cart Total = ₹6200

This is closer to the type of logic used in real shopping applications.

Key Takeaways

  • Real-world JavaScript combines multiple concepts together.
  • Arrays are useful for storing lists of products, employees, expenses, and marks.
  • Objects are useful for representing individual records.
  • filter() is useful for creating filtered lists.
  • Loops are useful for calculations involving multiple records.
  • Conditions help applications make decisions.
  • Functions can make repeated business logic reusable.
  • JavaScript can calculate prices, discounts, salaries, marks, and expenses.
  • Search functionality commonly uses filter() and includes().
  • Shopping carts usually combine price and quantity.
  • Real applications often require several JavaScript concepts working together.
  • Always test your program with different inputs.
  • Think about edge cases such as empty arrays, zero prices, missing values, and invalid input.
  • Real-world coding is less about complicated syntax and more about correctly solving a business problem.

FAQs

1. What are real-world JavaScript practice questions?

Real-world JavaScript questions simulate tasks found in actual websites and applications.

Examples include:

  • Shopping carts
  • Expense trackers
  • Search systems
  • Student result systems
  • Salary calculators
  • Product filters
  • Temperature converters

2. Why are real-world JavaScript projects important?

They help you understand how individual JavaScript concepts work together.

For example, a shopping cart can use:

Arrays
Objects
Loops
Functions
Conditions
DOM
Events

Learning these concepts together prepares you for actual frontend development.

3. What JavaScript concepts should I know for real-world projects?

You should gradually become comfortable with:

  • Variables
  • Conditions
  • Loops
  • Functions
  • Arrays
  • Objects
  • Array methods
  • DOM
  • Events
  • JSON
  • Promises
  • Fetch API
  • Local storage

You don’t need to master all of them before building your first project.

4. How do I turn a JavaScript problem into code?

Use this simple process:

Understand the requirement
        ↓
Identify the input
        ↓
Identify the expected output
        ↓
Break the problem into steps
        ↓
Write the JavaScript
        ↓
Test different inputs

This approach makes larger problems easier to solve.

5. What is business logic in JavaScript?

Business logic is the set of rules that determines how an application should behave.

For example, an online store might have:

Product price
+
Quantity
-
Discount
+
Tax
=
Final amount

JavaScript can implement these rules in the application.

6. How can I practice real-world JavaScript?

Start with small applications and gradually make them more advanced.

A good progression is:

Calculator
→
Counter
→
To-Do List
→
Quiz
→
Expense Tracker
→
Shopping Cart
→
Weather App
→
Product Filter

After completing a project, add one or two new features yourself.

7. Should I build JavaScript projects without looking at solutions?

Yes, whenever possible.

First try solving the problem yourself. If you get stuck, look at the solution and understand why it works instead of simply copying it.

Then close the solution and rebuild the project from memory.

This develops much stronger programming skills.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top