Explore practical examples of JavaScript expressions with real-life scenarios like calculating discounts and interest rates. Learn to write and evaluate expressions effectively.
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.
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.
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.
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.
To solve this problem, we will use the following formula:
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}`);
calculateDiscountedPrice
that takes originalPrice
and discountPercentage
as parameters.toFixed(2)
method to round the final price to two decimal places.Another common scenario is calculating simple interest, which is often used in financial applications.
You are building a financial application that requires calculating the simple interest on a loan. The formula for simple interest is:
Where:
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}`);
calculateSimpleInterest
that takes principal
, rate
, and time
as parameters.toFixed(2)
.In this example, we’ll use expressions to evaluate whether a person is eligible for a loan based on their income and credit score.
You are tasked with developing a loan eligibility checker. The eligibility criteria are as follows:
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'}`);
checkLoanEligibility
that takes income
and creditScore
as parameters.if
statement with logical operators to check if both conditions are met.true
if the applicant is eligible for the loan and false
otherwise.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.
You need to calculate the compound interest for an investment. The formula for compound interest is:
Where:
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}`);
calculateCompoundInterest
that takes principal
, rate
, timesCompounded
, and years
as parameters.toFixed(2)
.Tax calculation is a common requirement in many applications, especially those related to finance and payroll.
You need to calculate the tax payable based on an income slab. The tax rates are as follows:
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}`);
calculateTax
that takes income
as a parameter.Body Mass Index (BMI) is a simple calculation used to assess whether a person has a healthy body weight for a given height.
You need to calculate the BMI for a person using the formula:
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}`);
calculateBMI
that takes weight
and height
as parameters.toFixed(2)
.Currency conversion is a common task in applications that deal with international transactions.
You need to convert an amount from one currency to another using a given exchange rate.
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}`);
convertCurrency
that takes amount
and exchangeRate
as parameters.toFixed(2)
.Temperature conversion is a common task in applications that deal with weather data.
You need to convert a temperature from Celsius to Fahrenheit using the formula:
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`);
convertCelsiusToFahrenheit
that takes celsius
as a parameter.toFixed(2)
.Distance conversion is a common task in applications that deal with geographical data.
You need to convert a distance from kilometers to miles using the conversion factor:
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`);
convertKilometersToMiles
that takes kilometers
as a parameter.toFixed(2)
.Age calculation is a common task in applications that deal with personal data.
You need to calculate a person’s age based on their birth year.
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`);
calculateAge
that takes birthYear
as a parameter.new Date().getFullYear()
.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.