Browse JavaScript Fundamentals: A Beginner's Guide

JavaScript Expressions: Practical Examples and Real-Life Scenarios

Explore practical examples of JavaScript expressions with real-life scenarios like calculating discounts and interest rates. Learn to write and evaluate expressions effectively.

4.6.3 Practical Examples

Expressions in JavaScript are fundamental constructs that allow us to perform calculations, manipulate data, and make decisions based on conditions. In this section, we will delve into practical examples of writing and evaluating expressions, focusing on real-life scenarios such as calculating discounts, interest rates, and other common tasks. These examples will not only enhance your understanding of expressions but also demonstrate their application in solving everyday problems.

Understanding JavaScript Expressions

Before diving into examples, let’s briefly recap what expressions are. In JavaScript, an expression is a combination of values, variables, operators, and functions that are evaluated to produce a result. Expressions can be simple, like a single value or variable, or complex, involving multiple operators and function calls.

Practical Example 1: Calculating Discounts

One of the most common real-life scenarios where expressions are used is in calculating discounts. Let’s consider a scenario where we need to calculate the final price of a product after applying a discount.

Problem Statement

You are developing an e-commerce website, and you need to implement a feature that calculates the final price of a product after applying a discount. The discount is given as a percentage, and you need to ensure that the final price is rounded to two decimal places.

Solution

To solve this problem, we will use the following formula:

$$ \text{Final Price} = \text{Original Price} - (\text{Original Price} \times \frac{\text{Discount Percentage}}{100}) $$

Here’s how you can implement this in JavaScript:

function calculateDiscountedPrice(originalPrice, discountPercentage) {
    const discountAmount = originalPrice * (discountPercentage / 100);
    const finalPrice = originalPrice - discountAmount;
    return finalPrice.toFixed(2); // Round to two decimal places
}

// Example usage
const originalPrice = 100; // $100
const discountPercentage = 15; // 15% discount
const finalPrice = calculateDiscountedPrice(originalPrice, discountPercentage);
console.log(`The final price after discount is $${finalPrice}`);

Explanation

  • We define a function calculateDiscountedPrice that takes originalPrice and discountPercentage as parameters.
  • We calculate the discount amount by multiplying the original price by the discount percentage divided by 100.
  • We subtract the discount amount from the original price to get the final price.
  • We use the toFixed(2) method to round the final price to two decimal places.

Practical Example 2: Calculating Simple Interest

Another common scenario is calculating simple interest, which is often used in financial applications.

Problem Statement

You are building a financial application that requires calculating the simple interest on a loan. The formula for simple interest is:

$$ \text{Simple Interest} = \frac{\text{Principal} \times \text{Rate} \times \text{Time}}{100} $$

Where:

  • Principal is the initial amount of money borrowed or invested.
  • Rate is the annual interest rate (in percentage).
  • Time is the time period in years.

Solution

Here’s how you can implement this calculation in JavaScript:

function calculateSimpleInterest(principal, rate, time) {
    const simpleInterest = (principal * rate * time) / 100;
    return simpleInterest.toFixed(2); // Round to two decimal places
}

// Example usage
const principal = 1000; // $1000
const rate = 5; // 5% annual interest rate
const time = 3; // 3 years
const interest = calculateSimpleInterest(principal, rate, time);
console.log(`The simple interest is $${interest}`);

Explanation

  • We define a function calculateSimpleInterest that takes principal, rate, and time as parameters.
  • We use the formula for simple interest to calculate the interest amount.
  • We round the result to two decimal places using toFixed(2).

Practical Example 3: Evaluating Loan Eligibility

In this example, we’ll use expressions to evaluate whether a person is eligible for a loan based on their income and credit score.

Problem Statement

You are tasked with developing a loan eligibility checker. The eligibility criteria are as follows:

  • The applicant must have a minimum income of $30,000.
  • The applicant must have a credit score of at least 650.

Solution

Here’s how you can implement this logic in JavaScript:

function checkLoanEligibility(income, creditScore) {
    const minimumIncome = 30000;
    const minimumCreditScore = 650;

    if (income >= minimumIncome && creditScore >= minimumCreditScore) {
        return true; // Eligible for loan
    } else {
        return false; // Not eligible for loan
    }
}

// Example usage
const income = 35000; // $35,000 annual income
const creditScore = 700; // Credit score of 700
const isEligible = checkLoanEligibility(income, creditScore);
console.log(`Loan eligibility: ${isEligible ? 'Eligible' : 'Not Eligible'}`);

Explanation

  • We define a function checkLoanEligibility that takes income and creditScore as parameters.
  • We use a simple if statement with logical operators to check if both conditions are met.
  • The function returns true if the applicant is eligible for the loan and false otherwise.

Practical Example 4: Calculating Compound Interest

Compound interest is another financial calculation that is widely used. It involves calculating interest on both the initial principal and the accumulated interest from previous periods.

Problem Statement

You need to calculate the compound interest for an investment. The formula for compound interest is:

$$ A = P \left(1 + \frac{r}{n}\right)^{nt} $$

Where:

  • \( A \) is the amount of money accumulated after n years, including interest.
  • \( P \) is the principal amount.
  • \( r \) is the annual interest rate (decimal).
  • \( n \) is the number of times that interest is compounded per year.
  • \( t \) is the time in years.

Solution

Here’s how you can implement this calculation in JavaScript:

function calculateCompoundInterest(principal, rate, timesCompounded, years) {
    const amount = principal * Math.pow((1 + rate / timesCompounded), timesCompounded * years);
    return amount.toFixed(2); // Round to two decimal places
}

// Example usage
const principal = 1000; // $1000
const rate = 0.05; // 5% annual interest rate
const timesCompounded = 4; // Compounded quarterly
const years = 5; // 5 years
const totalAmount = calculateCompoundInterest(principal, rate, timesCompounded, years);
console.log(`The total amount after compound interest is $${totalAmount}`);

Explanation

  • We define a function calculateCompoundInterest that takes principal, rate, timesCompounded, and years as parameters.
  • We use the compound interest formula to calculate the total amount.
  • We round the result to two decimal places using toFixed(2).

Practical Example 5: Evaluating Expressions for Tax Calculation

Tax calculation is a common requirement in many applications, especially those related to finance and payroll.

Problem Statement

You need to calculate the tax payable based on an income slab. The tax rates are as follows:

  • 10% for income up to $10,000
  • 20% for income between $10,001 and $20,000
  • 30% for income above $20,000

Solution

Here’s how you can implement this tax calculation in JavaScript:

function calculateTax(income) {
    let tax;
    if (income <= 10000) {
        tax = income * 0.10;
    } else if (income <= 20000) {
        tax = 10000 * 0.10 + (income - 10000) * 0.20;
    } else {
        tax = 10000 * 0.10 + 10000 * 0.20 + (income - 20000) * 0.30;
    }
    return tax.toFixed(2); // Round to two decimal places
}

// Example usage
const income = 25000; // $25,000 annual income
const taxPayable = calculateTax(income);
console.log(`The tax payable is $${taxPayable}`);

Explanation

  • We define a function calculateTax that takes income as a parameter.
  • We use conditional statements to determine the tax rate based on the income slab.
  • We calculate the tax payable and round the result to two decimal places.

Practical Example 6: Evaluating Expressions for BMI Calculation

Body Mass Index (BMI) is a simple calculation used to assess whether a person has a healthy body weight for a given height.

Problem Statement

You need to calculate the BMI for a person using the formula:

$$ \text{BMI} = \frac{\text{Weight in kilograms}}{(\text{Height in meters})^2} $$

Solution

Here’s how you can implement this calculation in JavaScript:

function calculateBMI(weight, height) {
    const bmi = weight / Math.pow(height, 2);
    return bmi.toFixed(2); // Round to two decimal places
}

// Example usage
const weight = 70; // 70 kg
const height = 1.75; // 1.75 meters
const bmi = calculateBMI(weight, height);
console.log(`The BMI is ${bmi}`);

Explanation

  • We define a function calculateBMI that takes weight and height as parameters.
  • We use the BMI formula to calculate the BMI value.
  • We round the result to two decimal places using toFixed(2).

Practical Example 7: Evaluating Expressions for Currency Conversion

Currency conversion is a common task in applications that deal with international transactions.

Problem Statement

You need to convert an amount from one currency to another using a given exchange rate.

Solution

Here’s how you can implement this conversion in JavaScript:

function convertCurrency(amount, exchangeRate) {
    const convertedAmount = amount * exchangeRate;
    return convertedAmount.toFixed(2); // Round to two decimal places
}

// Example usage
const amount = 100; // $100
const exchangeRate = 0.85; // Exchange rate from USD to EUR
const convertedAmount = convertCurrency(amount, exchangeRate);
console.log(`The converted amount is €${convertedAmount}`);

Explanation

  • We define a function convertCurrency that takes amount and exchangeRate as parameters.
  • We multiply the amount by the exchange rate to get the converted amount.
  • We round the result to two decimal places using toFixed(2).

Practical Example 8: Evaluating Expressions for Temperature Conversion

Temperature conversion is a common task in applications that deal with weather data.

Problem Statement

You need to convert a temperature from Celsius to Fahrenheit using the formula:

$$ \text{Fahrenheit} = (\text{Celsius} \times \frac{9}{5}) + 32 $$

Solution

Here’s how you can implement this conversion in JavaScript:

function convertCelsiusToFahrenheit(celsius) {
    const fahrenheit = (celsius * 9/5) + 32;
    return fahrenheit.toFixed(2); // Round to two decimal places
}

// Example usage
const celsius = 25; // 25°C
const fahrenheit = convertCelsiusToFahrenheit(celsius);
console.log(`The temperature in Fahrenheit is ${fahrenheit}°F`);

Explanation

  • We define a function convertCelsiusToFahrenheit that takes celsius as a parameter.
  • We use the conversion formula to calculate the temperature in Fahrenheit.
  • We round the result to two decimal places using toFixed(2).

Practical Example 9: Evaluating Expressions for Distance Conversion

Distance conversion is a common task in applications that deal with geographical data.

Problem Statement

You need to convert a distance from kilometers to miles using the conversion factor:

$$ 1 \text{ kilometer} = 0.621371 \text{ miles} $$

Solution

Here’s how you can implement this conversion in JavaScript:

function convertKilometersToMiles(kilometers) {
    const miles = kilometers * 0.621371;
    return miles.toFixed(2); // Round to two decimal places
}

// Example usage
const kilometers = 10; // 10 km
const miles = convertKilometersToMiles(kilometers);
console.log(`The distance in miles is ${miles} miles`);

Explanation

  • We define a function convertKilometersToMiles that takes kilometers as a parameter.
  • We multiply the kilometers by the conversion factor to get the distance in miles.
  • We round the result to two decimal places using toFixed(2).

Practical Example 10: Evaluating Expressions for Age Calculation

Age calculation is a common task in applications that deal with personal data.

Problem Statement

You need to calculate a person’s age based on their birth year.

Solution

Here’s how you can implement this calculation in JavaScript:

function calculateAge(birthYear) {
    const currentYear = new Date().getFullYear();
    const age = currentYear - birthYear;
    return age;
}

// Example usage
const birthYear = 1990;
const age = calculateAge(birthYear);
console.log(`The person's age is ${age} years`);

Explanation

  • We define a function calculateAge that takes birthYear as a parameter.
  • We get the current year using new Date().getFullYear().
  • We subtract the birth year from the current year to calculate the age.

Conclusion

In this section, we explored a variety of practical examples that demonstrate how to write and evaluate expressions in JavaScript. These examples covered real-life scenarios such as calculating discounts, interest rates, tax, BMI, currency conversion, temperature conversion, distance conversion, and age calculation. By understanding these examples, you can apply similar logic to solve other problems in your JavaScript projects.

Quiz Time!

### What is the correct formula to calculate the final price after a discount? - [x] Final Price = Original Price - (Original Price * Discount Percentage / 100) - [ ] Final Price = Original Price + (Original Price * Discount Percentage / 100) - [ ] Final Price = Original Price * (1 - Discount Percentage / 100) - [ ] Final Price = Original Price / (1 + Discount Percentage / 100) > **Explanation:** The correct formula subtracts the discount amount from the original price. ### How do you round a number to two decimal places in JavaScript? - [x] Use the `toFixed(2)` method - [ ] Use the `Math.round()` method - [ ] Use the `toPrecision(2)` method - [ ] Use the `Math.floor()` method > **Explanation:** The `toFixed(2)` method rounds a number to two decimal places. ### Which of the following expressions correctly calculates simple interest? - [x] Simple Interest = (Principal * Rate * Time) / 100 - [ ] Simple Interest = Principal * (1 + Rate * Time) - [ ] Simple Interest = Principal * Rate * Time - [ ] Simple Interest = (Principal + Rate + Time) / 100 > **Explanation:** The correct formula for simple interest is (Principal * Rate * Time) / 100. ### What is the purpose of using logical operators in expressions? - [x] To combine multiple conditions - [ ] To perform arithmetic calculations - [ ] To convert data types - [ ] To declare variables > **Explanation:** Logical operators are used to combine multiple conditions in expressions. ### Which method is used to calculate the power of a number in JavaScript? - [x] `Math.pow(base, exponent)` - [ ] `Math.sqrt(base)` - [ ] `Math.exp(base)` - [ ] `Math.power(base, exponent)` > **Explanation:** The `Math.pow()` method is used to calculate the power of a number. ### How do you calculate compound interest in JavaScript? - [x] Use the formula: A = P * Math.pow((1 + r / n), n * t) - [ ] Use the formula: A = P * (1 + r * t) - [ ] Use the formula: A = P + (P * r * t) - [ ] Use the formula: A = P * Math.exp(r * t) > **Explanation:** The correct formula for compound interest is A = P * Math.pow((1 + r / n), n * t). ### What is the correct way to calculate BMI in JavaScript? - [x] BMI = weight / Math.pow(height, 2) - [ ] BMI = weight * height - [ ] BMI = weight / height - [ ] BMI = Math.sqrt(weight / height) > **Explanation:** The correct formula for BMI is weight divided by the square of height. ### Which conversion factor is used to convert kilometers to miles? - [x] 1 kilometer = 0.621371 miles - [ ] 1 kilometer = 1.60934 miles - [ ] 1 kilometer = 0.539957 miles - [ ] 1 kilometer = 0.868976 miles > **Explanation:** The correct conversion factor is 1 kilometer = 0.621371 miles. ### How do you get the current year in JavaScript? - [x] Use `new Date().getFullYear()` - [ ] Use `Date.now()` - [ ] Use `new Date().getYear()` - [ ] Use `new Date().getDate()` > **Explanation:** The `new Date().getFullYear()` method returns the current year. ### True or False: The `toFixed()` method can be used to round numbers to a specified number of decimal places. - [x] True - [ ] False > **Explanation:** The `toFixed()` method is used to format a number using fixed-point notation, rounding to the specified number of decimal places.
Sunday, October 27, 2024